0% found this document useful (0 votes)
43 views268 pages

Python UNIT-1 - 240323 - 213721

Uploaded by

addy6056
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)
43 views268 pages

Python UNIT-1 - 240323 - 213721

Uploaded by

addy6056
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/ 268

Unit-1

Introduction to Python
• Python is a general purpose high-level, interpreted, interactive and object-oriented
scripting language.
• It uses English keywords frequently where as other languages use punctuation, and it
has fewer syntactical constructions than other languages therefore It is very simple
and easy to use
• Python is recommended as first programming language for beginners.

Eg: To print Helloworld:


Java:
public class HelloWorld
{
public static void main (String args[])
{
System.out.println ("Java Hello World");
}
}
In C:
#include<stdio.h>
void main()
{
print("Hello world");
}

In Python:
print("Hello World")
History of Python

• Python was developed by Guido Van Rossam in 1989 while working at


National Research Institute at Netherlands.

• But officially Python was made available to public in 1991. The official Date
of Birth for Python is : Feb 20th 1991.

• Python is derived from many other languages, including ABC, Modula-3, C,


C++, Algol-68, SmallTalk, Unix shell, and other scripting languages.
• Guido developed Python language by taking almost all
programming features from different languages
1. Functional Programming Features from C
2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4. Modular Programming Features from Modula-3
5. Most of syntax in Python Derived from C and ABC languages.
Where we can use Python:
We can use everywhere. The most common important application areas are
1. For developing Desktop Applications
2. For developing web Applications
3. For developing database Applications
4. For Network Programming
5. For developing games
6. For Data Analysis Applications
7. For Machine Learning
8. For developing Artificial Intelligence Applications
9. For IOT
Who Uses Python Today?
1. Google makes extensive use of Python in its web search systems.
2. The popular YouTube video sharing service is largely written in Python.
3. The Dropbox storage service codes both its server and desktop client
software primarily in Python.
4. The Raspberry Pi single-board computer promotes Python as its
educational language.
5. The widespread BitTorrent peer-to-peer file sharing system began its life
as a Python program.
6. Google‘s App Engine web development framework uses Python as an
application language.
7. Maya, a powerful integrated 3D modeling and animation system,
provides a Python scripting API.
8. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python
for hardware testing.
9. NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific
programming tasks.
Features of Python
• Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
• There are lot of features provided by python programming language. Some
features of python are given below;
1. Easy to Use
2. High Level Language
3. Expressive Language
4. Interpreted
5. Platform Independent
6. Open Source
7. Object-Oriented language
8. Huge Standard Library
9. GUI Programming
10.Integrated
Python Features
1) Easy to Learn and Use
• Python is easy to learn and use. It is developer-friendly and high level
programming language.
2) Expressive Language
• Python language is more expressive means that it is more understandable
and readable.
3) Interpreted Language
• Python is an interpreted language i.e. interpreter executes the code line by
line at a time. This makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
• Python can run equally on different platforms such as Windows, Linux, Unix
and Macintosh etc. So, we can say that Python is a portable language.
5) Free and Open Source
• Python language is freely available at www.python.org.The source-
code is also available. Therefore it is open source.

6) Object-Oriented Language
• Python supports object oriented language and concepts of classes
and objects come into existence.

7) Extensible
• Extensible. If needed, you can write some of your Python code in
other languages like C++. This makes Python an extensible language,
meaning that it can be extended to other languages.
8) Large Standard Library
• Python has a large and broad library and provides rich set of module and
functions for rapid application development.

9) GUI Programming Support


• Graphical user interfaces can be developed using Python.

10) Integrated
• It can be easily integrated with languages like C, C++, JAVA etc.
• Limitations of Python:
1. Performance wise not up to the mark b'z it is interpreted language.
2. Not using for mobile Applications. Disadvantages of Python
3. Python is not as fast as C and C++, It means it is slower than C/C++:
4. Does not check variable type at compile time. It use dynamic type so flexible that
Python interpreter cannot check the type for mismatch at the compile time.

Flavors of Python:
1.CPython:
• It is the standard flavor of Python. It can be used to work with C language
Applications.

2.Jython or JPython:
• It is for Java Applications. It can run on JVM.

3. IronPython:
• It is for C#.Net platform.
4.PyPy:
• The main advantage of PyPy is performance will be improved because JIT
compiler is available inside PVM.

5.Ruby Python:
• For Ruby Platforms.

6. Anaconda Python :
• It is specially designed for handling large volume of data processing.
Python Versions:
• Python 1.0V introduced in Jan 1994.
• Python 2.0V introduced in October 2000.
• Python 3.0V introduced in December 2008.

Note: Python 3 won't provide backward compatibility to Python2 i.e. there is no


guarantee that Python2 programs will run in Python3.

Current versions:
• Python 3.7.4 July 8, 2019
• Python 2.7.16 March 4, 2019
Other Versions:
• Python 3.6.9 July 2, 2019
• Python 2.7.15 May 1, 2018
• Python 3.6.1 March 21, 2017
• Python 2.7.13 April 9, 2012
The two versions Python 2 and Python 3 are very much different from each other.
A list of differences between Python 2 and Python 3 are given below:
• Python 2 uses print as a statement and used as print "something" to print some
string on the console.
• On the other hand, Python 3 uses print as a function and used as
print("something") to print something on the console.
• Python 2 uses the function raw_input() to accept the user's input. It returns the
string representing the value, which is typed by the user.
• To convert it into the integer, we need to use the int() function in Python.
• On the other hand, Python 3 uses input() function.
• In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit
string type is Unicode.
Difference between python 2 and 3
#Python 2

print "hello"
print ("hello world")
n=input("enter no1:")
n1=input("enter no 2:")
a=n+n1
b=n-n1
print a
print b
C:\Python27>python add.py
hello
hello world
enter no1:6
enter no 2:7
13
-1
Ex. Python 3
print ("hello")
a=input("enter no")
b=input("enter no")
c=a+b
print (c)

>>>
==== RESTART: C:/Users/HP50/AppData/Local/Programs/Python/Python38-
32/add.py ===
hello
enter no6
enter no7
67
>>>
print ("hello")
a=int(input("enter no"))
b=int(input("enter no"))
c=a+b
print (c)
c=a-b
print(c)

>>>
==== RESTART: C:/Users/HP50/AppData/Local/Programs/Python/Python38-32/add.py ===
hello
enter no2
enter no8
10
-6
>>>
How to Run Python Programs
• There are three way to execute python code they are given below;
1)Interactive Mode
2)Script Mode
3)Using IDE
1.Interactive interpreter prompt

• Python provides us the feature to execute the python


statement one by one at the interactive prompt. It is
preferable in the case where we are concerned about the
output of each line of our python program.
• To open the interactive mode, open the terminal (or
command prompt) and type python.
• It will open the following prompt where we can execute the
python statement and check their impact on the console.
Command-Line Options

When starting Python from the command-line, additional options may be


provided to the interpreter. Here are some of the options to choose from:
• -d Provide debug output
• -O Generate optimized bytecode (resulting in .pyo files)
• -S Do not run importsite to look for Python paths on startup
• -v Verbose output (detailed trace on import statements)
• -m mod run (library) module as a script
• -Q opt division options (see documentation)
• -c cmd Run Python script sent in as cmd string
• file Run Python script from given file (see later)
2.Using a script file
• Interpreter prompt is good to run the individual statements of the code.
However, we can not write the code every-time on the terminal.
• We need to write our code into a file which can be executed later. For this
purpose, open an editor like notepad, create a file named first.py (python
used .py extension) and write the following code in it.
Print ("hello world"); #here, we have used print() function to print the messag
e on the console.
• To run this file named as first.py, we need to run the following command on
the terminal.
• $ python first.py
• 3.General Editors and IDEs with Python Support
• Eclipse + PyDev
• Sublime Text
• Atom
• GNU Emacs
• Vi / Vim
• Visual Studio
• Visual Studio Code
• Python-Specific Editors and IDEs
• PyCharm
• Spyder
• Thonny
Byte code Compilation:
• Python first compiles your source code (the statements in
your file) into a format known as byte code.
• Compilation is simply a translation step, and byte code is a
lower-level, platform independent representation of your
source code.
• Roughly, Python translates each of your source statements
into a group of byte code instructions by decomposing
them into individual steps.
• This byte code translation is performed to speed execution
—byte code can be run much more quickly than the original
source code statements in your text file.
The Python Virtual Machine:
• Once your program has been compiled to byte code (or the byte code
has been loaded from existing .pyc file), it is shipped off for execution to
something generally known as the python virtual machine (PVM).
Variables in Python
• Variables are used for store data on memory location
• Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in
memory.
• Based on the data type of a variable, the interpreter allocates memory
and decides what can be stored in the reserved memory. Therefore, by
assigning different data types to variables, you can store integers,
decimals or characters in these variables.
• Variable names can be a group of both letters and digits, but they have
to begin with a letter or an underscore.
• It is recommended to use lowercase letters for variable name. Rahul and
rahul both are two different variables.
Identifier Naming
• Variables are the example of identifiers. An Identifier is used to identify the
literals used in the program. The rules to name an identifier are given below.
• The first character of the variable must be an alphabet or underscore ( _ ).
• All the characters except the first character may be an alphabet of lower-
case(a-z), upper-case (A-Z), underscore or digit (0-9).
• Identifier name must not contain any white-space, or special character (!, @,
#, %, ^, &, *).
• Identifier name must not be similar to any keyword defined in the language.
• Identifier names are case sensitive for example myname, and MyName is
not the same.
• Examples of valid identifiers : a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.
• Declaring Variable and Assigning Values
• Python does not bound us to declare variable before using in
the application. It allows us to create variable at required time.
• We don't need to declare explicitly variable in Python. When
we assign any value to the variable that variable is declared
automatically.
• The equal (=) operator is used to assign value to a variable.
Multiple Assignment
• Python allows us to assign a value to multiple variables in a single
statement which is also known as multiple assignment.
• We can apply multiple assignments in two ways either by assigning a
single value to multiple variables or assigning multiple values to
multiple variables.
• e.g. assigning a single value to several variables simultaneously.
a=b=c=1
• e.g assigning multiple objects to multiple variables simultaneously.
a, b, c = 1, 2.5, ”mothi”
example
a, b, c = 0.1, 100, 'string'
print(a)
print(b)
print(c)

Output:
C:\Python>python multiassn.py
0.1
100
string

C:\Python>
Keywords in Python

• The following list shows the Python keywords.


• These are reserved words, and you cannot use them as constant or
variable or any other identifier names.
• All the Python keywords contain lowercase letters only.
• In Python some words are reserved to represent some meaning or
functionality. Such type of words are called Reserved words.
• There are 33 reserved words available in Python.
1. True,False,None
2. and, or ,not,is
3. if,elif,else while,for,break,continue,return,in,yield
4. try,except,finally,raise,assert
5. import,from,as,class,def,pass,global,nonlocal,lambda,del,with

If want see the keyword list type the following


import keyword
keyword.kwlist
All Reserved words in Python contain only alphabet symbols.
Except the following 3 reserved words, all contain only lower case
alphabet symbols.
True, False,None
True False and
asset def None
as class from
continue break finally
global elif del
for if else
except import raise
pass return or
nonlocal try in
lambda is not
Input And Output Statements

Reading dynamic input from the keyboard:


• In Python 2 the following 2 functions are available to read dynamic
input from the keyboard.

• raw_input()
• input()
1.raw_input():
• This function always reads the data from the keyboard in the form
of String Format. We have to convert that string type to our
required type by using the corresponding type casting methods.

Eg:
• x=raw_input("Enter First Number:")
• print(type(x)) It will always print str type only for any input type
• raw_input() : the function raw_input() always evaluates and return
string type data.
Syntax : x=raw_input()
• If input value is integer type then it returns string value or convert
integer value into string value.
• If input value is string type then it returns string value.

• Note : But in python3 raw_input() function is not supported.


2. input():
• input() function can be used to read data directly in our required
format.
• We are not required to perform type casting.

• x=input("Enter Value”)
• Print(type(x))

• 10 ===> int
• “siva"===>str
• 10.5===>float
• True==>bool
• Note: But in Python 3 we have only input() method and raw_input()
method is not available.
Python3 input() function behaviour exactly same as raw_input() method
of Python2. i.e every input value is treated as str type only.
• raw_input() function of Python 2 is renamed as input() function in
Python3
Example:
type(input("Enter value:"))
Enter value:10
<class 'str'>
INPUT Function:
• To get input from the user you can use the input function.
• The syntax for input statements is
input([prompt])
• Here prompt is the string to display on the screen.
• it is optional.
• Whatever you enter as input, the input() function converts it into a
string. If you enter an integer value, still it will convert it into a string.
• If you want to input number from a user, you need to perform type
conversion on the input value.
Example
Output:
name = input("Enter Employee Name: ")
salary = input("Enter salary: ")
C:\Python>python in.py
company = input("Enter Company name: ")
Enter Employee Name: Maya
print("\n")
Enter salary: 40000
print("Printing Employee Details")
Enter Company name: BRECW
print("Name", "Salary", "Company")
print(name, salary, company)
Printing Employee Details
Name Salary Company
Maya 40000 BRECW

C:\Python>
number = input("Enter number ") Output:
name = input("Enter name ") C:\Python>python in1.py
print("\n") Enter number 4
print("Printing type of a input Enter name maya
value") Printing type of a input value
print("type of number", type of number <class 'str'>
type(number))
type of name <class 'str'>
print("type of name", type(name))

C:\Python>
Accept an Integer input from User

• Let’s see how to accept an integer value from a user in Python. We need to
convert an input string value into an integer using a int() function.
E.g.
first_number = int(input("Enter first number "))
second_number = int(input("Enter second number "))
print("\n")
print("First Number:", first_number)
print("Second Number:", second_number)
sum1 = first_number + second_number
print("Addition of two number is: ", sum1)
• Output:

Enter first number 20


Enter second number 40
First Number: 20
Second Number: 40
Addition of two number is: 60
Accept float input from User

• Let’s see how to accept float value from a user in Python. You need to
convert user input to the float number using the float() function as
we did for the integer value.

float_number = float(input("Enter float number "))


print("\n")
print("input float number is: ", float_number)
print("type is:", type(float_number))
Output:

Enter float number 29.5


input float number is: 29.5
type is: <class 'float'>
output statements:

• We can use print() function to display output.

Form-1: print() without any argument


• Just it prints new line character
•Form-2: print(String):

print("Hello World")

•We can use escape characters also


print("Hello \n World")
print("Hello\tWorld")

•We can use repetetion operator (*) in the string


print(10*"Hello")
print("Hello"*10)
•We can use + operator also
print("Hello"+"World")
Note:
• If both arguments are String type then + operator acts as concatenation
operator.
• If one argument is string type and second is any other type like int then
we will get Error .
• If both arguments are number type then + operator acts as arithmetic
addition operator.
print("Hello"+"World")
print("Hello","World")
HelloWorld
Hello World
Form-3: print() with variable number of arguments:
a,b,c=10,20,30
print("The Values are :",a,b,c)

Output:The Values are : 10 20 30

By default output values are seperated by space.If we want we can specify seperator
by using "sep" attribute

a,b,c=10,20,30
print(a,b,c,sep=',’)
print(a,b,c,sep=':’)

C:\Python>python test.py
10,20,30
10:20:30
• Form-4: print() with end attribute:
Example:
print("Hello")
print(“shiva")
print(“welcome")

Output:
Hello
Shiva
Welcome

The default value for end attribute is \n,which is nothing but new line
character.
• If we want output in the same line with space
Example:
print("Hello”,end=‘ ‘)
print(“shiva“,end=‘ ‘)
print(“welcome“)
Output:
Hello Shiva Welcome
• Form-5: print(object) statement:
We can pass any object (like list,tuple,set etc)as argument to the
print() statement
l=[10,20,30,40]
t=(10,20,30,40)
print(l)
print(t)
Form-6: print(formatted string):

%i====>int
%d====>int
%f=====>float
%s======>String type
Syntax:
print("formatted string" %(variable list))
Example:1
a=10
b=20
c=30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))

Output
a value is 10
b value is 20 and c value is 30
Example-2
s=“shiva"
list=[10,20,30,40]
print("Hello %s ...The List of Items are %s" %(s,list))

Output:
• Hello shiva ...The List of Items are [10, 20, 30, 40]
• Note: Python contains several inbuilt functions and In Python
everything is object

1.type()
to check the type of variable
2. id()
to get address of object
Python Data Types

• Variables can hold values of different data types.


• Python is a dynamically typed language hence we need not define the type
of the variable while declaring it.
• The interpreter implicitly binds the value with its type.
• Python has seven standard data types:
➢Numbers
➢Boolean
➢String
➢List
➢Tuple
➢Set
➢Dictionary
• Standard Types
1. Numbers (separate subtypes; three are integer types)
a. Integer
i.Boolean
ii.Long integer
b. Floating point real number
c. Complex number
2.String
3.List
4.Tuple
5.Dictionary
Other Built-in Types
• Type
• Null object (None)
• File
• Set/Frozenset
• Function/Method
• Module
• Class
Unsupported Types: list of types that are not supported by Python.

1.char or byte: Python does not have a char or byte type to hold either single
character or 8-bit integers. It uses Strings for character type and integer type to
represent 8 bit number.

2.Pointer
• Python manages memory automatically, there is no need to access pointer
addresses.
• The closest to an address that you can get in Python is by looking at an
object's identity using the id() BIF.
3.short and long
• Python's integers are the universal "standard" integer type, obviating the need
for three different integer types, e.g., C's int, short, and long.
• Python use a single type integer ,even when the size of an integer is exceeded.
So python not uses short and long types.
• It uses integer only instead of short and long.

4.Double:
• C has both a single precision float type and double-precision double type.
Python's float type is actually a C double.
• So python float is double-precision type.
Categorizing the Standard Types
• There are three different models to help categorize the standard types, with
each model showing us the interrelationships between the types.
• These models help us obtain a better understanding of how the types are
related, as well as how they work.

1.Storage Model
2.Update Model
3.Access Model
Storage Model:
• Categorization of the types is described by how many objects can be
stored in an object of this type.

• Most other languages can hold either single or multiple values.

• In python a type which holds a single literal object we will call atomic or
scalar storage.

• A type which can hold multiple objects we will refer to as container


storage. Container objects are also referred to as composite or
compound objects.

• All of Python's container types can hold objects of different types


Update Model:
• Python types early on indicated that certain types allow their values to
be updated and others do not.
• This model describes about the objects which can be changed, or can
their values be updated or not.
• Mutable objects are those whose values can be changed, and
immutable objects are those whose values cannot be changed.
# Python code to test that
# tuples are immutable

tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)

Traceback (most recent call last): File


"e0eaddff843a8695575daec34506f126.py", line 3, in tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
• # Python code to test that
# strings are immutable

message = "Welcome to python programming"


message[0] = 'p'
print(message)

Traceback (most recent call last): File


"/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p' TypeError: 'str' object does not support
item assignment
# Python code to test that
# lists are mutable
color = ["red", "blue", "green"]
print(color)

Output:
color[0] = "pink" ['red', 'blue', 'green']
color[-1] = "orange" ['pink', 'blue', 'orange']
print(color)
Access Model: previous two models of categorizing the types are useful when
being introduced to Python.
• They are not the primary models for differentiating the types.
• In order to access the stored values we use access model.
• Access Model is categorized in 3 types:

1.Direct : Direct types indicate single-element, non-container types. All numeric


types fit into this category.
2.Sequence: Sequence types are those whose elements are sequentially
accessible via index values starting at 0.
• Accessed items can be either single elements or in groups, better known as
slices. Types that fall into this category include strings, lists, and tuples.
3.Mapping: Mapping types are similar to the indexing properties of sequences,
except instead of indexing on a sequential numeric offset, elements (values) are
unordered and accessed with a key, thus making mapping types a set of hashed
key-value pairs.
Standard Type Built-in Functions:
• The functions which are coming along with Python software automatically,
are called built in functions or pre defined functions.
• cmp(),repr(),str(),type(), id(),input(),eval().
• Function Operation
• cmp(obj1, obj2) Compares obj1 and obj2, returns integer i where:
i < 0 if obj1 < obj2
i > 0 if obj1 > obj2
i == 0 if obj1 == obj2
• repr(obj) or `obj` Returns evaluatable string representation of obj
• str(obj) Returns printable string representation of obj
• type(obj) Determines type of obj and return type object
type()
• In Python versions earlier than 2.2, type() is a BIF. It is also known as "factory
function .
• The syntax for type() is:
type(object)
type() takes an object and returns its type. The return value is a type object.
>>> type(4) # int type
<type 'int'>
>>>
>>> type('Hello World!') # string type
<type 'string'>
>>>
>>> type(type(4)) # type type
<type 'type'>
cmp()
• The cmp() BIF CoMPares two objects, say, obj1 and obj2, and returns a
negative number (integer) if obj1 is less than obj2, a positive number if obj1 is
greater than obj2, and zero if obj1 is equal to obj2.
• Notice the similarity in return values as C's strcmp().
>>> a, b = -4, 12 >>> a, b = 'abc', 'xyz'
>>> cmp(a,b) >>> cmp(a,b)
-1 -23
>>> cmp(b,a)
>>> cmp(b,a)
23
1 >>> b = 'abc'
>>> b = -4 >>> cmp(a,b)
>>> cmp(a,b) 0
0
str() and repr() (and `` Operator)
The str() STRing and repr() REPResentation BIFs or the single back or reverse quote operator ( `` )
Str() used to convert other type values to str type.
>>> str(4.53-2j)
'(4.53-2j)‘

>>> str(1)
'1‘

>>> str(2e10)
'20000000000.0'

>>> str([0, 5, 9, 9])


'[0, 5, 9, 9]'
repr() returns a string containing a printable representation of object.
>>> repr([0, 5, 9, 9])
'[0, 5, 9, 9]'

>>> `[0, 5, 9, 9]`


'[0, 5, 9, 9]'
• s = 'Hello, World.'
• print str(s) string using repr() function then it prints with a
• print str(2.0/11.0) pair of quotes and if we calculate a value we get
more precise value than str() function
Output:
‘Hello, World.’
0.1818181818
Output:
s = 'Hello, World.' ‘Hello, World.’
print repr(s) 0.18181818182
print repr(2.0/11.0)
eval():
eval Function take a String and evaluate the Result.

Eg: x = eval(“10+20+30”)
print(x)
Output: 60

Eg: x = eval(input(“Enter Expression”))


Enter Expression: 10+2*3/4
Output11.5

Write a Program to accept list from the keyboard on the display


>>> x=eval(input("enter list"))
enter list[10,20,30]
>>> print(type(x))
<class 'list'>
>>> print(x)
[10, 20, 30]
Type Factory Functions
• The "conversion" built-in functions like int(), type(), list(), etc., are
now factory functions.
• They are actually classnames, and when you call one, you are actually
instantiating an instance of that type.
• The following familiar factory functions were used to create function
objects.
int(), long(), float(), complex()
str(), list(), tuple(), type()
Data Type Conversion
• Sometimes, you may need to perform conversions between
the built-in types. To convert between types, you simply use
the type name as a function.
• int(x)-Converts x to an integer.
• float(x) -Converts x to float.
• str(x) -Converts x to string.
• tuple(s)-Converts s to tuple.
• hex(x)-Converts an integer to a hexadecimal string.
• Python enables us to check the type of the variable used in the program.
Python provides us the type() function which returns the type of the
variable passed.

• Consider the following example to define the values of different data


types and checking its type.
A=10
b="Hi Python"
c = 10.5
print(type(a));
print(type(b));
print(type(c));
Output:
<type 'int’>
<type 'str’>
<type 'float'>
Numbers
• Python supports four different numerical types:
➢int (signed integers)
➢long (long integers, they can also be represented in octal
and hexadecimal)
➢float (floating point real values)
➢complex (complex numbers)
Numbers
Program:
a=3
Output:
b = 2.65 C:\Python>python num.py
c = 98657412345 int is 3
d = 2+5j float is 2.65
print ("int is",a) long is 98657412345
print ("float is",b) complex is (2+5j)
print ("long is",c)
print ("complex is",d) C:\Python>
Boolean
• Booleans are identified by True or False.

Program:
a = True Output:
b = False True
print(a) False
print(b)
Strings
• Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.
• Python allows for either pairs of single or double quotes.
s1=‘geetha govindam'
s1=“vijayadevarakonda"
• By using single quotes or double quotes we cannot represent
multi line string literals.
s1=“abc
pqrstuv”
For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
s1=''‘siva
bhargav'''
s1=""“siva
bhargav""“
We can also use triple quotes to use single quote or double quote in our String.
''' This is " character'''
' This i " Character '
We can embed one string in another string
'''This "Python class very helpful" for java students'''
• Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and working
their way from -1 at the end.
• We can do the negative slicing in the string; it starts from the rightmost
character, which is indicated as -1. The second rightmost index indicates -
2, and so on. Consider the following image.
Strings
Program: Output:
str ="WELCOME" C:\Python>python str1.py
print(str) WELCOME
W
print(str[0])
LCO
print(str[2:5]) LCOME
print(str[2:]) WELCOMEWELCOME
print(str * 2) WELCOMEIT
print (str + "IT")
C:\Python>
Strings Methods

• capitalize()
str1=“hello"
print(str1.capitalize()) # Hello

• Center(width, fillchar)
str1="welcome“
print(str1.center(15,"*")) # ****welcome*****

• len(string)
str1="welcome"
print(len(str1)) #7
Strings Methods
• count(str, beg= 0, end=len(string))
str1="welcome"
print(str1.count('e',0,len(str1))) #2
print(str1.count('e’,2,len(str1)))

• endswith(suffix, beg=0, end=len(string))


str1="welcome"
print str1.endswith('me',0,len(str1)) # True

• startswith(str, beg=0, end=len(string))


str1="welcome"
print (str1.startswith(‘we',0,len(str1))) # False
print(str1.startswith('we',2,len(str1)))
Strings Methods
• replace(old, new)
str5="welcome to java”
print(str5.replace("java", "python”))
#welcome to python
• find(str, beg=0, end=len(string))
str1="welcome“
print (str1.find('e',0,len(str1))) #1
print(str1.find('l',3,len(str1))) #-1
print(str1.find(‘lc’,0,len(str1))) #1
Strings Methods
• isalnum()
str2="welcome2017"
Print(str2.isalnum()) # True
str2="welcome2017@"
print(str2.isalnum()) #False
• isalpha()
str2="welcome2017”
print(str2.isalpha()) # False
Strings Methods
• islower()
str2="welcome2017"
print (str2.islower()) # True

• isupper()
str2="welcome2017"
print (str2.isupper()) # False
Strings Methods
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

The lower() method returns the string in lower case:


a = "Hello, World!"
print(a.lower())

The upper() method returns the string in upper case:


a = "Hello, World!"
print(a.upper())
• The split() method splits the string into substrings if it finds instances of
the separator:
• split() function can take space as seperator by default. But we can pass
anything as separator.

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!’]

a = "Hello World Welcome to Python"


print(a.split( )) # returns ['Hello', ' World','Welcome', 'to', 'Python']
Check String
• To check if a certain phrase or character is present in a string, we can use the
keywords in or not in.
Example

#Check if the phrase "ain" is present in the following text:


txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)

Check if the phrase "ain" is NOT present in the following text:


txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
String Concatenation

• To concatenate, or combine, two strings you can use the + operator.


Example

a = "Hello"
b = "World"
c=a+b
print(c)
c=a+""+b
print(c)

Output:
HelloWorld
Hello World
str1="welcome"
print(str1.count('e',2,len(str1)))
str1="welcome"
print(str1.endswith('e',0,len(str1)))
str1="welcome"
print(str1.startswith('we',2,len(str1)))
str5="welcome to java"
print(str5.replace("java", "python"))
str1="welcome"
print(str1.find('el',0,len(str1)))
str2="welcome2017@"
print(str2.isalnum())
str2="welcome"
print(isalpha(str2))
a = "Hello World Welcome to Python"
print(a.split(" ")) # returns ['Hello', ' World’, 'Welcome', 'to', 'Python']
• Output:
C:\Users\HP>strmethods.py
Hello
****welcome*****
1
True
False
welcome to python
1
False
True
['Hello', 'World', 'Welcome', 'to', 'Python']

C:\Users\HP>
list data type
• A list can be defined as a collection of values or items
of different types.
• The items in the list are separated with the comma (,)
and enclosed with the square brackets [].
• An ordered, mutable, heterogeneous collection of
elements is nothing but list, where duplicates also
allowed.
• If we want to represent a group of individual objects
as a single entity where insertion order preserved and
duplicates are allowed, then we should go for List.
• List is dynamic because based on our requirement we can increase
the size and decrease the size.

• We can differentiate duplicate elements by using index and


we can preserve insertion order by using index. Hence
index will play very important role.

• Python supports both positive and negative indexes. +ve


index means from left to right where as negative index
means right to left

• List objects are mutable i.e we can change the content.


[10,"A","B",20, 30, 10]

-6 -5 -4 -3 -2 -1

10 A B 20 30 10
0 1 2 3 4 5
Creation of List Objects:
⦁ We can create empty list object as follows...

list=[]
print(list)
print(type(list))

Output

[]
<class 'list'>
• Example
list=[10,20,30,40]
2) >>> list[0]
3) 10
4) >>> list[-1]
5) 40
6) >>> list[1:3]
7) [20, 30]
8) >>> list[0]=100
9) >>> for i in list:print(i)
10) ...
11) 100
12) 20
13) 30
• With dynamic input:
list=input("Enter List:")
print(list)
print(type(list))

C:\Python>python test.py
Enter List:[10,20,30,40]
[10, 20, 30, 40]
• With list() function:
l=list(range(0,10,2))
print(l)
print(type(l))

C:\Python>python test.py
[0, 2, 4, 6, 8]
Accessing elements of List:
• We can access elements of the list either by using index or by using slice
operator(:)

1. By using index:

• List follows zero based index. ie index of first element is zero.


• List supports both +ve and -ve indexes.
• +ve index meant for Left to Right
• -ve index meant for Right to Left
• list=[10,20,30,40]
list=[10,20,30,40]

• print(list[0]) ==>10
• print(list[-1]) ==>40
• print(list[10]) ==>IndexError: list index out of range
2. By using slice operator:

Syntax:
list2= list1[start:stop:step]
start ==>it indicates the index where slice has to start default
value is 0

stop ===>It indicates the index where slice has to end


default value is max allowed index of list ie length of the list

step ==>increment value


default value is 1
Example:
Syntax: list2= list1[start:stop:step]
Output
n=[1,2,3,4,5,6,7,8,9,10] C:\Python>python test.py
print(n[2:7:2]) [3, 5, 7]
print(n[4::2]) [5, 7, 9]
print(n[3:7]) [4, 5, 6, 7]
print(n[4:100]) [5, 6, 7, 8, 9, 10]
Important functions of List:
• To get information about list:
• len(): Returns the number of elements present in the
list
Eg: n=[10,20,30,40]
print(len(n))==>4
2. count():
It returns the number of occurrences of specified item in the list
n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))

Output
C:\Python>python test.py
1
4
2
0
3. index() function: Returns the index of first occurrence of the specified item.
• Eg:
n=[1,2,2,2,2,3,3]
print(n.index(1)) ==>0
print(n.index(2)) ==>1
print(n.index(3)) ==>5
print(n.index(4)) ==> ValueError: 4 is not in list.

• Note: If the specified element not present in the list then we will get Value
Error. Hence before index() method we have to check whether item present
in the list or not by using in operator.
• print( 4 in n)==>False
Manipulating elements of List:
1. append() function:
We can use append() function to add item at the end of the list.
Eg:
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)

C:\Python>python test.py

o/p['A', 'B', 'C']


Eg: To add all elements to list upto 100 which are divisible by 10
list=[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)

C:\Python>python test.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
2.insert() function:
To insert item at specified index position
n=[1,2,3,4,5]
n.insert(1,888)
print(n)

C:\Python>python test.py
[1, 888, 2, 3, 4, 5]
Eg:
n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)

C:\Python>python test.py
[999, 1, 2, 3, 4, 5, 777]

• Note: If the specified index is greater than max index then element will be
inserted at last position. If the specified index is smaller than min index then
element will be inserted at first position.
Differences between append() and insert()
• In List when we add any element it will come in last i.e. it will be last
element.

• In List we can insert any element in particular index number


3. extend() function:
To add all items of one list to another list
l1.extend(l2)
all items present in l2 will be added to l1
Eg:
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)

Output:
C:\Python>python test.py
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
4. remove() function:
We can use this function to remove specified item from the list. If the item
present multiple times then only first occurrence will be removed.
Example:
n=[10,20,10,30]
n.remove(10)
print(n)

C:\Python>python test.py
[20, 10, 30]
5. pop() function:
• It removes and returns the last element of the list.
• This is only function which manipulates list and returns some element.
Eaxample:
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)

C:\Python>python test.py
40
30
[10, 20]
If the list is empty then pop() function raises IndexError
• In general we can use pop() function to remove last element of the list.
• But we can also use pop() to remove elements based on index.
• n.pop(index)===>To remove and return element present at specified
index.
• n.pop()==>To remove and return last element of the list

Example:
n=[10,20,30,40,50,60]
print(n.pop()) #60
print(n.pop(1)) #20
print(n.pop(10)) ==>IndexError: pop index out of range
Note:
• List objects are dynamic. i.e based on our requirement we can
increase and decrease the size.
• append(),insert() ,extend() ===>for increasing the size/growable
nature
• remove(), pop() ======>for decreasing the size /shrinking nature
clear() function:
• We can use clear() function to remove all elements of List.
Eg:
n=[10,20,30,40]
print(n)
n.clear()
print(n)

Output
C:\Python>python test.py
[10, 20, 30, 40]
[]
III. Ordering elements of List:

1. reverse():

We can use to reverse() order of elements of list.


n=[10,20,30,40]
n.reverse()
print(n)

Output:
C:\Python>python test.py
[40, 30, 20, 10]
2. sort() function:
The sort function sort the list in ascending order by default.
• For numbers ==>default natural sorting order is Ascending Order
• For Strings ==> default natural sorting order is Alphabetical Order
• Syntax
list.sort(reverse=True|False)
Reverse is Optional.
reverse=True will sort the list descending.
Default is reverse=False(ascending order)
Example:1
n=[20,5,15,10,0]
n.sort()
print(n) #[0,5,10,15,20]

Example:2
a=["Si", "sa", "Bh", "Pr", "GB"]
a. sort()
print(a) # ['Bh', ‘GB', 'Pr', 'Si', 'sa']
To sort in reverse of default natural sorting order:
We can sort according to reverse of default natural sorting order by using
reverse=True argument.
Eg:
n=[40,10,30,20]
n.sort()
print(n) ==>[10,20,30,40]
n.sort(reverse=True)
print(n) ===>[40,30,20,10]
n.sort(reverse=False)
print(n) ==>[10,20,30,40]
Example: (Descending order)
a=["Si", "sa", "Bh", "Pr", "GB"]
a.sort(reverse=True)
print(a)
Output:
['sa', 'Si', 'Pr', ‘GB', 'Bh']
• The sorted() function returns a sorted list of the specified iterable object.

l=[6,5,8,9]
l.sort(reverse=True)
print(l)
l1=sorted(l)
print(l1)
l2=sorted(l,reverse=True)
print(l2)

>>>
=== RESTART: C:/Users/HP50/AppData/Local/Programs/Python/Python38-32/lsort.py ==
[9, 8, 6, 5]
[5, 6, 8, 9]
[9, 8, 6, 5]
>>>
• Note: To use sort() function, compulsory list should contain only
homogeneous elements.otherwise we will get TypeError

Eg:

n=[20,10,"A","B"]
n.sort()
print(n)

TypeError: '<' not supported between instances of


'str' and 'int'
Nested Lists:
• Sometimes we can take one list inside another list. Such type of lists
are called nested lists.
• We can access nested list elements by using index just like accessing
multidimensional array elements
Eg:
n=[10,20,[30,40]] Output
print(n) c:\Python>python test.py
print(n[0]) [10, 20, [30, 40]]
10
print(n[2])
[30, 40]
print(n[2][0]) 30
print(n[2][1]) 40
Example
# creating an empty list
lst = []
# number of elemetns as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input())
lst.append(ele) # adding the element

print(lst)
Python List Operations

• The concatenation (+) and repetition (*) operator work in the same
way as they were working with the strings.
Consider a List l1 = [1, 2, 3, 4], and
l2 = [5, 6, 7, 8]
Operator Description Example
The repetition operator
enables the list elements
Repetition L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
to be repeated multiple
times.
It concatenates the list
Concatenation mentioned on either side l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
of the operator.
It returns true if a
particular item exists in a
Membership print(2 in l1) prints True.
particular list otherwise
false.
The for loop is used to
for i in l1: print(i) Output1
Iteration iterate over the list
234
elements.
Tuple:

1.Tuple is exactly same as List except that it is immutable. i.e, once we


creates Tuple object, we cannot perform any changes in that object. Hence
Tuple is Read Only version of List.
2. We can represent Tuple elements within Parenthesis and with comma
seperator. Parenethesis are optional but recommended to use.
3. If our data is fixed and never changes then we should go for Tuple.
4. Insertion Order is preserved
5. Duplicates are allowed
6. Heterogeneous objects are allowed.
7. We can preserve insertion order and we can differentiate duplicate
objects by using index. Hence index will play very important role in
Tuple also.
8. Tuple support both +ve and -ve index. +ve index means forward
direction(from left to right) and -ve index means backward
direction(from right to left)
Tuple creation:
1. t=()
creation of empty tuple

2. t=(10,)
t=10,
creation of single valued tuple ,parenthesis are optional,should ends with comma

3. t=10,20,30
t=(10,20,30)
creation of multi values tuples & parenthesis are optional
4. By using tuple() function:
list=[10,20,30]
t=tuple(list)
print(t)

5.By using range() function:


t=tuple(range(10,20,2))
print(t)
Eg:1
t=10,20,30,40
print(t) Examples:
print(type(t)) T1 = (201, "Aishwarya", 20)
T2 = ("Akhila", "Anusha", "Kavya")
Output
(10, 20, 30, 40)
<class 'tuple’>

Eg:2
t=()
print(type(t)) # tuple
Accessing elements of tuple:
• We can access either by index or by slice operator.
Exmaple:
t=(10,20,30,40,50,60)
print(t[0]) #10
print(t[-1]) #60
print(t[100]) IndexError: tuple index out of range
2. By using slice operator:
Example:
t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[::2])

Output
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
Tuple vs immutability:

Once we creates tuple,we cannot change its content.


Hence tuple objects are immutable.
Eg:
t=(10,20,30,40)
t[1]=70 TypeError: 'tuple' object does not support item assignment
Important functions of Tuple:
1. len()
To return number of elements present in the tuple
Eg:
t=(10,20,30,40)
print(len(t)) #4

2. count()
To return number of occurrences of given element in the tuple
Eg:
t=(10,20,10,10,20)
print(t.count(10)) #3
3. index()
• returns index of first occurrence of the given element.
• If the specified element is not available then we will get ValueError.
Eg:
t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) ValueError: tuple.index(x): x not in tuple
4. sorted()
• To sort elements based on default natural sorting order
t=(40,10,30,20)
t1=sorted(t) We can sort according to reverse of
print(t1) default natural sorting order as follows
print(t)
t1=sorted(t,reverse=True)
print(t1) [40, 30, 20, 10]
Output
[10, 20, 30, 40]
(40, 10, 30, 20)
5. min() and max() functions:
• These functions return min and max values according to default
natural sorting order.
Eg:
t=(40,10,30,20)
print(min(t)) #10
print(max(t)) #40
6. cmp():
• It compares the elements of both tuples.
• If both tuples are equal then returns 0
• If the first tuple is less than second tuple then it returns -1
• If the first tuple is greater than second tuple then it returns +1
Eg:
t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2)) # -1
print(cmp(t1,t3)) # 0
print(cmp(t2,t3)) # +1
Note: cmp() function is available only in Python2 but not in Python 3
t1=(10,20,30,40)
t2=(40,60,70,80)
print(cmp(t1,t2))

C:\Python27>python tucmp.py
-1

C:\Python27>
t1=(50,20,30,40)
t2=(40,60,70,80)
print(cmp(t1,t2))

C:\Python27>python tucmp.py
1

C:\Python27>
t1=(20,70,30,40)
t2=(40,60,70,80)
print(cmp(t1,t2))

C:\Python27>python tucmp.py
-1

C:\Python27>
• Differences between List and Tuple:
• List and Tuple are exactly same except small difference: List objects
are mutable where as
• Tuple objects are immutable.
• In both cases insertion order is preserved, duplicate objects are
allowed, heterogenous
• objects are allowed, index and slicing are supported
Set Data Type:
• If we want to represent a group of values without duplicates where
order is not important then we should go for set Data Type.
• If we want to represent a group of unique values as a single entity
then we should go for set.
• Duplicates are not allowed.
• Insertion order is not preserved. But we can sort the elements.
• Indexing and slicing not allowed for the set.
• Heterogeneous elements are allowed.
• Set objects are mutable i.e once we creates set object we can perform any
changes in that object based on our requirement.
• We can represent set elements within curly braces and with comma separation
• Creation of Set objects:
Eg:
s={10,20,30,40}
print(s)
print(type(s))
Output
>>>
{40, 10, 20, 30}
<class 'set'>
>>>
• We can create set objects by using set() function
s=set(any sequence)
Eg 1:
l = [10,20,30,40,10,20,10]
s=set(l)
print(s) # {40, 10, 20, 30}

Eg 2:
s=set(range(5))
print(s) #{0, 1, 2, 3, 4}
Note: While creating empty set we have to take special care.
• Compulsory we should use set() function.

s={} ==>It is treated as dictionary but not empty set.

Eg: Eg:
s={} s=set()
print(s) print(s)
print(type(s)) print(type(s))

Output Output
{} set()
<class 'dict'> <class 'set'>
Important functions of set:
add(x):
Adds item x to the set
Eg:
s={10,20,30}
s.add(40);
print(s)➔ #{40, 10, 20, 30}
s={10,20,30} • Output
s.add(40); >>>
print(s) {40, 10, 20, 30}
s.add(50) {40, 10, 50, 20, 30}
print(s) {40, 10, 50, 20, 30}
s.add(40); {40, 10, 50, 20, 30}
print(s) >>>
s.add(10);
print(s)
2. update([x,y,z]):
To add multiple items to the set.

Eg:
s={10,20,30}
s.update([50,60])
print(s)
s={10,20,30} • output
s.update([50,60]) >>>
print(s) RESTART:
s.update([80,40]) C:/Users/91986/AppData/Local/Progra
ms/Python/Python36/setupdate.py
print(s)
{10, 50, 20, 60, 30}
s.update([50,40])
{40, 10, 80, 50, 20, 60, 30}
print(s)
{40, 10, 80, 50, 20, 60, 30}
>>>
• Note: We can use add() to add individual item to the Set, where as we can use
update() function to add multiple items to Set.
• add() function can take only one argument where as update() function can
take any number of arguments.

• 3. copy(): Returns copy of the set. It is cloned object.

s={10,20,30}
s1=s.copy()
print(s1)
• 4. pop():It removes and returns some random element from the set.
Eg:
S = {"ram", "rahim", "ajay", "rishav", "aakash"}
# Popping three elements and printing them
print(S.pop())
print(S.pop())
print(S.pop())
# The updated set
print("Updated set is", S)

Output
>>>
= RESTART: C:/Users/91986/AppData/Local/Programs/Python/Python36/setpop1.py =
ajay
rishav
rahim
Updated set is {'ram', 'aakash'}
>>>
5. remove(x):It removes specified element from the set. If the specified element not
present in the Set then we will get Key Error.
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) ==>KeyError: 50

6. discard(x): It removes the specified element from the set. If the specified element
not present in the set then we won't get any error.
s={10,20,30}
s.discard(10)
print(s) ===> {20, 30}
s.discard(50)
print(s) ==> {20, 30}
7.clear(): To remove all elements from the Set.
s={10,20,30}
print(s)
s.clear()
print(s)

Output
{10, 20, 30}
set()
• Mathematical operations on the Set:
1.union():
x.union(y) ==>We can use this function to return all elements present in both
sets
x.union(y) or x|y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y)) #{10, 20, 30, 40, 50, 60}
print(x|y) #{10, 20, 30, 40, 50, 60}
• 2. intersection():
x.intersection(y) or x&y
• Returns common elements present in both x and y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y)) #{40, 30}
print(x&y) #{40, 30}
3. difference():
• x.difference(y) or x-y
• returns the elements present in x but not in y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y)) #{10, 20}
print(x-y) #{10, 20}
print(y-x) #{50, 60}
4.symmetric_difference():

x.symmetric_difference(y) or x^y
Returns elements present in either x or y but not in both.

Eg:

x={10,20,30,40}
y={30,40,50,60}

print(x.symmetric_difference(y)) #{10, 50, 20, 60}

print(x^y) #{10, 50, 20, 60}


Write a program to eliminate duplicates present in the list?

l=eval(input("Enter List of values: "))


s=set(l)
print(s)

Output
D:\Python_classes>py test.py
Enter List of values: [10,20,30,10,20,40]
{40, 10, 20, 30}
• Set Comprehension:

Set comprehension is possible.


s={x*x for x in range(5)}
print(s) #{0, 1, 4, 9, 16}
frozenset Data Type:
• It is exactly same as set except that it is immutable.
• Hence we cannot use add or remove functions.
s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(fs)
<class 'frozenset‘>

>>>fs.add(70)
AttributeError: 'frozenset' object has no attribute 'add'
>>> fs.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
Dictionary
• We can use List,Tuple and Set to represent a group of individual
objects as a single entity.
• If we want to represent a group of objects as key-value pairs
then we should go for Dictionary.
Eg:
rollno----name
phone number--address
ipaddress---domain name
• Duplicate keys are not allowed but values can be duplicated.
• Heterogeneous objects are allowed for both key and values.
• insertion order is not preserved
• Dictionaries are mutable
• Dictionaries are dynamic
• indexing and slicing concepts are not applicable

Note: In C++ and Java Dictionaries are known as


"Map" where as in Perl and Ruby it is known as
"Hash"
How to create Dictionary?
d={} or d=dict()
we are creating empty dictionary. We can add entries as follows

d[100]=“ananthapur"
d[200]=“srikakulam"
d[300]=“prakasam"
print(d) #{100: ‘ananthapur ', 200: ‘srikakulam ', 300: ‘prakasam '}
• If we know data in advance then we can create dictionary as follows
d= {100: ‘ananthapur ', 200: ‘srikakulam ', 300: ‘prakasam '}

d={key:value, key:value}
• How to access data from the dictionary?

• We can access data by using keys.


d= {100: ‘ananthapur ', 200: ‘srikakulam ', 300: ‘prakasam '}
print(d[100]) # ananthapur
print(d[300]) # prakasam

If the specified key is not available then we will get KeyError

print(d[400]) # KeyError: 400


• We can prevent this by checking whether key is already available or
not by using has_key() function or by using in operator.
d.has_key(400) ==> returns 1 if key is available otherwise returns 0

• But has_key() function is available only in Python 2 but not in


Python 3. Hence compulsory we have to use in operator.
if 400 in d:
print(d[400])
How to update dictionaries?
d[key]=value
if the key is not available then a new entry will be added to the
dictionary with the specified key-value pair
If the key is already available then old value will be replaced with new
value.
• Eg:
d={100:”pavani",200:"rani",300:"shivani"}
print(d)
d[400]=“Geetha"
print(d)
d[100]=“Prerana"
print(d)

• Output:
{100: ‘pavani', 200: ‘rani', 300: 'shivani'}
{100: ‘pavani', 200: ‘rani', 300: 'shivani', 400: ‘Geetha'}
{100: ‘Prerana', 200: ‘rani', 300: 'shivani', 400: ‘Geetha'}
delete elements from dictionary:
• It deletes entry associated with the specified key. If the key is not available
then we will get Key Error.
• Syntax: del d[key]
Eg:
d={100:"N",200:"T",300:"g"}
print(d) Output
del d[100] {100: 'N', 200: 'T', 300: 'g'}
print(d) {200: 'T', 300: 'g'}
del d[400] KeyError: 400
• del d
To delete total dictionary. Now we cannot access d
Eg:
d={100:"baby",200:"smart",300:"Maha"}
print(d)
del d
print(d)

Output:
{100: 'baby', 200: 'smart ', 300: 'Maha'}
Name Error: name 'd' is not defined
• d.clear() : To remove all entries from the dictionary
Eg:
d={100:"pavani",200:"rani",300:"shivani"}
print(d)
d.clear()
print(d)

Output
{100: 'pavani', 200: ‘rani', 300: 'shivani'}
{}
• Important functions of dictionary:
1. dict():
• To create a dictionary

• d=dict() ===>It creates empty dictionary

• d=dict({100:"sita",200:"geeta"}) ==>It creates dictionary with specified


elements

• d=dict([(100,"Ram"),(200,"laxman"),(300,“sita")])==>It creates dictionary


with the given list of tuple elements.
2. len()
• Returns the number of items in the dictionary
e.g. print(len(d))

3. clear():
To remove all elements from the dictionary

4. get():
To get the value associated with the key

• d.get(key)
If the key is available then returns the corresponding value otherwise returns None. It
wont raise any error.

• d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.
d={100:"pavani",200:"rani",300:"shivani"}
print(d)
print(d.get(200))
print(d.get(400,"abc"))
d.clear()
print(d)

>>>
{100: 'pavani', 200: 'rani', 300: 'shivani'}
rani
abc
{}
>>>
• 4. popitem():
• It removes an arbitrary item(key-value) from the dictionary and returns it.
Eg:
d={100:"Mahesh",200:"raviteja",300:"charan"}
print(d)
print(d.popitem())
print(d)

Output
{100: 'Mahesh', 200: 'raviteja', 300: 'charan'}
(300, 'charan')
{100: 'Mahesh', 200: 'raviteja‘}

If the dictionary is empty then we will get KeyError


d={}
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty'
• Eg:
d={100:"Mahesh",200:"raviteja",300:"charan"}
print(d.pop(100))
print(d)
print(d.pop(400))

Output:
Mahesh
{200:’raviteja’,300:’charan’}
KeyError: 400
• 5. keys():
• It returns all keys associated with dictionary
Eg:
d={100:"Pavan",200:"ravi",300:"shiva"}
print(d.keys())
for k in d.keys():
print(k)

Output
dict_keys([100, 200, 300])
100
200
300
6. values():
• It returns all values associated with the dictionary.
Eg:
d={100:"Orbiter",200:"Lander",300:"Rover"}
print(d.values())
for v in d.values():
print(v)

Output:
dict_values(['Orbiter', 'Lander', 'Rover'])
Orbiter
Lander
Rover
• 7. items():
• It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]

Eg:
d={100:"Orbiter",200:"Lander",300:"Rover"}
print(d.items())
for k,v in d.items():
print(k,"--",v)

Output:
dict_items([(100, 'Orbiter'), (200, 'Lander'), (300, 'Rover')])
100 -- Orbiter
200 -- Lander
300 -- Rover
8. copy():
• To create exactly duplicate dictionary(cloned copy)
Syntax: d1=d.copy();

9. setdefault():
Syntax: d.setdefault(k,v)

• If the key is already available then this function returns the corresponding
value.
• If the key is not available then the specified key-value will be added as new
item to the dictionary.
• Eg:
d={100:"Ganguly",200:"Sehwag",300:"Dhoni"}
print(d.setdefault(400,"Kohli"))
print(d)
print(d.setdefault(100,"sachin"))
print(d)

Output:
Kohli
{100: 'Ganguly', 200: 'Sehwag', 300: 'Dhoni', 400: 'Kohli'}
Ganguly
{100: 'Ganguly', 200: 'Sehwag', 300: 'Dhoni', 400: 'Kohli'}
10. update():
• All items present in the dictionary x will be added to dictionary d.
d.update(x)
Example:
d = {1: “whatsapp", 2: “facebook"}
d1 = {2: “instagram"}# updates the value of key 2
d.update(d1) Output:
print(d)
{1: ‘whatsapp', 2: ‘instagram'}
d1 = {3: “faceapp"}# adds element with key 3 {1: ‘whatsapp', 2: ‘instagram', 3: ‘faceapp'}
d.update(d1)
print(d)
• The update method directly takes a key-value pair and puts it into the
existing dictionary. The key value pair is the argument to the update
function. We can also supply multiple key values as shown below.
• Example
CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34}
print(CountryCodeDict)
CountryCodeDict.update( {'Germany' : 49} )
print(CountryCodeDict)
# Adding multiple key value pairs
CountryCodeDict.update( [('Austria', 43),('Russia',7)] )
print(CountryCodeDict)
• Output(python3)

• >>>
• = RESTART:
C:/Users/HP50/AppData/Local/Programs/Python/Python38-
32/dicupdate.py
• {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34}
• {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34, 'Germany': 49}
• {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34, 'Germany': 49, 'Austria': 43,
'Russia': 7}
• >>>
Output(python2)

C:\>cd python27
C:\Python27>python dict.py
{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
{'Germany': 49, 'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
{'USA': 1, 'India': 91, 'Austria': 43, 'Germany': 49, 'UK': 44, 'Russia': 7,
'Spain': 34}

C:\Python27>
None Data Type:
• None means Nothing or No value associated.
• If the value is not available,then to handle such type of cases None introduced.
• It is something like null value in Java.
Eg:
def m1():
a=10
print(m1())

Output:
None
Python Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators
consider a=10,b=20
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

Divides left hand operand by right hand operand and


% Modulus b%a=0
returns remainder

Performs exponential (power) calculation on a**b =10 to the


** Exponent
operators power 20

The division of operands where the result is the


9//2 = 4 and
// Floor Division quotient in which the digits after the decimal point
9.0//2.0 = 4.0
are removed.
1. Arithmetic Operators example:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulo operator
// ==>Floor Division operator
** ==>Exponent operator or power operator
Eg: test.py:
a=10 Output:
b=2 Python test.py or py test.py
a+b= 12
print('a+b=',a+b) a-b= 8
print('a-b=',a-b) a*b= 20
print('a*b=',a*b) a/b= 5.0
a//b= 5
print('a/b=',a/b) a%b= 0
print('a//b=',a//b) a**b= 100
print('a%b=',a%b)
print('a**b=',a**b)
10/2==>5.0
10//2==>5
10.0/2===>5.0
10.0//2===>5.0

• Division operator (/) always performs floating point arithmetic. Hence it will
always returns float value.
• Floor division (//) can perform both floating point and integral arithmetic.
We can use + operator for str concat also.
>>> “Python"+123
Output :TypeError: must be str, not int
>>> “Python"+"123"
Output: Python123
Comparison (Relational) Operators

Operator Description Example

If the values of two operands are equal, then the condition


== (a == b) is not true.
becomes true.
If values of two operands are not equal, then condition
!= (a != b) is true.
becomes true.

If values of two operands are not equal, then condition (a <> b) is true. This is
<>
becomes true. similar to != operator.

If the value of left operand is greater than the value of right


> (a > b) is not true.
operand, then condition becomes true.
If the value of left operand is less than the value of right
< (a < b) is true.
operand, then condition becomes true.

If the value of left operand is greater than or equal to the


>= (a >= b) is not true.
value of right operand, then condition becomes true.

If the value of left operand is less than or equal to the value


<= (a <= b) is true.
of right operand, then condition becomes true.
Relational Operators example:
>,>=,<,<=
Eg 1: Output:

>>>a=10 a > b is False


>>>b=20 a >= b is False
a < b is True
>>>print("a > b is ",a>b) a <= b is True
>>>print("a >= b is ",a>=b)
>>>print("a < b is ",a<b)
>>>print("a <= b is ",a<=b)
Eg 2:
a,b=10,20
if(a>b):
print("a is greater than b")
else:
print("a is not greater than b")
• Output :a is not greater than b
Equality operators example:
== , !=
We can apply these operators for any type even for incompatible types also
>>> 10==20
False
>>> 10!= 20
True
>>> 10==True
False
>>> False==False
True
>>> “Siva”!=“Bhargav"
True
>>> 10==“python"
False
Assignment Operators
Operator Description Example
Assigns values from right side operands to left side c = a + b assigns value of
=
operand a + b into c
+= It adds right operand to the left operand and assign the c += a is equivalent to c
Add AND result to left operand =c+a
-= It subtracts right operand from the left operand and c -= a is equivalent to c =
Subtract AND assign the result to left operand c-a

*= It multiplies right operand with the left operand and c *= a is equivalent to c =


Multiply AND assign the result to left operand c*a

/= It divides left operand with the right operand and c /= a is equivalent to c =


Divide AND assign the result to left operand c/a

%= It takes modulus using two operands and assign the c %= a is equivalent to c


Modulus AND result to left operand =c%a

**= Performs exponential (power) calculation on operators c **= a is equivalent to c


Exponent AND and assign value to the left operand = c ** a
//= It performs floor division on operators and assign value c //= a is equivalent to c
Floor Division to the left operand = c // a
Assignment Operators example:

• The following is the list of all possible compound assignment operators in Python
+=, -=, *=, /=, %=, //=, **=, &=, |=, ^=

Eg:1 x=10,
x+=10 ====> x = x+10

Eg:2
x=10
x+=20
print(x) ==>30

Eg: 3
x=10
x&=5
print(x) ==>0
Logical Operators
Operator Description Example
And
If both the operands are true then (a and b) is
Logical
condition becomes true. true.
AND
Or If any of the two operands are non-zero (a or b) is
Logical OR then condition becomes true. true.
not
Used to reverse the logical state of its Not (a and
Logical
operand. b) is false.
NOT
Logical Operators example:
and, or ,not

We can apply for all types.

For boolean types behaviour:


and ==>If both arguments are True then only result is True
or ====>If atleast one arugemnt is True then result is True
not ==>complement
True and False ==>False
True or False ===>True
not False ==>True
BitwiseOperator
Operators Description Example
& Operator copies a bit to the result if (a & b) = 12
Binary AND it exists in both operands. (means 0000 1100)
| It copies a bit if it exists in either (a | b) = 61
Binary OR operand. (means 0011 1101)
^ It copies the bit if it is set in one (a ^ b) = 49
Binary XOR operand but not both. (means 0011 0001)
~ (~a ) = -61 (means 1100 0011
It is unary and has the effect of
Binary Ones in 2's complement form due to
'flipping' bits.
Complement a signed binary number.
The left operands value is moved
<< a << 2 = 240
left by the number of bits specified
Binary Left Shift (means 1111 0000)
by the right operand.
The left operands value is moved
>> a >> 2 = 15
right by the number of bits specified
Binary Right Shift (means 0000 1111)
by the right operand.
Bitwise Operators example:
• We can apply these operators bitwise.
• These operators are applicable only for int and boolean types.
• By mistake if we are trying to apply for any other type then we will get
Error.
OPERATORS ARE: &,|,^,~,<<,>>
print(4&5) ==>4
print(10.5 & 5.6) ==>
TypeError: unsupported operand type(s) for &: 'float' and 'float'
print(True & True) ==>True
• bitwise complement operator(~):
We have to apply complement for total bits.
Eg: print(~5) ==>-6.

• << Left shift operator


After shifting the empty cells we have to fill with zero
• print(10<<2)==>40

• >> Right Shift operator


• After shifting the empty cells we have to fill with sign bit.( 0 for +ve and
1 for -ve)
print(10>>2) ==>2
Ternary Operator:
Syntax:
x = firstValue if condition else secondValue
If condition is True then firstValue will be considered else secondValue will
be considered.
Eg 1:
a,b=10,20
x=30 if a<b else 40
print(x) #30
Eg 2: Read two numbers from the keyboard and print minimum value
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)

Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
Eg3: Program for minimum of 3 numbers
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
min=a if a<b and a<c else b if b<c else c
print("Minimum Value:",min)
Eg4: Program for maximum of 3 numbers
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
max=a if a>b and a>c else b if b>c else c
print("Maximum Value:",max)
Special operators:
• Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
Identity Operators
Operator Description Example

Evaluates to true if the variables on


x is y, here is results in 1 if
is either side of the operator point to
id(x) equals id(y).
the same object and false otherwise.

Evaluates to false if the variables on x is not y, here is not results


is not either side of the operator point to in 1 if id(x) is not equal to
the same object and true otherwise. id(y).
Example:
# Python program to illustrate the # Python program to illustrate the
use of 'is' identity operator # use of 'is not' identity operator
x=5 x = 5.2
if (type(x) is int): if (type(x) is not int):
print("true") print("true")
else: else:
print("false") print("false")
Membership Operators

Operator Description Example

Evaluates to true if it finds a x in y, here in results in


in variable in the specified a 1 if x is a member of
sequence and false otherwise. sequence y.
x not in y, here not in
Evaluates to true if it does not
results in a 1 if x is not
not in finds a variable in the specified
a member of sequence
sequence and false otherwise.
y.
• We can use Membership operators to check whether the given object
present in the given collection(String,List,Set,Tuple or Dict).
• in -> Returns True if the given object present in the specified
Collection
• not in -> Returns True if the given object not present in the specified
Collection.
• Eg:1
• x="hello learning Python is very easy!!!"
• print('h' in x) True
• print('d' in x) False
• print('d' not in x) True
• print('Python' in x) True
Python Operator Precedence
Operator Description
( ) Parenthesis
** Exponentiation (raise to the power)
~ x, +x, -x Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is , is not Identity operators
in, not in Membership operators
not or and Logical operators
Expression
• An expression is a combination of variables constants and operators
written according to the syntax of Python language.
• In Python every expression evaluates to a value i.e., every expression
results in some value of a certain type that can be assigned to a
variable.
• Example:
• A*b-c
• (m+n)*(x+y)
• 3*x*x+2*x+1
•x/y+c
Evaluation of Expression
• The expression is evaluated first and then replaces the
previous value of the variable on the left hand side.
• The Expression can be evaluated based on operator
precedence.
Decision Making
• Decision making is anticipation of conditions occurring while execution
of the program and specifying actions taken according to the conditions.
• Decision structures evaluate multiple expressions which produce True or
False as outcome.

Statement Description
if statement consists of a boolean expression followed by one or more
if statements
statements.
if statement can be followed by an optional else statement, which executes
if...else statements
when the boolean expression is FALSE.

nested if statements You can use one if or else if statement inside another if or else if statement(s).
if Statement
• The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
• The condition is tested. If the condition is True, then the statements given after
colon (:) are executed.
• Indentation : Python relies on indentation (whitespace at the beginning of a line)
to define scope in the code. Other programming languages often use curly-brackets
for this purpose.

• Syntax:
if Condition:
Statements
if Statement
Program:
a=10
b=15
Output:
B is Big
if a < b :
print "b is Big“ The value is 15
print "The value is", b
a=10
b=15
if a < b :
print ("b is Big")
print ("The value is", b)

C:\Python>python if1.py
File "if1.py", line 4
print ("b is Big")
^
IndentationError: expected an indented block

C:\Python>
if….else Statement
• An else statement contains the block of code that
executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
• Syntax:
if Condition:
Statements
else:
Statements
if Statement
Program:
a=48
b=34 Output:
if a < b: a is big
print "b is big“ a value is 48
print "b value is", b
else:
END
print "a is big "
print "a value is", a
print "END"
• Write a program to check if a number is Odd or Even

num = int(input(“Enter the number:”))


if (num % 2)== 0:
print (“Given number is Even”)
else:
print(“ Given number is Odd”)
elif Statement
• The elif statement allows you to check multiple
expressions for True and execute a block of code as soon
as one of the conditions evaluates to True.
• Syntax:
if Condition1:
Statements
elif Condition2:
Statements
else:
Statements
elif Statement
Program:
a=20
b=10 Output:
c=30
c is big
if a >= b and a >= c:
print "a is big"
elif b >= a and b >= c:
print "b is big"
else:
print "c is big"
Nested if … else Statements

We can write an entire if… else statement in another if… else statement called nesting, and
the statement is called nested if.

• Syntax
if expression1:
statement(s)
if expression2:
statement(s):
else:
statement(s)
else:
statement(s)
Example program
n = int(input(“Enter number:”))
If (n<=15):
if (n == 10):
print(‘play cricket’)
else:
print(‘play kabadi’)
else:
print(‘Don’t play game’)
Iteration Statements
• In general, statements are executed sequentially: The
first statement in a function is executed first, followed
by the second, and so on. There may be a situation
when you need to execute a block of code several
number of times.
• A loop statement allows us to execute a statement or
group of statements multiple times.

Loop Type Description


Repeats a statement or group of statements while a given condition is TRUE.
while loop
It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code
for loop
that manages the loop variable.
nested loops You can use one or more loop inside any another while, for loop.
while Loop
• A while loop statement in Python programming language repeatedly
executes a target statement as long as a given condition is True.
• Syntax:
while Condition:
Statements
while Loop
Program: Program:
i=1 i=1
while i <= 3 : while i <= 3 :
print i print i
i+=1 i+=1
print "END" print "END"

Output: Output:
1 1
END 2
2 3
END END
3
END
for Loop
• The for loop is useful to iterate over the elements of a sequence.
• It means, the for loop can be used to execute a group of statements
repeatedly depending upon the number of elements in the sequence.
• The for loop can work with sequence like string, list, tuple, range etc.
• Syntax:
for variable in sequence:
Statements
Example:
for i in [1,2,3,4]:
print i
print "END”

C:\Python>python forp.py
1
2
3
4
END
How to read multiple values from the keyboard in a single line:

a,b= [int(x) for x in input("Enter 2 numbers :").split()]


print("Product is :", a*b)
range() :
The range() function returns a sequence of numbers, starting from 0 by default,
and increments by 1 (by default), and ends at a specified number
Syntax:
range(start, stop, step)
Parameter Description
Optional. An integer number
start specifying at which position to start.
Default is 0
An integer number specifying at
stop
which position to end.
Optional. An integer number
step specifying the incrementation.
Default is 1
Example1:
range(10)
• generate numbers from 0 to 9

Example2:
r = range(10,20)
for i in r : print(i) 10 to 19

Example3:
r = range(10,20,2)
for i in r : print(i) 2 means increment value

10,12,14,16,18
We can access elements present in the range Data Type by using index.
r=range(10,15)
print(r[0]) #10
print(r[15]) #IndexError: range object index out of range

We cannot modify the values of range data type

Eg:
r[0]=100
TypeError: 'range' object does not support item assignment
for Loop
Program: Program:
for i in range(1,4): for i in range(1,4):
print(i) print(i)
print ("END“) print ("END“)

Output: Output:
1 1
END 2
2 3
END END
3
END
Nested Loops
• It is possible to write one loop inside another loop.
• For example, we can write a for loop inside a while loop or a for loop
inside another for loop.
Nested Loops
Program: Program:
for i in range(1,6): for i in range(1,6):
for j in range(1,i+1): for j in range(1,6):
print(j) print (j)
print ("“)
print ("“)
Jump Statements
• There are Three jump statements,
➢break
➢continue
➢pass
break statement
• The break is a keyword in python which is used to bring the program
control out of the loop.
• The break statement breaks the loops one by one, i.e., in the case of
nested loops, it breaks the inner loop first and then proceeds to outer
loops.
• In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after
the loop.
• The break is commonly used in the cases where we need to break the
loop for a given condition.
break statement Example

Program:
n=input("Enter the n value")
count=0
for i in range(2,n): Output:
if n%i==0: Enter the n value: 7
count=count+1 Prime Number
break
if count==0:
print ("Prime Number“)
else:
print ("Not Prime Number“)
continue statement
• The continue statement in Python is used to bring the program control to the
beginning of the loop.
• The continue statement skips the remaining lines of code inside the loop and
start with the next iteration.
• It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.
Program:
Output:
for number in range(1,7): Number is 1
if number == 4: Number is 2
continue Number is 3
print ('Number is ' + number) Number is 5
Number is 6
pass statement
• In Python, the pass keyword is used to execute nothing; it means,
when we don't want to execute code, the pass can be used to execute
empty.
• It is the same as the name refers to.
• It just makes the control to pass by without executing any code.
• If we want to bypass any code pass statement can be used.Program:
for number in range(1,7): Output:
Number is 1
if number == 4:
Number is 2
pass Number is 3
print ('Number is ' + number) Number is 4
Number is 5
Number is 6
for i in [1,2,3,4,5]: 1
if(i==4): 2
pass 3
print("This is pass block",i) This is pass block 4
print(i) 4
5

You might also like