0% found this document useful (0 votes)
12 views98 pages

PP&DS 1

The document provides a comprehensive overview of Python programming, covering its introduction, applications, features, and history. It highlights Python's ease of use, versatility across various domains, and comparisons with other programming languages. Additionally, it discusses the structure of Python code, including keywords, variables, data types, and the importance of indentation and comments.

Uploaded by

shatviklakshman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views98 pages

PP&DS 1

The document provides a comprehensive overview of Python programming, covering its introduction, applications, features, and history. It highlights Python's ease of use, versatility across various domains, and comparisons with other programming languages. Additionally, it discusses the structure of Python code, including keywords, variables, data types, and the importance of indentation and comments.

Uploaded by

shatviklakshman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

PYTHON PROGRAMMING

CONTENTS
• Introduction to python
• Applications of python
• IDEs
• Introduction to python interpreter
• Indentation and comments
• Keywords
• Variables – identifiers
• Built– in types
• Assigning values to variables
• Input and output statements
• Operators
• Control structures
• Math & random modules
• List
• Tuple
• Strings
• Set
• Dictionary
• Functions
• Files
• Libraries in python
INTRODUCTION TO PYTHON

1.WHY PYTHON ?

Because it's
• Easy
• Short
• High-level language(many features build-in or in libraries)
• Able to do many things (servers, ai, data analysis, raspberry pi,
gui, desktop apps, image/language processing, etc.)
• Great structured, making you able to write extremely complex
programs easy understandable and simple
• Object oriented and functional at the same time
• Extendable and able to work with many other technologies
• Much more…
2.DIFFERENCE BETWEEN C ,C++,JAVA AND PYTHON

C C++ JAVA PYTHON


Language type Procedure Object oriented Object oriented Both Procedu
oriented language language Object orient
language language
Building Block Function Driven Object Driven Both Object & Function, Ob
Class Driven Class Driven
Extension .C .Cpp .Java .Py
Platform Dependent Independent Independent Independent
Comment Style /* Multi Lines */ /* Multi Lines */ /* Multi Lines */ , # Single Line
, // Single Line , // Single Line // Single Line “””multi lines
Translation Type Compiled Compiled Compiled Interpreted
&Interpreted
Database Not Supported Not Supported Not Supported Supported
Connectivity
Representing { } { } { } Indentation
Block of
Statements
Declaring Required Required Required Not Required
Variables
Applications Compilers, Simple Desktop Desktop GUI, Desktop , We
interpreters... etc Applications Mobile, Web, gamming,
Gamming... etc Network
programming
...etc
IDE Turbo C, Code Turbo C++, Code Eclipse, NetBeans Pycharm, Pyd
Blocks Blocks ...etc ,Jupyter,
Anakonda ...

3.FEATURES OF PYTHON
There are many features in Python, some of which are discussed below –
I. Easy to code:
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is
very easy to code in python language and anybody can learn python basics in a
few hours or days. It is also a developer-friendly language.

II. Free and Open Source:


Python language is freely available at the official website and you can
download it from the given download link below click on the Download
Python keyword.Since it is open-source, this means that source code is also
available to the public. So you can download it as, use it as well as share it.

III. Object-Oriented Language:


One of the key features of python is Object-Oriented programming. Python
supports object-oriented language and concepts of classes, objects
encapsulation, etc.

IV. GUI Programming Support:


Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python. PyQt5 is the most popular option for creating
graphical apps with Python.

V. High-Level Language:
Python is a high-level language. When we write programs in python, we do not
need to remember the system architecture, nor do we need to manage the
memory.

VI. Extensible feature:


Python is a Extensible language. We can write us some Python code into C or
C++ language and also we can compile that code in C/C++ language.

VII. Python is Portable language:


Python language is also a portable language. For example, if we have python
code for windows and if we want to run this code on other platforms such as
Linux, Unix, and Mac then we do not need to change it, we can run this code
on any platform.

VIII. Python is Integrated language:


Python is also an Integrated language because we can easily integrated python
with other languages like c, c++, etc.

IX. Interpreted Language:


Python is an Interpreted Language because Python code is executed line by
line at a time. like other languages C, C++, Java, etc. there is no need to
compile python code this makes it easier to debug our code. The source code
of python is converted into an immediate form called bytecode.

X. Large Standard Library


Python has a large standard library which provides a rich set of module and
functions so you do not have to write your own code for every single thing.
There are many libraries present in python for such as regular expressions,
unit-testing, web browsers, etc.

XI. Dynamically Typed Language:


Python is a dynamically-typed language. That means the type (for example-
int, double, long, etc.) for a variable is decided at run time not in advance
because of this feature we don’t need to specify the type of variable.
4.HISTORY OF PYTHON
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido
Van Rossum at CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version
0.9.0) to alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map,
filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage
collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It
was designed to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python
language, which was capable of Exception Handling and interfacing with
the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3

APPLICATIONS OF PYTHON

Python is known for its general-purpose nature that makes it


applicable in almost every domain of software development.
Python makes its presence in every emerging field. It is the
fastest-growing programming language and can develop any
application.

Here, we are specifying application areas where Python can be


applied.
1) Web Applications

We can use Python to develop web applications. It provides


libraries to handle internet protocols such as HTML and XML,
JSON, Email processing, request, beautifulSoup, Feedparser,
etc. One of Python web-framework named Django is used
on Instagram. Python provides many useful frameworks, and
these are given below:

o Django and Pyramid framework(Use for heavy


applications)
o Flask and Bottle (Micro-framework)
o Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications

The GUI stands for the Graphical User Interface, which


provides a smooth interaction to any application. Python
provides a Tk GUI library to develop a user interface. Some
popular GUI libraries are given below.
o Tkinter or Tk
o wxWidgetM
o Kivy (used for writing multitouch applications )
o PyQt or Pyside

3) Console-based Application

Console-based applications run from the command-line or


shell. These applications are computer program which are used
commands to execute. This kind of application was more
popular in the old generation of computers. Python can develop
this kind of application very effectively. It is famous for having
REPL, which means the Read-Eval-Print Loop that makes it
the most suitable language for the command-line applications.

4) Software Development

Python is useful for the software development process. It works


as a support language and can be used to build control and
management, testing, etc.

o SCons is used to build control.


o Buildbot and Apache Gumps are used for automated
continuous compilation and testing.
o Round or Trac for bug tracking and project management.

5) Scientific and Numeric

Python language is the most suitable language for Artificial


intelligence or machine learning. It consists of many scientific
and mathematical libraries, which makes easy to solve complex
calculations.

Implementing machine learning algorithms require complex


mathematical calculation. Python has many libraries for
scientific and numeric such as Numpy, Pandas, Scipy, Scikit-
learn, etc.
If you have some basic knowledge of Python, you need to
import libraries on the top of the code. Few popular
frameworks of machine libraries are given below.

o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib

6) Business Applications

Business Applications differ from standard applications. E-


commerce and ERP are an example of a business application.
This kind of application requires extensively, scalability and
readability, and Python provides all these features.

Oddo is an example of the all-in-one Python-based application


which offers a range of business applications. Python provides
a Tryton platform which is used to develop the business
application.

7) Audio or Video-based Applications

Python is flexible to perform multiple tasks and can be used to


create multimedia applications. Some multimedia applications
which are made by using Python are TimPlayer, cplay, etc.
The few multimedia libraries are given below.

o Gstreamer
o Pyglet
o QT Phonon

8) 3D CAD Applications

The CAD (Computer-aided design) is used to design


engineering related architecture. It is used to develop the 3D
representation of a part of a system. Python can create a 3D
CAD application by using the following functionalities.
o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM

9) Enterprise Applications

Python can be used to create applications that can be used


within an Enterprise or an Organization. Some real-time
applications are OpenERP, Tryton, Picalo, etc.

10) Image Processing Application

Python contains many libraries that are used to work with the
image. The image can be manipulated according to our
requirements. Some libraries of image processing are given
below.

o OpenCV
o Pillow
o SimpleITK

INTEGRATED DEVELOPMENT ENVIRONMENT (IDEs)


INTRODUCTION TO PYTHON INTERPRETER

INTERPRETER

Interpreter is a program that converts the high level language into the
bit format i.e. machine language. The function of the interpreter and
compiler is the same but the interpreter translates one line at a time and
executes it. No object code is produced so every time when the program has
to be run it is to be interpreted first.
INDENTATION AND COMMENTS

INDENTATION
Most of the programming languages like C, C++, and Java use braces { } to
define a block of code. Python, however, uses indentation. A code block (body
of a function, loop, etc.) starts with indentation and ends with the first
unindented line. Generally, four whitespaces are used for indentation and are
preferred over tabs. Here is an example.

for i in range(1,11):
print(i)
if i == 5:
break

COMMENTS

Comments are very important while writing a program.

In Python, we use the hash (#) symbol to start writing a comment.

#print out Hello


print('Hello')

Multi-line comments

We can have comments that extend up to multiple lines. One way is to use the
hash(#) symbol at the beginning of each line. For example:

#This is a long comment


#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are used for multi-line comments

"""This is also a
perfect example of
multi-line comments"""

KEYWORDS
keywords are reserved words. The keywords Which cannot be used as the
function name, variable name, and any identifier name, etc. Each keyword
has a specific meaning. In Python, except True, False and None All
keywords are case sensitive

False class finally is return


None continue for lambda try

True def from nonlocal while

And del global not with

As elif if or yield

Assert else import pass

Break except in raise

.
No. Keywords Descripti
on

This is a logical operator it returns true if both


1 And the operands are true else return false.

This is also a logical operator it returns true if


2 Or anyone operand is true else return false.

This is again a logical operator it returns True if


3 Not the operand is false else return false.

4 If This is used to make a conditional statement.

Elif is a condition statement used with if


statement the elif statement is executed if the
5 Elif previous conditions were not true

Else is used with if and elif conditional statement


the else block is executed if the given condition
6 Else is not true.

7 For This is created for a loop.


No. Keywords Descripti
on

8 While This keyword is used to create a while loop.

9 Break This is used to terminate the loop.

10 As This is used to create an alternative.

11 Def It helps us to define functions.

12 Lambda It used to define the anonymous function.

This is a null statement that means it will do


13 Pass nothing.

14 Return It will return a value and exit the function.

15 True This is a boolean value.

16 False This is also a boolean value.

17 Try It makes a try-except statement.

The with keyword is used to simplify exception


18 With handling.

This function is used for debugging purposes.


19 Assert Usually used to check the correctness of code

20 Class It helps us to define a class.

21 continue It continues to the next iteration of a loop

22 Del It deletes a reference to an object.


No. Keywords Descripti
on

Used with exceptions, what to do when an


23 Except exception occurs

Finally is use with exceptions, a block of code


that will be executed no matter if there is an
24 Finally exception or not.

The form is used to import specific parts of any


25 From module.

26 Global This declares a global variable.

27 Import This is used to import a module.

It’s used to check if a value is present in a list,


28 In tuple, etc, or not.

This is used to check if the two variables are


29 Is equal or not.

This is a special constant used to denote a null


value or avoid. It’s important to remember, 0,
any empty container(e.g empty list) do not
30 None compute to None

31 nonlocal It’s declared a non-local variable.

32 Raise This raises an exception

33 Yield It’s ends a function and returns a generator.

VARIABLES – IDENTIFIERS
The identifier is a name used to identify a variable, function, class,
module, etc. The identifier is a combination of character digits and
underscore. The identifier should start with a character or Underscore then
use digit. The characters are A-Z or a-z,a UnderScore ( _ ) and digit (0-9). we
should not use special characters ( #, @, $, %, ! ) in identifiers.
Examples of valid identifiers:
1. var1
2. _var1
3. _1_var
4. var_1
Examples of invalid identifiers
1. !var1
2. 1var
3. 1_var
4. var#1

BUILT– IN TYPES / DATA TYPES

Data types are the classification or categorization of data items. It


represents the kind of value that tells what operations can be performed on a
particular data. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these
classes.
Following are the standard or built-in data type of Python:

• Numeric

• Sequence Type

• Boolean

• Set

• Dictionary
In Python, numeric data type represents the data which has numeric
value. Numeric value can be integer, floating number or even complex
numbers. These values are defined as int, float and complex class in
Python.

• Integers – This value is represented by int class. It contains positive or


negative whole numbers (without fraction or decimal). In Python there is
no limit to how long an integer value can be.
• Float – This value is represented by float class. It is a real number with
floating point representation. It is specified by a decimal point. Optionally,
the character e or E followed by a positive or negative integer may be
appended to specify scientific notation.

• Complex Numbers – Complex number is represented by complex class.


It is specified as (real part) + (imaginary part)j. For example – 2+3j

Note – type() function is used to determine the type of data type.


# Python program to

# demonstrate numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

Output:

Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>

SEQUENCE TYPE
In Python, sequence is the ordered collection of similar or different
data types. Sequences allows to store multiple values in an organized and
efficient fashion. There are several sequence types in Python –

• String

• List

• Tuple
STRING
A string is a collection of one or more characters put in a single quote,
double-quote or triple quote. In python there is no character data type, a
character is a string of length one. It is represented by str class.

CREATING STRING
Strings in Python can be created using single quotes or double quotes or even
triple quotes.

# Python Program for

# Creating a String

# with single Quotes

String1 = 'Welcome to Siddartha Engineering College'

print("String with the use of Single Quotes: ")

print(String1)

# Creating a String

# with double Quotes

String1 = "Anand Reddy"

print("\n String with the use of Double Quotes: ")

print(String1)

print(type(String1))

# Creating a String

# with triple Quotes


String1 = '''I'm an Indian"'''

print("\n String with the use of Triple Quotes: ")

print(String1)

print(type(String1))

# Creating String with triple

# Quotes allows multiple lines

String1 = '''All

Is

Well'''

print("\nCreating a multiline String: ")

print(String1)

Output:

String with the use of Single Quotes:


Welcome to Siddartha Engineering College

String with the use of Double Quotes:


Anand Reddy
<class 'str'>

String with the use of Triple Quotes:


I'm an Indian
<class 'str'>

Creating a multiline String:


All
Is
Well

ACCESSING ELEMENTS OF STRING


In Python, individual characters of a String can be accessed by using the
method of Indexing. Indexing allows negative address references to access
characters from the back of the String, e.g. -1 refers to the last character, -2
refers to the second last character and so on.

S I D D A R T H A
0 1 2 3 4 5 6 7
8
-9 -8 -7 -6 -5 -4 -3 -2
-1

# Python Program to Access


# characters of String
String1 = "SIDDARTHA"
print("Initial String: ")
print(String1)

# Printing First character


print("\n First character of String is: ")
print(String1[0])

# Printing Last character


print("\n Last character of String is: ")
print(String1[-1])

Output:

Initial String: SIDDARTHA

First character of String is: S

Last character of String is: A

LIST
Lists are just like the arrays, declared in other languages which is an
ordered collection of data. It is very flexible as the items in a list do not need
to be of the same type.
CREATING LIST
Lists in Python can be created by just placing the sequence inside the square
brackets[ ].

# Python program to demonstrate


# Creation of List

# Creating a List
List = [ ]
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['Computer Science And Engineering']
print("\n List with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["Computer", "Science", "And" “Engineering”]
print("\n List containing multiple values: ")
print(List[0])
print(List[3])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Computerscience', 'And'], ['Engineering']]
print("\n Multi-Dimensional List: ")
print(List)
Output:

Intial blank List: [ ]

List with the use of String:

['Computer Science And Engineering']

List containing multiple values:

Computer

Engineering

Multi-Dimensional List:

[['Computerscience', 'And'], ['Engineering']]

ACCESSING ELEMENTS OF LIST


In order to access the list items refer to the index number. Use the index
operator
[ ] to access an item in a list. In Python, negative sequence indexes represent
positions from the end of the array. Negative indexing means beginning from
the end, -1 refers to the last item, -2 refers to the second-last item, etc.

# Python program to demonstrate


# accessing of element from list
# Creating a List with
# the use of multiple values

List = ["Siddartha", "For", "CSE"]

# accessing a element from the


# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])
# accessing a element using
# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

Output:

Accessing element from the list


Siddartha
CSE
Accessing element using negative indexing
CSE
Siddartha

TUPLE
Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e. tuples
cannot be modified after it is created. It is represented by tuple class.
CREATING TUPLE
In Python, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of the data
sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, list, etc.).

Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a
trailing ‘comma’ to make it a tuple.

# Python program to demonstrate


# creation of Set
# Creating an empty tuple
Tuple1 = ( )
print("Initial empty Tuple: ")
print (Tuple1)

# Creating a Tuple with


# the use of Strings
Tuple1 = ('CSE', 'For')
print("\n Tuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\n Tuple using List: ")
print(tuple(list1))

# Creating a Tuple with the


# use of built-in function
Tuple1 = tuple('CSE')
print("\nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'CSE')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

Output:

Initial empty Tuple:


()

Tuple with the use of String:


('CSE', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('C', 'S', 'E')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'CSE'))

Note – Creation of Python tuple without the use of parentheses is known as


Tuple Packing.

ACCESSING ELEMENTS OF TUPLE


In order to access the tuple items refer to the index number. Use the index
operator [ ] to access an item in a tuple. The index must be an integer. Nested
tuples are accessed using nested indexing.

# Python program to
# demonstrate accessing tuple
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("Frist element of tuple")
print(tuple1[0])
# Accessing element from last
# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-3])

Output:

Frist element of tuple


1

Last element of tuple


5

Third last element of tuple


3
Note – To know more about tuples, refer Python Tuples.

SEQUENCE TYPE
In Python, sequence is the ordered collection of similar or different
data types. Sequences allows to store multiple values in an organized and
efficient fashion. There are several sequence types in Python –

• String

• List

• Tuple
STRING
A string is a collection of one or more characters put in a single quote,
double-quote or triple quote. In python there is no character data type, a
character is a string of length one. It is represented by str class.

CREATING STRING
Strings in Python can be created using single quotes or double quotes or even
triple quotes.

# Python Program for

# Creation of String

# Creating a String

# with single Quotes

String1 = 'Welcome to Siddartha Engineering College'

print("String with the use of Single Quotes: ")

print(String1)

# Creating a String

# with double Quotes

String1 = "Anand Reddy"

print("\n String with the use of Double Quotes: ")

print(String1)

print(type(String1))

# Creating a String
# with triple Quotes

String1 = '''I'm an Indian"'''

print("\n String with the use of Triple Quotes: ")

print(String1)

print(type(String1))

# Creating String with triple

# Quotes allows multiple lines

String1 = '''All

Is

Well'''

print("\nCreating a multiline String: ")

print(String1)

Output:

String with the use of Single Quotes:


Welcome to Siddartha Engineering College

String with the use of Double Quotes:


Anand Reddy
<class 'str'>

String with the use of Triple Quotes:


I'm an Indian
<class 'str'>

Creating a multiline String:


All
Is
Well
ACCESSING ELEMENTS OF STRING

In Python, individual characters of a String can be accessed by using the


method of Indexing. Indexing allows negative address references to access
characters from the back of the String, e.g. -1 refers to the last character, -2
refers to the second last character and so on.

S I D D A R T H A
0 1 2 3 4 5 6 7
8
-9 -8 -7 -6 -5 -4 -3 -2
-1

# Python Program to Access


# characters of String
String1 = "SIDDARTHA"
print("Initial String: ")
print(String1)

# Printing First character


print("\n First character of String is: ")
print(String1[0])

# Printing Last character


print("\n Last character of String is: ")
print(String1[-1])

Output:

Initial String: SIDDARTHA

First character of String is: S

Last character of String is: A


String Operators
Operator Description

+ It is known as concatenation operator used to join the strings given either s

of the operator.

* It is known as repetition operator. It concatenates the multiple copies of th

same string.

[] It is known as slice operator. It is used to access the sub-strings of a particul

string.

[:] It is known as range slice operator. It is used to access the characters from t

specified range.

in It is known as membership operator. It returns if a particular sub-string is

present in the specified string.

not in It is also a membership operator and does the exact reverse of in. It returns

true if a particular substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where

need to print the actual meaning of escape characters such as "C://python"

To define any string as a raw string, the character r or R is followed by the s

% It is used to perform string formatting. It makes use of the format specifiers

used in C programming like %d or %f to map their values in python.

We will discuss how formatting is done in python.


Example

Consider the following example to understand the real use of Python operators.

str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

Python String Methods

Python provides lots of built-in methods which we can use on strings.


Below are the list of string methods available in Python 3.

Method Description Examples

Returns a copy of the >>> mystring = "hello python"


capitalize()
string with its first >>> print(mystring.capitalize(
character capitalized Hello python
and the rest
lowercased.

Returns a casefolded >>> mystring = "hello PYTHON


copy of the string. >>> print(mystring.casefold())
Casefold() Casefolded strings may hello python
be used for caseless
matching.

Returns the string >>> mystring = "Hello"


centered in a string of >>> x = mystring.center(12,"-
length width. Padding >>> print(x)
can be done using the ---Hello----
specified fillchar (the
Center(width, [fillchar])
default padding uses
an ASCII space). The
original string is
returned if width is less
than or equal to len(s)

>>> mystr = "Hello Python"


>>> print(mystr.count("o"))
Returns the number of 2
non-overlapping >>> print(mystr.count("th"))
occurrences of 1
substring (sub) in the >>> print(mystr.count("l"))
Count(sub, [start], [end]) range [start, end]. 2
Optional >>> print(mystr.count("h"))
arguments startand en 1
d are interpreted as in >>> print(mystr.count("H"))
slice notation. 1
>>> print(mystr.count("hH"))
0

Returns an encoded >>> mystr = 'python!'


version of the string as >>> print('The string is:',mystr
Encode(encoding = “utf-g”, errors
a bytes object. The The string is: python!
= “strict”)
default encoding is utf- >>> print('The encoded versio
8. errors may be given ',mystr.encode("ascii","ignore
to set a different error The encoded version is:
handling scheme. The b'python!'
possible value for >>> print('The encoded
errors are: version (with replace) is:',
mystr.encode("ascii","replace
• strict (encoding The encoded version (with
errors raise replace) is: b'python!'
a UnicodeError)
• ignore
• replace
• xmlcharrefreplac
e
• backslashreplace
• any other name
registered via
codecs.register_
error()

>>> mystr = "Python"


Returns True if the >>>
string ends with the print(mystr.endswith("y"))
endswith(suffix, [start], [end]) specified suffix, False
otherwise it returns >>>
False. print(mystr.endswith("hon"))
True

>>> mystr = "1\t2\t3"


Returns a copy of the >>> print(mystr)
string where all tab 123
characters are replaced >>>
Expandtabs(tabsize=8) by one or more spaces, print(mystr.expandtabs())
depending on the 123
current column and >>>
the given tab size. print(mystr.expandtabs(tabsi
ze=15))
12
3
>>>
print(mystr.expandtabs(tabsi
ze=2))
123

>>> mystring = "Python"


Returns the lowest >>>
index in the string print(mystring.find("P"))
Find(sub, [start], [end]) where substring sub is 0
found within the slice >>>
s[start:end]. print(mystring.find("on"))
4

>>> print("{} and


{}".format("Apple",
"Banana"))
Performs a string
Apple and Banana
formatting operation.
>>> print("{1} and
The string on which
{0}".format("Apple",
Format(*args, **kwargs) this method is called
"Banana"))
can contain literal text
Banana and Apple
or replacement fields
>>> print("{lunch} and
delimited by braces {}.
{dinner}".format(lunch="Peas
", dinner="Beans"))
Peas and Beans

>>> lunch = {"Food":


"Pizza", "Drink": "Wine"}
>>> print("Lunch: {Food},
Similar to {Drink}".format_map(lunch))
format(**mapping), Lunch: Pizza, Wine
format_map(mapping) except that mapping is >>> class Default(dict):
used directly and not def __missing__(self,
copied to a dictionary. key):
return key
>>> lunch = {"Drink":
"Wine"}
>>> print("Lunch: {Food},
{Drink}".format_map(Default(
lunch)))
Lunch: Food, Wine

>>> mystr = "HelloPython"


>>> print(mystr.index("P"))
Searches the string for 5
a specified value and >>>
Index(sub, [start], [end])
returns the position of print(mystr.index("hon"))
where it was found 8
>>> print(mystr.index("o"))
4

>>> mystr = "HelloPython"


>>> print(mystr.isalnum())
True
Returns True if all >>> a = "123"
isalnum characters in the string >>> print(a.isalnum())
are alphanumeric True
>>> a= "$*%!!!"
>>> print(a.isalnum())
False

>>> mystr = "HelloPython"


>>> print(mystr.isalpha())
True
Returns True if all >>> a = "123"
Isalpha() characters in the string >>> print(a.isalpha())
are in the alphabet False
>>> a= "$*%!!!"
>>> print(a.isalpha())
False

Returns True if all >>> mystr = "HelloPython"


Isdecimal() characters in the string >>> print(mystr.isdecimal())
are decimals False
>>> a="1.23"
>>> print(a.isdecimal())
False
>>> c = u"\u00B2"
>>> print(c.isdecimal())
False
>>> c="133"
>>> print(c.isdecimal())
True

>>> c="133"
>>> print(c.isdigit())
True
Returns True if all >>> c = u"\u00B2"
Isdigit() characters in the string >>> print(c.isdigit())
are digits True
>>> a="1.23"
>>> print(a.isdigit())
False

>>> c="133"
>>> print(c.isidentifier())
False
>>> c="_user_123"
Returns True if the
isidentifier() >>> print(c.isidentifier())
string is an identifier
True
>>> c="Python"
>>> print(c.isidentifier())
True

>>> c="Python"
>>> print(c.islower())
False
Returns True if all
>>> c="_user_123"
Islower() characters in the string
>>> print(c.islower())
are lower case
True
>>> print(c.islower())
False
>>> c="133"
>>> print(c.isnumeric())
True
Returns True if all >>> c="_user_123"
Isnumeric() characters in the string >>> print(c.isnumeric())
are numeric False
>>> c="Python"
>>> print(c.isnumeric())
False

>>> c="133"
>>> print(c.isprintable())
True
Returns True if all >>> c="_user_123"
isprintable() characters in the string >>> print(c.isprintable())
are printable True
>>> c="\t"
>>> print(c.isprintable())
False

>>> c="133"
>>> print(c.isspace())
False
>>> c="Hello Python"
>>> print(c.isspace())
Returns True if all False
isspace() characters in the string 73
are whitespaces >>> c="Hello"
>>> print(c.isspace())
False
>>> c="\t"
>>> print(c.isspace())
True

Returns True if the >>> c="133"


istitle() string follows the rules >>> print(c.istitle())
of a title False
>>> c="Python"
>>> print(c.istitle())
True
>>> c="\t"
>>> print(c.istitle())
False

>>> c="Python"
>>> print(c.isupper())
False
Returns True if all >>> c="PYHTON"
isupper() characters in the string >>> print(c.isupper())
are upper case True
>>> c="\t"
>>> print(c.isupper())
False

>>> a ="-"
>>> print(a.join("123"))
1-2-3
Joins the elements of >>> a="Hello Python"
join(iterable) an iterable to the end >>> a="**"
of the string >>> print(a.join("Hello
Python"))
H**e**l**l**o**
**P**y**t**h**o**n

>>> a="Hello"
Returns a left justified >>> b = a.ljust(12, "_")
ljust(width[,fillchar])
version of the string >>> print(b)
Hello_______

>>> a = "Python"
Converts a string into
lower() >>> print(a.lower())
lower case
Python

>>> a = " Hello "


Returns a left trim
lstrip([chars]) >>> print(a.lstrip(), "!")
version of the string
Hello !
>>> frm = "SecretCode"
>>> to = "4203040540"
>>> trans_table =
Returns a translation
str.maketrans(frm,to)
maketrans(x[, y[, z]]) table to be used in
>>> sec_code = "Secret
translations
Code".translate(trans_table)
>>> print(sec_code)
400304 0540

>>> mystr = "Hello-Python"


>>> print(mystr.partition("-
"))
Returns a tuple where
('Hello', '-', 'Python')
partition(sep) the string is parted into
74
three parts
>>>
print(mystr.partition("."))
('Hello-Python', '', '')

>>> mystr = "Hello Python.


Hello Java. Hello C++."
>>>
print(mystr.replace("Hello",
Returns a string where "Bye"))
a specified value is Bye Python. Bye Java. Bye
replace(old, new[,count])
replaced with a C++.
specified value >>>
print(mystr.replace("Hello",
"Hell", 2))
Hell Python. Hell Java.
Hello C++.

>>> mystr = "Hello-Python"


Searches the string for >>> print(mystr.rfind("P"))
a specified value and 6
rfind(sub[, start[,end]]) returns the last >>> print(mystr.rfind("-"))
position of where it 5
was found >>> print(mystr.rfind("z"))
-1
>>> mystr = "Hello-Python"
>>> print(mystr.rindex("P"))
6
>>> print(mystr.rindex("-"))
Searches the string for 5
a specified value and >>> print(mystr.rindex("z"))
rindex(sub[, start[,end]]) returns the last Traceback (most recent call
position of where it last):
was found File "<pyshell#253>", line
1, in <module>
print(mystr.rindex("z"))
ValueError: substring not
found

>>> mystr = "Hello Python"


Returns the string right >>> mystr1 = mystr.rjust(20,
rjust(width[,fillchar]) justified in a string of "-")
length width. >>> print(mystr1)
--------Hello Python

>>> mystr = "Hello Python"


>>>
Returns a tuple where print(mystr.rpartition("."))
rpartition(sep) the string is parted into ('', '', 'Hello Python')
three parts >>> print(mystr.rpartition("
"))
('Hello', ' ', 'Python')

>>> mystr = "Hello Python"


>>> print(mystr.rsplit())
['Hello', 'Python']
Splits the string at the >>> mystr = "Hello-Python-
rsplit(sep=None, maxsplit=-1) specified separator, Hello"
and returns a list >>>
print(mystr.rsplit(sep="-",
maxsplit=1))
['Hello-Python', 'Hello']
>>> mystr = "Hello Python"
>>> print(mystr.rstrip(),
"!")
Hello Python !
>>> mystr = "------------
Hello Python-----------"
Returns a right trim >>> print(mystr.rstrip(), "-
rstrip([chars])
version of the string ")
------------Hello Python----
------- -
>>> print(mystr.rstrip(),
"_")
------------Hello Python----
------- _

>>> mystr = "Hello Python"


>>> print(mystr.split())
Splits the string at the
['Hello', 'Python']
split(sep=None, maxsplit=-1) specified separator,
>>> mystr1="Hello,,Python"
and returns a list
>>> print(mystr1.split(","))
['Hello', '', 'Python']

>>> mystr = "Hello:\n\n


Python\r\nJava\nC++\n"
>>>
print(mystr.splitlines())
['Hello:', '', ' Python',
Splits the string at line
'Java', 'C++']
splitlines([keepends]) breaks and returns a
>>>
list
print(mystr.splitlines(keepe
nds=True))
['Hello:\n', '\n', '
Python\r\n', 'Java\n',
'C++\n']

Returns true if the >>> mystr = "Hello Python"


startswith(prefix[,start[, end]]) string starts with the >>>
specified value print(mystr.startswith("P"))
False
>>>
print(mystr.startswith("H"))
True
>>>
print(mystr.startswith("Hell
"))
True

>>> mystr = "


Hello Python
"
>>> print(mystr.strip(),
Returns a trimmed
strip([chars]) "!")
version of the string
Hello Python !
>>> print(mystr.strip(), "
")
Hello Python

Swaps cases, lower >>> mystr = "Hello PYthon"


swapcase() case becomes upper >>> print(mystr.swapcase())
case and vice versa hELLO pyTHON

>>> mystr = "Hello PYthon"


>>> print(mystr.title())
Converts the first
Hello Python
title() character of each word
>>> mystr = "HELLO JAVA"
to upper case
>>> print(mystr.title())
Hello Java

>>> frm = "helloPython"


>>> to = "40250666333"
>>> trans_table =
Returns a translated str.maketrans(frm, to)
translate(table)
string >>> secret_code = "Secret
Code".translate(trans_table)
>>> print(secret_code)
S0cr06 C3d0
>>> mystr = "hello Python"
Converts a string into
upper() >>> print(mystr.upper())
upper case
HELLO PYTHON

>>> mystr = "999"


>>> print(mystr.zfill(9))
Fills the string with a
000000999
zfill(width) specified number of 0
>>> mystr = "-40"
values at the beginning
>>> print(mystr.zfill(5))
-0040

LIST
Lists are just like the arrays, declared in other languages which is an
ordered collection of data. It is very flexible as the items in a list do not need
to be of the same type.

CREATING LIST
Lists in Python can be created by just placing the sequence inside the square
brackets[ ].

# Python program to demonstrate


# Creation of List

# Creating a List
List = [ ]
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['Computer Science And Engineering']
print("\n List with the use of String: ")
print(List)
# Creating a List with
# the use of multiple values
List = ["Computer", "Science", "And" “Engineering”]
print("\n List containing multiple values: ")
print(List[0])
print(List[3])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Computerscience', 'And'], ['Engineering']]
print("\n Multi-Dimensional List: ")
print(List)

Output:
Intial blank List: [ ]

List with the use of String:

['Computer Science And Engineering']

List containing multiple values:

Computer

Engineering

Multi-Dimensional List:

[['Computerscience', 'And'], ['Engineering']]

ACCESSING ELEMENTS OF LIST


In order to access the list items refer to the index number. Use the index
operator
[ ] to access an item in a list. In Python, negative sequence indexes represent
positions from the end of the array. Negative indexing means beginning from
the end, -1 refers to the last item, -2 refers to the second-last item, etc.
# Python program to demonstrate
# accessing of element from list
# Creating a List with
# the use of multiple values

List = ["Siddartha", "For", "CSE"]

# accessing a element from the


# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])

# accessing a element using


# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

Output:

Accessing element from the list


Siddartha
CSE
Accessing element using negative indexing
CSE
Siddartha

TUPLE
Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e. tuples
cannot be modified after it is created. It is represented by tuple class.

CREATING TUPLE
In Python, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of the data
sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, list, etc.).

Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a
trailing ‘comma’ to make it a tuple.

# Python program to demonstrate


# creation of Set
# Creating an empty tuple
Tuple1 = ( )
print("Initial empty Tuple: ")
print (Tuple1)

# Creating a Tuple with


# the use of Strings
Tuple1 = ('CSE', 'For')
print("\n Tuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\n Tuple using List: ")
print(tuple(list1))

# Creating a Tuple with the


# use of built-in function
Tuple1 = tuple('CSE')
print("\nTuple with the use of function: ")
print(Tuple1)

# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'CSE')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

Output:

Initial empty Tuple:


()

Tuple with the use of String:


('CSE', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('C', 'S', 'E')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'CSE'))

Note – Creation of Python tuple without the use of parentheses is known as


Tuple Packing.

ACCESSING ELEMENTS OF TUPLE


In order to access the tuple items refer to the index number. Use the index
operator [ ] to access an item in a tuple. The index must be an integer. Nested
tuples are accessed using nested indexing.

# Python program to
# demonstrate accessing tuple
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("Frist element of tuple")
print(tuple1[0])
# Accessing element from last
# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-3])

Output:

Frist element of tuple


1

Last element of tuple


5

Third last element of tuple


3

Difference Between List and Tuple


Lists and Tuples are used to store one or more Python objects or data-types
sequentially. Both can store any data such as integer, float, string, and
dictionary. Lists and Tuples are similar in most factors but here we will describe
the main difference between them.

Let's discuss the main differences in the following points.

Representation Differences

The representation of the Lists and tuple is marginally different. List are
commonly enclosed with the square bracket [ ], and elements are comma-
separated element. Tuples are enclosed with parenthesis (), and elements are
separated by the comma. The parenthesis is optional to use, and these types of
tuples are called tuple packing.

Consider the following example.

list1 = ['Anand', 1, 2, 54.30, {'Name: ''Ant'}]


print(type(list))
tuple1 = ('Anand',5,8,31.9,[1,2,3])
print(type(tuple1))

Output:

<class 'list'>
<class 'tuple'>

In the above program, we defined a list1 variable which holds a list of


different data types . It is enclosed by the [ ].

We defined another variable tuple1, which holds a tuple of different data


types. It is enclosed by the ().

Mutable Lists and Immutable Tuples

It is the most important difference between list and tuple whereas lists
are mutable, and tuples are immutable. The lists are mutable which means the
Python object can be modified after creation, whereas tuples can't be modified
after creation.

Consider the given an example.

a = ["Computer","Science","And","Engineering"]
print(a)

Output: ["Computer","Science","And","Engineering"]

Now we are changing 0th index element "Computer" to "Python".

a[0] = "Python"
print(a)
Output: ['Python', 'Science', 'And', 'Engineering']

Now we create a tuple and do the same thing.


a = (10,20,"Siddartha",30,40)
print(a)

Output:

(10,20,"Siddartha",30,40)

a[0] = 50

Output:

TypeError Traceback (most recent call last)


<ipython-input-5-2143354fc192> in <module>
----> 1 a[0] = 50

TypeError: 'tuple' object does not support item assignment

We get an error while changing the 1st element of the tuple because of
immutability. It does not support item assignment.

BOOLEAN
Data type with one of the two built-in values, True or False. True and
False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an
error.

Booleans represent one of two values: True or False.

You can evaluate any expression in Python, and get one of two
answers, True or False.

When you compare two values, the expression is evaluated and Python returns
the Boolean answer:

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

Output:
True
False
False

# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))

Output:

<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "<string>", line 3, in <module>
NameError: name 'true' is not defined

SET
Set is an unordered collection of data type that is iterable, mutable
and has no duplicate elements. The order of elements in a set is undefined
though it may consist of various elements.

CREATING SETS
Sets can be created by using the built-in set( ) function with an iterable
object or a sequence by placing the sequence inside curly braces, separated by
‘comma’. Type of elements in a set need not be the same, various mixed-up
data type values can also be passed to the set.

# Python program to demonstrate


# Creation of Set in Python
# Creating a Set
set1 = set( )
print("Intial blank Set: ")
print(set1)
# Creating a Set with
# the use of a String
set1 = set(“CSE")
print("\n Set with the use of String: ")
print(set1)
# Creating a Set with
# the use of a List
set1 = set(["CSE", "For", "CSE"])
print("\n Set with the use of List: ")
print(set1)
# Creating a Set with
# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'CSE', 4, 'For', 6, 'CSE'])
print("\n Set with the use of Mixed Values")
print(set1)

Output:

Intial blank Set:


set()

Set with the use of String:


{'S', 'C', 'E'}

Set with the use of List:


{'For', 'CSE'}

Set with the use of Mixed Values


{1, 2, 4, 6, 'CSE', 'For'}
>

ACCESSING ELEMENTS OF SETS


Set items cannot be accessed by referring to an index, since sets are
unordered the items has no index. But you can loop through the set items
using a for loop, or ask if a specified value is present in a set, by using the
keyword.

# Python program to demonstrate


# Accessing of elements in a set
# Creating a set
set1 = set(["Siddartha", "For", "CSE"])
print("\n Initial set")
print(set1)
# Accessing element using
# for loop
print("\n Elements of set: ")
for i in set1:
print(i, end =" ")

# Checking the element


# using in keyword
print("Siddartha" in set1)

Output:

Initial set
{'Siddartha', 'For', 'CSE'}

Elements of set:
Siddartha For CSE True
>

DICTIONARY
Dictionary is an unordered collection of data values, used to store data
elements, Dictionary holds key:value pair. Each key-value pair in a Dictionary is
separated by a colon :, whereas each key is separated by a ‘comma’.

CREATING DICTIONARY
Dictionary can be created by placing a sequence of elements within
curly { } braces, separated by ‘comma’. Values in a dictionary can be of any
datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable. Dictionary can also be created by the built-in function dict( ). An
empty dictionary can be created by just placing it to curly braces{ }. Dictionary
keys are case sensitive, same name but different cases of Key will be treated
distinctly.

# Creating an empty Dictionary


Dict = { }
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Siddartha', 2: 'For', 3: 'CSE'}
print("\n Dictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Siddartha', 1: [1, 2, 3, 4]}
print("\n Dictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Siddartha', 2: 'For', 3:'CSE'})
print("\n Dictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'ANT'), (2, 'For')])
print("\n Dictionary with each item as a pair: ")
print(Dict)

Output:

Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Siddartha', 2: 'For', 3: 'CSE'}
Dictionary with the use of Mixed Keys:
{'Name': 'Siddartha', 1: [1, 2, 3, 4]}
Dictionary with the use of dict():
{1: 'Siddartha', 2: 'For', 3: 'CSE'}

Dictionary with each item as a pair:


{1: 'ANT', 2: 'For'}
>
ACCESSING ELEMENTS OF DICTIONARY

In order to access the items of a dictionary refer to its key name. Key can
be used inside square brackets. There is also a method called get( ) that will
also help in accessing the element from a dictionary.

# Python program to demonstrate


# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Anand', 'name': 'For', 3: 'ANT'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))

Output:

Accessing a element using key:


For
Accessing a element using get:
ANT
>

ASSIGNING VALUES TO VARIABLES


Python is a dynamically typed language. So, Python doesn't need an
explicit variable declaration to reserve memory. The variable declaration will
happen automatically when we assign value to it.
#Assigning value to variables

name = "Anand" #string value


age = 3 #integer value
price = 10.0 #float value
#Printing values
print(name)
print(age)
print(price)

Output:
Anand
3
10.0
>

MULTIPLE ASSIGNMENT IN PYTHON


We can assign the same object to multiple variables.

#Multiple assignment in python

num1 = num2 = num3 = 0 #initializing num1, num2, num3 to zero

print(num1, num2, num3)

Output: 0 0 0

MULTI-VALUE ASSIGNMENT IN PYTHON


We can also assign the multiple objects to multiple variables.

#Multi-value assignment in python

name, page_count, price = "Python", 300, 254.65


print(name, page_count, price)

Output:Python 300 254.65

INPUT AND OUTPUT STATEMENTS


Python provides numerous built-in functions that are available to us at
the Python prompt. Some of the functions like input( ) and print( ) are widely
used for standard input and output operations respectively.
PYTHON OUTPUT USING PRINT( ) FUNCTION

We use the print( ) function to output data to the standard output device
(screen).
Example :

print('This sentence is output to the screen')

Output

This sentence is output to the screen

Another example is given below:

a=5
print('The value of a is', a)

Output
The value of a is 5
Example

print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output

1234
1*2*3*4
1#2#3#4&

OUTPUT FORMATTING

Sometimes we would like to format our output to make it look attractive.


This can be done by using the str.format() method. This method is visible to any
string object.

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
# OUTPUT: The value of x is 5 and y is 10

Here, the curly braces {} are used as placeholders. We can specify the order in
which they are printed by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))


print('I love {1} and {0}'.format('bread','butter'))

Output

I love bread and butter


I love butter and bread

PYTHON INPUT

The syntax for input ( ) is:

# Taking input from the user


name = input("Enter your name: ")
# Output
print("Hello, " + name)
Output:
Enter your name: anand
Hello, anand
>

Example:
# Taking input from the user as integer
num = int(input("Enter a number: "))

add = num + 1

# Output
print(add)
Output:
Enter a number: 9
10

OPERATORS
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Relational operators /Comparison Operators
• Logical operators
• Bitwise operators
• Assignment Operators
• Special Operators/Identity Operators
• Membership Operators

1. ARITHMETIC OPERATORS:
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.

OPERATOR DESCRIPTION SYNTAX


+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x-y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

Modulus: returns the remainder when first operand is divided by


% the second x%y

x **
** Power : Returns first raised to power second y

# Examples of Arithmetic Operator


a=9
b=4

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Division(float) of number
div1 = a / b

# Division(floor) of number
div2 = a // b

# Modulo of both number


mod = a % b

# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)

OUTPUT:
13
5
36
2.25
2
1
6561
2. RELATIONAL OPERATORS:
Relational operators compares the values. It either
returns True or False according to the condition.

OPERATOR DESCRIPTION SYNTAX


> Greater than: True if left operand is greater than the right x>y

< Less than: True if left operand is less than the right x<y
== Equal to: True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to: True if left operand is greater than


>= or equal to the right x >= y

Less than or equal to: True if left operand is less than or


<= equal to the right x <= y

# Examples of Relational Operators


a = 13
b = 33
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)

OUTPUT: False True False True False True

3. LOGICAL OPERATORS:

Logical operators perform Logical AND, Logical OR and Logical


NOT operations.

OPERATOR DESCRIPTION SYNTAX


And Logical AND: True if both the operands are true x and y
Or Logical OR: True if either of the operands is true x or y

Not Logical NOT: True if operand is false not x

# Examples of Logical Operator


a = True
b = False

# Print a and b is False


print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False


print(not a)

Output:
False
True
False

4. BITWISE OPERATORS:

Bitwise operators works on bits and performs bit by bit operation.


p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

OPERATOR DESCRIPTION SYNTAX


& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

# Examples of Bitwise operators


a = 10
b=4

# Print bitwise AND operation


print(a & b)

# Print bitwise OR operation


print(a | b)
# Print bitwise NOT operation
print(~a)

# print bitwise XOR operation


print(a ^ b)

# print bitwise right shift operation


print(a >> 2)

# print bitwise left shift operation


print(a << 2)

OUTPUT:
0
14
-11
14
2
40

5. ASSIGNMENT OPERATORS:

Assignment operators are used to assign values to the variables.

OPERATOR DESCRIPTION SYNTAX


Assign value of right side of expression to left side
= operand x=y+z

Add AND: Add right side operand with left side


+= operand and then assign to left operand a+=b a=a+b

Subtract AND: Subtract right operand from left


-= operand and then assign to left operand a-=b a=a-b

Multiply AND: Multiply right operand with left


*= operand and then assign to left operand a*=b a=a*b
Divide AND: Divide left operand with right operand
/= and then assign to left operand a/=b a=a/b

Modulus AND: Takes modulus using left and right


%= operands and assign result to left operand a%=b a=a%b

Divide(floor) AND: Divide left operand with right


operand and then assign the value(floor) to left
//= operand a//=b a=a//b

Exponent AND: Calculate exponent(raise power)


value using operands and assign value to left
**= operand a**=b a=a**b

Performs Bitwise AND on operands and assign


&= value to left operand a&=b a=a&b

Performs Bitwise OR on operands and assign value


|= to left operand a|=b a=a|b

Performs Bitwise xOR on operands and assign value


^= to left operand a^=b a=a^b

Performs Bitwise right shift on operands and assign


>>= value to left operand a>>=b a=a>>b

Performs Bitwise left shift on operands and assign a <<= b a=


<<= value to left operand a << b
1) Assign: This operator is used to assign the value of the right side of the
expression to the left side operand.
Syntax:
x=y+z
Example:

# Assigning values using


# Assignment Operator
a=3
b=5
c=a+b
print(c)

Output:
8
2) Add and Assign: This operator is used to add the right side operand with the
left side operand and then assigning the result to the left operand.
Syntax:
x += y
Example:

a=3
b=5
#a=a+b
a += b
print(a)

Output: 8
3) Subtract and Assign: This operator is used to subtract the right operand
from the left operand and then assigning the result to the left operand.
Syntax:
x -= y
Example :

a=3
b=5
#a=a-b
a -= b
print(a)

Output:
-2

4) Multiply and Assign: This operator is used to multiply the right operand
with the left operand and then assigning the result to the left operand.
Syntax:
x *= y
Example:

a=3
b=5
#a=a*b
a *= b
print(a)

Output:
15

5) Divide and Assign: This operator is used to divide the left operand with the
right operand and then assigning the result to the left operand.
Syntax:
x /= y
Example:

a=3
b=5
#a=a/b
a /= b
print(a)

Output:
0.6
6) Modulus and Assign: This operator is used to take the modulus using the
left and the right operands and then assigning the result to the left operand.
Syntax:
x %= y
Example:

a=3
b=5
#a=a%b
a %= b
print(a)

Output:
3
7) Divide (floor) and Assign: This operator is used to divide the left operand
with the right operand and then assigning the result(floor) to the left operand.
Syntax:
x //= y
Example:
a=3
b=5
# a = a // b
a //= b
print(a)

Output:
0
8) Exponent and Assign: This operator is used to calculate the exponent(raise
power) value using operands and then assigning the result to the left operand.
Syntax:
x **= y
Example:

a=3
b=5
# a = a ** b
a **= b
print(a)

Output:
243
9) Bitwise AND and Assign: This operator is used to perform Bitwise AND on
both operands and then assigning the result to the left operand.

Syntax:
x &= y
Example:

a=3
b=5
#a=a&b
a &= b
print(a)

Output:
1
10) Bitwise OR and Assign: This operator is used to perform Bitwise OR on the
operands and then assigning result to the left operand.
Syntax:
x |= y
Example:

a=3
b=5
#a=a|b
a |= b
print(a)

Output:
7

11) Bitwise XOR and Assign: This operator is used to perform Bitwise XOR on
the operands and then assigning result to the left operand.
Syntax:
x ^= y
Example:

a=3
b=5
#a=a^b
a ^= b
print(a)

Output:
6
12) Bitwise Right Shift and Assign: This operator is used to perform Bitwise
right shift on the operands and then assigning result to the left operand.
Syntax:
x >>= y
Example:

a=3
b=5
# a = a >> b
a >>= b
print(a)

Output:
0
13) Bitwise Left Shift and Assign: This operator is used to perform Bitwise left
shift on the operands and then assigning result to the left operand.
Syntax:
x <<= y
Example:

a=3
b=5
# a = a << b
a <<= b
print(a)

Output:
96

6. SPECIAL OPERATORS:

There are some special type of operators like-Identity operators


(is and is not) are the identity operators both are used to check if two
values are located on the same part of the memory.

Is True if the operands are identical


is not True if the operands are not identical

‘is’ operator – Evaluates to true if the variables on either side of the operator
point to the same object and false otherwise.

# Python program to illustrate the use


# of 'is' identity operator
x=5
if (type(x) is int):
print("true")
else:
print("false")

Output:
true
‘is not’ operator – Evaluates to false if the variables on either side of the
operator point to the same object and true otherwise.

# Python program to illustrate the


# use of 'is not' identity operator
x = 5.2
if (type(x) is not int):
print("true")
else:
print("false")

Output:
true

7. MEMBERSHIP OPERATORS
in and not in are the membership operators; used to test whether a
value or variable is in a sequence.

in True if value is found in the sequence

not in True if value is not found in the sequence

in operator : The ‘in’ operator is used to check if a value exists in a sequence


or not. Evaluates to true if it finds a variable in the specified sequence and
false otherwise.

# Python program to illustrate


# Finding common member in list
# using 'in' operator
list1=[1,2,3,4,5]
list2=[6,7,8,9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")

Output:
not overlapping

‘not in’ operator- Evaluates to true if it does not finds a variable in the
specified sequence and false otherwise.
x = ["apple", "banana"]
print("pineapple" not in x)

Output: True

3. Repetition/Loop Control Statements

A repetition statement is used to repeat a group(block) of programming


instructions.

In Python, we generally have two loops/repetitive statements:

• for loop
• while loop
for loop:
The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects.
Syntax of for Loop

for x in variable:
print(x)

for val in sequence:


Body of for
Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.

Example:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

Output:

apple
banana
cherry

Example:

# Program to find the sum of all numbers stored in a list


# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)

Output:The sum is 48
The range() function

We can generate a sequence of numbers


using range() function. range(10) will generate numbers from 0 to 9 (10
numbers).
We can also define the start, stop and step size as range(start,
stop,step_size). step_size defaults to 1 if not provided.

Example:

print(range(10))

print(list(range(10)))

print(list(range(2, 8)))

print(list(range(2, 20, 3)))

Output:
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
for loop with else

A for loop can have an optional else block as well. The else part is
executed if the items in the sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is
ignored.
Hence, a for loop's else part runs if no break occurs

Example:

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output:

0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts.
When the for loop exhausts, it executes the block of code in the else and
prints No items left.
This for...else statement can be used with the break keyword to run
the else block only when the break keyword was not executed.
Example:
# program to display student's marks from record
student_name = 'Baldev'
marks = {'Anand': 90, 'Ram': 55, 'Bhavmanyu': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')
Output:
No entry with that name found.

Example:

# Python program to illustrate


# Iterating over a list
print("List Iteration")
l = ["Siddartha", "for", "CSE"]
for i in l:
print(i)

# Iterating over a tuple (immutable)


print("\nTuple Iteration")
t = ("Computers", "for", "Engineers")
for i in t:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "Bhavmanyu"
for i in s :
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))

Output:
List Iteration
Siddartha
for
CSE

Tuple Iteration
Computers
for
Engineers

String Iteration
B
h
a
v
m
a
n
y
u
Dictionary Iteration
xyz 123
abc 345

Iterating by index of sequences:


We can also use the index of elements in the sequence to iterate. The key
idea is to first calculate the length of the list and in iterate over the sequence
within the range of this length.

Example:

# Python program to illustrate


# Iterating by index

list = ["Bhavmanyu", "Anand", "Ram","Baldev"]


for index in range(len(list)):
print(list[index])

Output:
Bhavmanyu
Anand
Ram
Baldev

Pass statement
In Python, we use the pass statement to implement stubs.
When we need a particular loop, class, or function in our program,
but don’t know what goes in it, we place the pass statement in it.
It is a null statement. The interpreter does not ignore it, but it
performs a no-operation (NOP).
Example
for i in 'selfhelp':
pass
print(i)
Output:
P

Continue Statement: It returns the control to the beginning of the loop.

Example:

# Prints all letters except 'a' and 't'


for letter in 'Mahabharat':
if letter == 'a' or letter == 't':
continue
print ('Current Letter :', letter)
var = 10

Output:
Current Letter : M
Current Letter : h
Current Letter : b
Current Letter : h
Current Letter : r

Nested for Loops

Python programming language allows to use one loop inside another loop.
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

Example:
persons = [ "Ram", "Bhavmanyu", "Arjun", "Dev" ]
restaurants = [ "Japanese", "American", "Mexican", "French" ]

for person in persons:


for restaurant in restaurants:
print(person + " eats " + restaurant)

Output:
Ram eats Japanese
Ram eats American
Ram eats Mexican
Ram eats French
Bhavmanyu eats Japanese
Bhavmanyu eats American
Bhavmanyu eats Mexican
Bhavmanyu eats French
Arjun eats Japanese
Arjun eats American
Arjun eats Mexican
Arjun eats French
Dev eats Japanese
Dev eats American
Dev eats Mexican
Dev eats French
while loop:

In Python, while loops are used to execute a block of statements repeatedly


until a given condition is satisfied. Then, the expression is checked again and, if
it is still true, the body is executed again. This continues until the expression
becomes false.

Syntax :

while expression:
statement(s)

Example:

# Python program to illustrate


# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello World")

Output:
Hello World
Hello World
Hello World

Example:
i=1
while i < 6:
print(i)
i += 1
Output:
1
2
3
4
5
The break Statement

With the break statement we can stop the loop even if the while condition
is true:

Example:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3

The continue Statement

With the continue statement we can stop the current iteration, and continue
with the next:

Example:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
3
4
5
6
The else Statement

With the else statement we can run a block of code once when the
condition no longer is true:

Example:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output:
1
2
3
4
5
i is no longer less than 6

Math & Random modules

Math Modules
The math module is a standard module in Python and is always
available. To use mathematical functions under this module, you have to import
the module using import math.

All methods of these functions are used for integer or real type objects, not for
complex numbers.

To use math module, we should import that module into our code.

import math
Some Constants
These constants are used to put them into our calculations.

SNo Constants & Description

1 Pi Return the value of pi: 3.141592

2 E Return the value of natural base e. e is 0.718282

3 Tau Returns the value of tau. tau = 6.283185

4 Inf Returns the infinite

5 Nan Not a number type.

Pi constant:

The math.pi constant returns the value pi: 3.14159265359. It is defined


as the ratio of the circumference to the diameter of a circle.

Example:
# Import math Library
import math
# Print the value of pi
print (math.pi)
Output:
3.141592653589793
E constant:

The math.e constant returns the Euler’s number: 2.71828182846.

Example:
# Import math Library
import math
# Print the value of Euler e
print (math.e)
Output:
2.718281828459045
Tau constant:

The math.tau constant returns the value tau: 6.283185307179586. It is


defined as the ratio of the circumference to the radius of a circle.

# Import math Library


import math
# Print the value of tau
print (math.tau)
Output:
6.283185307179586
Inf constant:

The math.inf constant returns of positive infinity.For negative infinity, use


-math.inf.

Example:
# Import math Library
import math
# Print the positive infinity
print (math.inf)
# Print the negative infinity
print (-math.inf)
Output:
inf
-inf
Nan constant:

The math.nan constant returns a floating-point nan (Not a Number)


value. This value is not a legal number.The nan constant is equivalent to
float(“nan”).
# Import math Library
import math
# Print the value of nan
print (math.nan)
Output:

nan
Numbers and Numeric Representation
These functions are used to represent numbers in different forms.

SNo. Function & Description

1 ceil(x) Return the Ceiling value.It is the smallest integer,greater or equal to the num
x.

2 copysign(x, y) It returns the number x and copy the sign of y to x.

3 fabs(x) Returns the absolute value of x.

4 factorial(x) Returns factorial of x. where x ≥ 0

5 floor(x) Return the Floor value. It is the largest integer, less or equal to the numbe

6 fsum(iterable) Find sum of the elements in an iterable object

7 gcd(x, y) Returns the Greatest Common Divisor of x and y

8 remainder(x, y) Find remainder after dividing x by y.

ceil() :
This function returns the smallest integral value greater than the number.
If number is already integer, same number is returned.
floor() :
This function returns the greatest integral value smaller than the number.
If number is already integer, same number is returned.

Example:
# Python code to demonstrate the working of
# ceil() and floor()
# importing "math" for mathematical operations
import math
a = 2.3
# returning the ceil of 2.3
print ("The ceil of 2.3 is : ", end="")
print (math.ceil(a))

# returning the floor of 2.3


print ("The floor of 2.3 is : ", end="")
print (math.floor(a))
Output:
The ceil of 2.3 is : 3
The floor of 2.3 is : 2
fabs() :
This function returns the absolute value of the number.

factorial() :
This function returns the factorial of the number. An error message is
displayed if number is not integral.

Example:
# Python code to demonstrate the working of
# fabs() and factorial()
# importing "math" for mathematical operations
import math
a = -10
b= 5
# returning the absolute value.
print ("The absolute value of -10 is : ", end="")
print (math.fabs(a))

# returning the factorial of 5


print ("The factorial of 5 is : ", end="")
print (math.factorial(b))
Output:
The absolute value of -10 is : 10.0
The factorial of 5 is : 120

copysign(a, b) :
This function returns the number with the value of ‘a’ but with the sign of ‘b’. The retu
value is float type.
gcd() :
This function is used to compute the greatest common divisor of 2 numbers mentione
arguments.

Example:
# Python code to demonstrate the working of
# copysign() and gcd()
# importing "math" for mathematical operations
import math
a = -10
b = 5.5
c = 15
d=5
# returning the copysigned value.
print ("The copysigned value of -10 and 5.5 is : ", end="")
print (math.copysign(5.5, -10))
# returning the gcd of 15 and 5
print ("The gcd of 5 and 15 is : ", end="")
print (math.gcd(5,15))
Output:
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5

fsum(iterable) :
Find sum of the elements in an iterable object

Example:
# Import math Library
import math
# Print the sum of all items
print(math.fsum([1, 2, 3, 4, 5]))
print(math.fsum([100, 400, 340, 500]))
print(math.fsum([1.7, 0.3, 1.5, 4.5]))
Output:
15.0
1340.0
8.0
remainder(x, y)
Find remainder after dividing x by y.
Example:
# Import math Library
import math
# Return the remainder of x/y
print (math.remainder(9, 2))
print (math.remainder(9, 3))
print (math.remainder(18, 4))
Output:
1.0
0.0
2.0
Power and Logarithmic Functions
These functions are used to calculate different power related and logarithmic
related tasks.

SNo. Function & Description

1 pow(x, y) Return the x to the power y value.

2 sqrt(x) Finds the square root of x

3 exp(x) Finds xe, where e = 2.718281

4 log(x[, base]) Returns the Log of x, where base is given. The default base is e

5 log2(x) Returns the Log of x, where base is 2

6 log10(x) Returns the Log of x, where base is 10

exp(a) :
This function returns the value of e raised to the power a (e**a) .
log(a, b) :
This function returns the logarithmic value of a with base b. If base is not
mentioned, the computed value is of natural log.
EXAMPLE:

# Python code to demonstrate the working of


# exp() and log()
# importing "math" for mathematical operations
import math
# returning the exp of 4
print ("The e**4 value is : ", end="")
print (math.exp(4))

# returning the log of 2,3


print ("The value of log 2 with base 3 is : ", end="")
print (math.log(2,3))
Output:
The e**4 value is : 54.598150033144236
The value of log 2 with base 3 is : 0.6309297535714574
log2(a) :
This function computes value of log a with base 2.

log10(a) :
This function computes value of log a with base 10.
Example:
# Python code to demonstrate the working of
# log2() and log10()

# importing "math" for mathematical operations


import math
# returning the log2 of 16
print ("The value of log2 of 16 is : ", end="")
print (math.log2(16))

# returning the log10 of 10000


print ("The value of log10 of 10000 is : ", end="")
print (math.log10(10000))
Output:
The value of log2 of 16 is : 4.0
The value of log10 of 10000 is : 4.0
pow(a, b) :
This function is used to compute value of a raised to the power b (a**b).
sqrt():
This function returns the square root of the number.
Example:
# Python code to demonstrate the working of
# pow() and sqrt()

# importing "math" for mathematical operations


import math

# returning the value of 3**2


print ("The value of 3 to the power 2 is : ", end="")
print (math.pow(3,2))

# returning the square root of 25


print ("The value of square root of 25 : ", end="")
print (math.sqrt(25))
Output:
The value of 3 to the power 2 is : 9.0
The value of square root of 25 : 5.0
Trigonometric & Angular Conversion Functions
These functions are used to calculate different trigonometric operations.

Sr.No. Function & Description

1 sin(x) Return the sine of x in radians

2 cos(x) Return the cosine of x in radians

3 tan(x) Return the tangent of x in radians

4 asin(x) This is the inverse operation of the sine, there are acos, atan also.
5 degrees(x) Convert angle x from radian to degrees

6 radians(x) Convert angle x from degrees to radian

sin() :
This function returns the sine of value passed as argument. The value
passed in this function should be in radians.
cos() :
This function returns the cosine of value passed as argument. The value
passed in this function should be in radians.

Example:
# Python code to demonstrate the working of
# sin() and cos()
# importing "math" for mathematical operations
import math
a = math.pi/6
# returning the value of sine of pi/6
print ("The value of sine of pi/6 is : ", end="")
print (math.sin(a))

# returning the value of cosine of pi/6


print ("The value of cosine of pi/6 is : ", end="")
print (math.cos(a))
Output:
The value of sine of pi/6 is : 0.49999999999999994
The value of cosine of pi/6 is : 0.8660254037844387
tan() :
This function returns the tangent of value passed as argument. The value
passed in this function should be in radians.

Example:
# Python code to demonstrate the working of
# tan()
# importing "math" for mathematical operations
import math
a = math.pi/6
b=3
c=4
# returning the value of tangent of pi/6
print ("The value of tangent of pi/6 is : ", end="")
print (math.tan(a))
Output:
The value of tangent of pi/6 is : 0.5773502691896257
degrees() :
This function is used to convert argument value from radians to degrees.

radians() :
This function is used to convert argument value from degrees to radians.
Example:
# Python code to demonstrate the working of
# degrees() and radians()
# importing "math" for mathematical operations
import math
a = math.pi/6
b = 30
# returning the converted value from radians to degrees
print ("The converted value from radians to degrees is : ", end="")
print (math.degrees(a))

# returning the converted value from degrees to radians


print ("The converted value from degrees to radians is : ", end="")
print (math.radians(b))
Output:
The converted value from radians to degrees is : 29.999999999999996
The converted value from degrees to radians is : 0.5235987755982988
Random Modules
choice() :
choice() is an in built function in the Python programming language that
returns a random item from a list, tuple, or string.

Example:
# Python3 program to demonstrate the use of
# choice() method
# import random
import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))
# prints a random item from the string
string = "Anand"
print(random.choice(string))
Output:
5
t

randrange(beg, end, step):


The random module offers a function that can generate random
numbers from a specified range and also allowing rooms for steps to be
included, called randrange().

# Python code to demonstrate the working of


#randrange()
# importing "random" for random operations
import random
# using randrange() to generate in range from 20
# to 50. The last parameter 3 is step size to skip
# three numbers when selecting.
print("A random number from range is : ", end="")
print(random.randrange(20, 50, 3))
Output:

A random number from list is : 4


A random number from range is : 41
random():
This method is used to generate a float random number less than 1 and
greater or equal to 0.

Example:

import random
random.seed()
print(random.random())

Output:

0.7051535963024892

shuffle():
It is used to shuffle a sequence (list). Shuffling means changing the
position of the elements of the sequence.

Example:
# import the random module
import random
# declare a list
sample_list = ['A', 'B', 'C', 'D', 'E']
print("Original list : ")
print(sample_list)
# first shuffle
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)
Output:
Original list :
['A', 'B', 'C', 'D', 'E']

After the first shuffle :


['A', 'B', 'E', 'C', 'D']
After the second shuffle :
['C', 'E', 'B', 'D', 'A']
uniform(a, b):
This function is used to generate a floating point random number
between the numbers mentioned in its arguments. It takes two arguments,
lower limit(included in generation) and upper limit(not included in
generation).
# Python code to demonstrate the working of
# shuffle() and
import random
# using uniform() to generate random floating number in range
# prints number between 5 and 10
print("The random floating point number between 5 and 10 is : ", end="")
print(random.uniform(5, 10))
Output:

The random floating point number between 5 and 10 is : 7.92861916447321


85

You might also like