0% found this document useful (0 votes)
414 views417 pages

UNIT-1 Modules

Python is a high-level, general-purpose programming language that is easy to learn and use. It supports multiple programming paradigms including object-oriented, imperative, functional programming. Python can be used for both desktop and web applications, data science, and more. Some key features of Python include being interpreted, dynamically typed, portable, having extensive libraries and being open source.

Uploaded by

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

UNIT-1 Modules

Python is a high-level, general-purpose programming language that is easy to learn and use. It supports multiple programming paradigms including object-oriented, imperative, functional programming. Python can be used for both desktop and web applications, data science, and more. Some key features of Python include being interpreted, dynamically typed, portable, having extensive libraries and being open source.

Uploaded by

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

INTRODUCTION TO PYTHON

• Introduction:
• 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.

• Python is recommended as first programming language for beginners.


• Python is object oriented, high level, open source, interpreter based
programming language.
• It is very simple and easy to use.
• Python supports multiple programming pattern, including object
oriented programming.
Eg: To print Helloworld:
Java:
public class HelloWorld
{ In python
p s v main(String[] args) print("Hello World")
{
SOP("Hello world");
}}
In C:
#include<stdio.h>
void main()
{printf("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.
• In Python:
• The name Python was selected from the TV Show"The Complete
Monty Python’s Circus", which was broadcasted in BBC from 1969 to
1974.
• 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
• 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
• Disadvantages of Python
• Python is not as fast as C and C++, It means it is slower than C/C++:
• 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.
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 a lot of features provided by python
programming language. Some features of python are given
below;
1. Simple and easy to learn:

• Python is a simple programming language. When we read


Python program, we can feel like reading english
statements.
• The syntaxes are very simple and only 30+ keywords are
available.
• When compared with other languages, we can write
programs with very less number of lines. Hence more
readability and simplicity.
• We can reduce development and cost of the project.
2. Freeware and Open Source:
• We can use Python software without any licence and it is
freeware.

• Its source code is open,so that we can we can customize based


on our requirement.

• Eg: Jython is customized version of Python to work with Java


Applications.

• Python language is freely available at www.python.org.


• The source-code is also available. Therefore it is open source.
3. High Level Programming language:
• Python is high level programming language and hence it is
programmer friendly language. Being a programmer we are not
required to concentrate low level activities like memory
management and security etc..

4. Platform Independent:
• Once we write a Python program,it can run on any platform
without rewriting once again.
• Internally PVM is responsible to convert into machine
understandable form.
5. Portability:
• Python programs are portable. ie we can migrate from one platform
to another platform very easily. Python programs will provide same
results on any platform.

6. Dynamically Typed:
In Python we are not required to declare type for variables.
Whenever we are assigning the value, based on value, type will be
allocated automatically. Hence Python is considered as dynamically
typed language.

• But Java, C etc are Statically Typed Languages b'z we have to provide
type at the beginning only.
• This dynamic typing nature will provide more flexibility to the
programmer.
7.Both Procedure Oriented and Object Oriented:
• Python language supports both Procedure oriented (like C,
pascal etc) and object oriented (like C++,Java) features.
Hence we can get benefits of both like security and
reusability etc

8. Interpreted:
• We are not required to compile Python programs explcitly.
Internally Python interpreter will take care that
compilation.
• If compilation fails interpreter raised syntax errors. Once
compilation success then PVM (Python Virtual Machine) is
responsible to execute.
9. Embedded:
• We can use Python programs in any other language
programs.
• i.e we can embedd Python programs anywhere.

10. Extensive Library:


• Python has a rich inbuilt library.
• Being a programmer we can use this library directly and we
are not responsible to implement the functionality.
Limitations of Python(Disadvantages of Python):
1. Performance wise not up to the mark because it is interpreted
language.
2. Not using for mobile Applications.
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
Difference between Python 2 and Python 3

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.
• Python 3 uses input() function to accept the user’s input().
• In Python 2, the implicit string type is ASCII, whereas, in Python 3, the
implicit string type is Unicode.
• 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 (python3 in case if you have python2 and
python3 both installed on your system).
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 (python3 in case if you have python2
and python3 both installed on your system).
• It will open the following prompt where we can execute the
python statement and check their impact on the console.
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 th
e message on the console.
• To run this file named as first.py, we need to run the following
command on the terminal.
• $ python3 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).
Print Hello World in Python

Python code save with .py extension.


Print hello world in python
a="Hello World!"
print(a)
Output
Hello World!
Identifiers
A name in Python program is called identifier.
It can be class name or function name or module name or variable
name.
a = 10
Rules to define identifiers in Python:
1. The only allowed characters in Python are
alphabet symbols(either lower case or upper case)
digits(0 to 9)
underscore symbol(_)
By mistake if we are using any other symbol like $ then we will get
syntax error.
cash = 10
ca$h =20
2. Identifier should not starts with digit
123total
total123
3. Identifiers are case sensitive. Of course Python language is
case sensitive language.
total=10
TOTAL=999
print(total) #10
print(TOTAL) #999
1.Alphabet Symbols (Either Upper case OR Lower case)
2. If Identifier is start with Underscore (_) then it indicates it is
private.
3. Identifier should not start with Digits.
4. Identifiers are case sensitive.
5. We cannot use reserved words as identifiers
Eg: def=10
6. There is no length limit for Python identifiers. Bu no recommended
to use too lengthy identifiers.
7. Dollor ($) Symbol is not allowed in Python
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 recomended to use lowercase letters for variable name. Rahul
and rahul both are two different variables.
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. Lets see given examples.
Multiple Assignments to variables :

• Python allows you to assign a single value to several variables


simultaneously.
• For example –
•a=b=c=1
• Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location. You can
also assign multiple objects to multiple variables.
• For example –
• a, b, c = 1, 2.5, ”mothi”
• Here, two integer objects with values 1 and 2 are assigned to
variables a and b respectively, and one string object with the
value "john" is assigned to the variable c.
example

a,b,c=5,10,15
print a
print b
print c
Keywords in Python(Reserved Words)

• 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.
• 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
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
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)
• 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'>
• EXAMPLE : A1.PY
• x=input('Enter your name:')
• print('Hello,'+ x)

EXAMPLE :A2.PY
print("enter your name:")
x=input()
print('Hello,'+ x)
Example: a3.py
x=input("Enter First Number:")
y=input("Enter Second Number:")
i = int(x)
j = int(y)
print("The Sum:",i+j)

Enter First Number:100


Enter Second Number:200
The Sum: 300
x=int(input("Enter First Number:"))
y=int(input("Enter Second Number:"))
print("The Sum:",x+y)

(OR)
print("The Sum:",int(input("Enter First Number:"))+int(input("Enter Second Number:")))
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)

D:\Python_classes>py test.py
Enter 2 numbers :10 20
Product is : 200
• split() function can take space as seperator by default. But we can
pass anything as separator.
• Write a program to read 3 float numbers from the keyboard with ,
seperator and print their sum
a,b,c= [float(x) for x in input("Enter 3 float numbers :").split(',’)]
print("The Sum is :", a+b+c)
D:\Python_classes>py test.py
Enter 3 float numbers :10.5,20.6,20.1
The Sum is : 51.2
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=':’)

D:\Python_classes>py 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
3. 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
Optional. An integer number
stop
specifying at 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,20)
r[0]==>10
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
Data types

• A variable can hold different types of values. For example, a person's


name must be stored as a string whereas its id must be stored as an
integer.
• Python provides various standard data types that define the storage
method on each of them. The data types defined in Python are given
below.
1. Numbers
2. String
3. List
4. Tuple
5. set
6. Dictionary
• In Python the following data types are considered as Fundamental
Data types
• int
• float
• complex
• bool
• str
• int data type:
We can use int data type to represent whole numbers (integral values)
Eg: f1.py
a=10
type(a) #int
Output:
C:\Users\My Name>python fl.py

<class ‘int'>

Note: In Python2 we have long data type to represent very large integral values. But
in Python3 there is no long type explicitly and we can represent long values also by
using int type only.
• Float: Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
• Example: fl.py:
x = 1.10
y = 1.0 Output:
z = -35.59 C:\Users\My Name>python fl.py

print(type(x)) <class 'float'>


print(type(y)) <class 'float'>
print(type(z)) <class 'float'>
Complex: Numbers are written with a "j" as the imaginary part:
Example: complx.py
Output:
• x = 3+5j C:\Users\My Name>python complx.py
y = 5j
z = -5j <class 'complex'>
<class 'complex'>
print(type(x)) <class 'complex'>
print(type(y))
print(type(z))
Python Strings
• str represents String data type.
• A String is a sequence of characters enclosed within single quotes or
double quotes.
s1=‘geetha govindam'
s1=“vijayadevarakonda"
• By using single quotes or double quotes we cannot represent multi
line string literals.
s1=“siva
bhargav”
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'''
Slicing of Strings:
• slice means a piece [ : ] operator is called slice operator, which can be
used to retrieve parts of String.
• In Python Strings follows zero based index.
• The index can be either +ve or -ve.
• +ve index means forward direction from Left to Right
• -ve index means backward direction from Right to Left

-6 -5 -4 -3 -2 -1
P Y T H O N

0 1 2 3 4 5
>>>s=“PYTHON” >>>s*3
>>>s[0] PYTHON PYTHON PYTHON
P
>>>len(s)
>>>s[-1]
6
N
>>>s[0:5]
PYTHO len() in-built function:
>>>s[0:]
PYTHON We can use len() function to find the
>>>s[:]
number of characters present in the
PYTHON
>>>S[:5]
string.
PYTHO
• In Python, we can represent char values also by using str type and
explicitly char type is not available.
• Eg:
>>> c='a‘
>>> type(c)

<class 'str'>
bool data type:

• We can use this data type to represent boolean values.


• The only allowed values for this data type are:
True and False
• Internally Python represents True as 1 and False as 0
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True

>>>True+True==>2

>>>True-False==>1
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))
Python_classes>py test.py
Enter List:[10,20,30,40]
[10, 20, 30, 40]
<class 'list'>
• With list() function:
l=list(range(0,10,2))
print(l)
print(type(l))

Python_classes>py test.py
[0, 2, 4, 6, 8]
<class 'list'>
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] D:\Python_classes>py 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
D:\Python_classes>py 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)
D:\Python_classes>py 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)

D:\Python_classes>py 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)

D:\Python_classes>py 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)

D:\Python_classes>py 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:
D:\Python_classes>py 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)

D:\Python_classes>py 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)

D:\Python_classes>py 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 use 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
D:\Python_classes>py 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:
D:\Python_classes>py test.py
[40, 30, 20, 10]
2. sorted() 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=["Siva", "santosh", "Bhargav", "Prashanth", "GNRamesh"]
a. sort()
print(a) # ['Bhargav', 'GNRamesh', 'Prashanth', 'Siva', 'santosh']
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=["Siva", "santosh", "Bhargav", "Prashanth", "GNRamesh"]
a.sort(reverse=True)
print(a)
Output:
['santosh', 'Siva', 'Prashanth', 'GNRamesh', 'Bhargav']
• 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: Output
n=[10,20,[30,40]] D:\Python_classes>py test.py
print(n) [10, 20, [30, 40]]
print(n[0]) 10
[30, 40]
print(n[2])
30
print(n[2][0]) 40
print(n[2][1])
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 data type is exactly same as list data type except that it is
immutable.i.e we cannot change values.
2.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.
3.Tuple elements can be represented within parenthesis

4. If our data is fixed and never changes then we should go for Tuple.
5. Insertion Order is preserved
6. Duplicates are allowed
7. Heterogeneous objects are allowed.
8. We can preserve insertion order and we can differentiate duplicate
objects by using index. Hence index will play very important role in
Tuple also.
9. 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)
10. We can represent Tuple elements within Parenthesis and with
comma seperator.Parenethesis are optional but recommended to use.
Eg:1
t=10,20,30,40 T1 = (201, "Aishwarya", 20)
print(t) T2 = ("Akhila", "Anusha", "Kavya")
print(type(t))

Output
(10, 20, 30, 40)
<class 'tuple'>
Eg:2
t=()
print(type(t)) # tuple
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)
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
• 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)
• 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.
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}
2. update([x,y,z]):
To add multiple items to the set.

Eg:
s={10,20,30}
s.update([50,60])
print(s)
• 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={40,10,30,20}
print(s)
print(s.pop())
print(s)

Output
{40, 10, 20, 30}
40
{10, 20, 30}
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'
# Python program to understand
# use of frozenset function

# creating a list
favourite_subject = [“python", "DBMS",
“java"]

# making it frozenset type


f_subject = frozenset(favourite_subject)

# below line will generate error

f_subject[1] = "Networking" Output:


Traceback (most recent call last): File
"/home/0fbd773df8aa631590ed0f3f865c1437.py",
line 12, in f_subject[1] = "Networking"
TypeError: 'frozenset' object does not
support item assignment
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. Hetrogeneous 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:“pavan",200:"ravi",300:"shiva"}
print(d)
d[400]=“Bhargav"
print(d)
d[100]=“Prashanth"
print(d)

• Output:
{100: ‘pavan', 200: 'ravi', 300: 'shiva'}
{100: ‘pavan', 200: 'ravi', 300: 'shiva', 400: 'Bhargav'}
{100: ‘Prashanth', 200: 'ravi', 300: 'shiva', 400: ‘Bhargav'}
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:"Nota",200:"Taxiwala",300:"geetagov"}
print(d) Output
del d[100] {100: 'Nota', 200: 'Taxiwala', 300: 'geetagov'}
print(d) {200: 'Taxiwala', 300: 'geetagov'}
del d[400] KeyError: 400
• d.clear() : To remove all entries from the dictionary
Eg:
d={100:"pavan",200:"ravi",300:"shiva"}
print(d)
d.clear()
print(d)

Output
{100: 'pavan', 200: 'ravi', 300: 'shiva'}
{}
• del d
To delete total dictionary. Now we cannot access d
Eg:
d={100:"ohbaby",200:"Issmart",300:"Maharshi"}
print(d)
del d
print(d)

Output:
{100: 'ohbaby', 200: 'Issmart ', 300: 'Maharshi'}
Name Error: name 'd' is not defined
• 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,"RaceGurram")])==>It creates
dictionary with the given list of tuple elements.
2. len()
• Returns the number of items in the dictionary

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.
• 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"}
for k,v in d.items():
print(k,"--",v)

Output:
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)
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
• 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 exceed.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.
• 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
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.
• Acess 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.
Operators:
Operator is a symbol that performs certain operations.
Python provides the following set of operators
1. Arithmetic Operators
2. Relational Operators
3. Equality Operators
4. Logical Operators
5. Assignment Operators
6. Bitwise Operators
7.Ternary Operator
8. Special operators
1. Arithmetic Operators:
+ ==>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
2.Relational Operators:
>,>=,<,<=
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
3.Equality operators:
== , !=
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
4.Logical Operators:
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
5.Assignment Operators:

• 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
6.Bitwise Operators:
• 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
print(4&5) ==>4
print(4|5) ==>5
print(4^5) ==>1
• 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
7.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)
8.Special operators:
• Python defines the following 2 special operators
1. Identity Operators
2. Membership operators

1. Identity Operators
We can use identity operators for address comparison. Two identity
operators are available:
1. is
2. is not
r1 is r2 returns True if both r1 and r2 are pointing to the same object
r1 is not r2 returns True if both r1 and r2 are not pointing to the same
object
Eg:
>>>a=10
>>>b=10
>>>print(a is b) True
>>>x=True
>>>y=True
print(x is y) True
2.Membership operators:
• 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
Eg: 2
list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1) True
print("tunny" in list1) False
print("tunny" not in list1) True
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()
File Handling:
• To store our data permanently for future purpose. For this requirement we
should go for files.

There are 2 types of files:


1. Text Files:
Usually we can use text files to store character data
eg: abc.txt
2. Binary Files:
Usually we can use binary files to store binary data like images,video files,
audio files etc...
• File Built-in functions:
• Before performing any operation (like read or write) on the file, first we
have to open that file. For this we should use Python's inbuilt function
open().

• But at the time of open, we have to specify mode, which represents the
purpose of opening file.

• Syntax :handle = open(file_name, access_mode = 'r’)


(Or)
f = open(filename, mode)
Opening a file example:
f = open("abc.txt","w")
We are opening abc.txt file for writing data.

Closing a File:
• After completing our operations on the file, it is highly recommended to
close the file. For this we have to use close() function.
Syntax : handle.close()

for ex: f.close()


The allowed modes in Python are:
1) r ->open an existing file for read operation. The file pointer is positioned
at the beginning of the file. If the specified file does not exist then we will
get FileNotFoundError. This is default mode.

2) w -> open an existing file for write operation. If the file already contains
some data then it will be overridden. If the specified file is not already
available then this mode will create that file.

3) a -> open an existing file for append operation. It won't override existing
data. If the specified file is not already available then this mode will create a
new file.
4) r+ ->To read and write data into the file. The previous data in the file will not
be deleted. The file pointer is placed at the beginning of the file.

5) w+ ->To write and read data. It will override existing data.

6) a+ ->To append and read data from the file. It wont override existing data.

7) x ->To open a file in exclusive creation mode for write operation. If the file
already exists then we will get FileExistsError.

• Note: All the above modes are applicable for text files. If the above modes
suffixed with 'b' then these represents for binary files.
• Eg: rb, wb, ab, r+b, w+b, a+b, xb
Various File Attributes (properties) of File Object:
• Once we open a file and we got file object, we can get various details related
to that file by using its properties.
name : Name of opened file

mode : Mode in which the file is opened

Closed : Returns boolean value indicates that file is closed or not

readable() : Returns boolean value indicates that whether file is readable or not

writable() : Returns boolean value indicates that whether file is writable or not.
Example program for file properties:
Output
f=open("abc.txt",'w') D:\Python_classes>py test.py
File Name: abc.txt
print("File Name: ",f.name) File Mode: w
print("File Mode: ",f.mode) Is File Readable: False
Is File Writable: True
print("Is File Readable: ",f.readable())
Is File Closed : False
print("Is File Writable: ",f.writable()) Is File Closed : True
print("Is File Closed : ",f.closed)
f.close()
print("Is File Closed : ",f.closed)
File Methods:
File methods are 2 types: 1) Input method 2) Output method

1. Input methods (Reading Character Data from text files):


• We can read character data from text file by using the following read methods.
read()->To read total data from the file
read(n) -> To read 'n' characters from the file
readline()->To read only one line
readlines()->To read all lines into a list
Eg 1: To read total data from the file
f=open("abc.txt",'r') Output:
data=f.read() sunny
bunny
print(data)
chinny
f.close() vinny

Eg 2: To read only first 10 characters:


Output:
f=open("abc.txt",'r')
sunny
data=f.read(10) bunn
print(data)
f.close()
Eg 3: To read data line by line:

f=open("abc.txt",'r') Output:
line1=f.readline()
sunny
print(line1,end='') bunny
line2=f.readline() chinny
print(line2,end='')
line3=f.readline()
print(line3,end='')
f.close()
Eg 4: To read all lines into list:
f=open("abc.txt",'r') Output
lines=f.readlines() sunny
for line in lines: bunny
chinny
print(line,end='')
vinny
f.close()
Eg 5: Output
f=open("abc.txt","r")
Sun
print(f.read(3))
ny
print(f.readline())
print(f.read(4)) bunn
Remaining data
print("Remaining data") chinny
print(f.read()) vinny
• 2. Output functions:
• The write() built-in method has the opposite functionality as read() and
readline(). It takes a string that can consist of one or more lines of text data or
a block of bytes and writes the data to the file.

• The writelines() method operates on a list just like readlines(), but takes a list
of strings and writes them out to a file.

• Line termination characters are not inserted between each line, so if desired,
they must be added to the end of each line before writelines() is called.

Note: There is no "writeline()" method since it would be equivalent to calling


write() with a single line string terminated with a NEWLINE character.
Writing data to text files:
We can write character data to the text files by using the following 2
methods.
write(str)
writelines(list of lines) abcd.txt:
Eg: Python
f=open("abcd.txt",'w') Programming
f.write(“Python\n") Language
f.write(“Programming\n")
f.write(“Language\n")
print("Data written to the file successfully")
f.close()
• Note: In the above program, data present in the file will be overridden every
time if we run the program. Instead of overriding if we want append
operation then we should open the file as follows.
abcd.txt:
Python
f=open("abcd.txt",‘a')
Programming
list=["sunny\n","bunny\n","vinny\n","chinny"] Language
f.writelines(list) sunny
print("List of lines written to the file successfully") bunny
f.close() vinny
chinny
Note: while writing data by using write() methods, compulsory we have to
provide line separator(\n),otherwise total data should be written to a single
line.
• Standard Files:
• There are generally three standard files that are made available to you when
your program starts.
• These are standard input (usually the keyboard), standard output (buffered
output to the monitor or display),and standard error (unbuffered output to
the screen).
• These files are named stdin, stdout, and stderr and take their names from
the C language.
• Python makes these file handles available to you from the sys module. Once
you import sys, you have access to these files as sys.stdin, sys.stdout, and
sys.stderr.

• The print statement normally outputs to sys.stdout while the raw_input() or


input() built-in function receives its input from sys.stdin.

• sys.* are files, you have to manage the line separation characters.

• The print statement has the built-in feature of automatically adding one to the
end of a string to output.
• Command-Line Arguments:
• The Argument which are passing at the time of execution are called
Command Line Arguments.
• The sys module also provides access to any command-line arguments via
sys.argv
• argv is not Array it is a List. It is available in sys Module.

• Eg: D:\Python_classes py test.py 10 20 30

Command Line Arguments


Note:
• argv[0] represents name of Program. But not first Command Line Argument.
• argv[1] represent First Command Line Argument.
• len(argv) returns no of arguments passed, which is available in sys module.

Program to check type of argv from sys:

import argv Output:


print(type(argv)) <class 'module'>
<class 'module'>
Program to display Command Line Arguments
test.py
from sys import argv
print(“The Number of Command Line Arguments:”, len(argv))
print(“The List of Command Line Arguments:”, argv)
print(“Command Line Arguments one by one:”)
for x in argv: Output:
print(x) D:\Python_classes>py test.py 10 20 30
The Number of Command Line Arguments: 4
test.py 10 20 30
The List of Command Line Arguments: [‘test.py’, ‘10’,’20’,’30’]
Command Line Arguments one by one:
test.py
10
20
30
Program to add all the Command Line Arguments and display sum:

from sys import argv


sum=0
args=argv[1:]
Output:
for x in args :
n=int(x) D:\Python_classes>py test.py 10 20 30 40
The Sum: 100
sum=sum+n
print("The Sum:",sum)
cla.py
from sys import argv
print(argv[1])
--------------------------------------------------------------------------------
D:\Python_classes>py cla.py Python Programming
Python

D:\Python_classes>py cla.py 'Narendra Damodardas Modi'


'Narendra

D:\Python_classes>py cla.py "Article 35A"


Article 35A
• space is separator between command line arguments. If our command line
argument itself contains space then we should enclose within double
quotes(but not single quotes).

• Based on our requirement, we can convert into corresponding type by using


type casting methods.

• Eg: Output:
from sys import argv D:\Python_classes>py test.py 10 20
1020
print(argv[1]+argv[2]) 30
print(int(argv[1])+int(argv[2]))
File System:

• Access to file system occurs mostly through the Python os module.


• The os module is actually a front-end real module that is loaded, a module that
is clearly operating system dependent.
• This"real" module may be one of the following: posix (Unix-based, i.e., Linux,
MacOS X, *BSD, Solaris,etc.), nt (Win32), mac (old MacOS), dos (DOS), os2
(OS/2), etc.
Working with Directories:
• It is very common requirement to perform operations for directories like
1. To know current working directory
2. To create a new directory
3. To remove an existing directory
4. To rename a directory
5. To list contents of the directory

Note:
• To perform these operations, Python provides inbuilt module os, which
contains several functions to perform directory related operations.
To Know Current Working Directory:
Output:

import os Current Working Directory:


cwd=os.getcwd() C:\Users\Dell\Desktop
print("Current Working Directory:",cwd)

To create a sub directory in the current working directory:


Output:
import os
os.mkdir("mysub") Creates a sub directory called my sub
mysub directory created in cwd
print("mysub directory created in cwd")
To create a sub directory in mysub directory:
cwd
|-mysub
|-mysub2

import os
os.mkdir("mysub/mysub2") C:\Users\Dell\Desktop\mysub\mysub2

print("mysub2 created inside mysub")


• To create multiple directories like sub1 in that sub2 in that sub3:

import os
os.makedirs("sub1/sub2/sub3")
print("sub1 and in that sub2 and in that sub3 directories created")

To remove a directory:

import os
os.rmdir("mysub/mysub2")
print("mysub2 directory deleted")
• To remove multiple directories in the path:

import os
os.removedirs("sub1/sub2/sub3")
print("All 3 directories sub1,sub2 and sub3 removed")

To rename a directory:

import os
os.rename("mysub","newdir")
print("mysub directory renamed to newdir")
• To know contents of directory:
• os module provides listdir() to list out the contents of the specified directory.
It won’t display the contents of sub directory.
• Eg:
import os
print(os.listdir("."))

Output:

D:\Python_classes>py test.py
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe',
'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools',
'vcruntime140.dll']
• The above program display contents of current working directory but not
contents of sub directories.
• If we want the contents of a directory including sub directories, then we
should go for walk() function.
• To know contents of directory including sub directories:
• We have to use walk() function [walk in the directory so that we can aware
all contents of that directory].

• os.walk(path,topdown=True,onerror=None,followlinks=False)

• It returns an Iterator object whose contents can be displayed by using for


loop

• path-->Directory path means cwd.


• topdown =True --->Travel from top to bottom
• onerror=None --->on error detected which function has to execute.
• followlinks=True -->To visit directories pointed by symbolic links
To display all contents of Current working directory including sub directories:
import os
for dirpath,dirnames,filenames in os.walk('.’):
print("Current Directory Path:",dirpath)
print("Directories:",dirnames)
Output:
print("Files:",filenames)
print() Current Directory Path: .
Directories: ['Custom Office Templates', 'My
Music', 'My Pictures', 'My Videos']
Files: ['desktop.ini', 'file.py']

Current Directory Path: .\Custom Office


Templates
Directories: []
Files: []
• Note: To display contents of particular directory, we have to provide that
directory name as argument to walk() function.

• os.walk("directoryname")
Output:
import os ('softwares', ['data-integration', 'ibm rational rose', 'Oracle 10
G', 'Wamp Server', 'weka'], ['apache-tomcat-9.0.0.M9.exe',
for file in os.walk("softwares"): 'eclipse-java-indigo-SR2-win32-x86_65.zip', 'jdk-8u144-
print(file) windows-x64.exe', 'mysql-5.5.46-win32.msi', 'mysql-connector-
java-8.0.12.jar', 'netbeans-7.1-ml-javaee-windows.exe',
'npp.7.2.2.Installer.exe', 'putty.exe', 'python-3.7.2.exe', 'R-3.5.2-
win.exe', 'staruml-5.0-with-cm.exe', 'turboc.exe', 'WampServer-
print('finished') 3.1.7-(32-bit).exe’])

finished
• File Execution: (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 mess
age on the console.
• To run this file named as first.py, we need to run the following command
on the terminal.
• $ python3 first.py
• Modules and Files
• A module is a logical way to physically organize and distinguish related pieces
of Python code into individual files. (Or)

• A group of functions, variables and classes saved to a file, which is nothing but
module. Every Python file (.py) acts as a module.

• Once a module is created, you may import that module for use from another
module using the import statement.
To Import a Module:
import module_name
Ex: import sys
import os
Eg: mathop.py
x=888
def add(a,b):
print("The Sum:",a+b)
def product(a,b):
print("The Product:",a*b)

mathop module contains one variable and 2 functions.


If we want to use members of module in our program then we should import
that module.
Access a Module Function or Module Variable:
• Once imported, a module's attributes (functions and variables) can be
accessed using the familiar dotted.

Attribute notation:

module.function()
module.variable
Ex :
test.py: Output:

import mathop 888


print(mathop.x) The Sum: 30
The Product: 200
mathop.add(10,20)
mathop.product(10,20)

Note:
• whenever we are using a module in our program, for that module compiled
file will be generated and stored in the hard disk permanently.
Renaming a module at the time of import (module aliasing):

Syntax: import module_name as alias_name

>>>import mathop as mo
Here mathop is original module name and mo is alias name. We can access
members by using alias name mo

test.py: Output:
import mathop as mo
print(mo.x) 888
The Sum: 30
mo.add(10,20) The Product: 200
mo.product(10,20)
Second way of import from ... import:
We can import particular members of module by using from ... import .
The main advantage of this is we can access members directly without using
module name.

Syn: from module_name import module_members

Eg:
from mathop import x, add
print(x)
add(10,20)
We can import all members of a module by using *

Syn: from module_name import *

test.py:
from mathop import *
print(x)
add(10,20)
product(10,20)
Built-in modules:

Working with math module:

• Python provides inbuilt module math.


• This module defines several functions which can be used for mathematical operations.
• The main important functions are
1. sqrt(x)
2. ceil(x)
3. floor(x)
4. fabs(x)
5.log(x)
6. sin(x)
7. tan(x)
Example:
Output
from math import *
2.0
print(sqrt(4)) 11
print(ceil(10.1)) 10
print(floor(10.1)) 10.6
print(fabs(-10.6)) 10.6
print(fabs(10.6))
Working with random module:
• This module defines several functions to generate random numbers.
• We can use these functions while developing games,in cryptography
and to generate random numbers on fly for authentication
1.random() function:
• This function always generate some float value between 0 and 1
( not inclusive) 0<x<1
Example
from random import *
for i in range(10):
print(random())
Output
0.4572685609302056
0.6584325233197768
0.15444034016553587
0.18351427005232201
0.1330257265904884
0.9291139798071045
0.6586741197891783
0.8901649834019002
0.25540891083913053
0.7290504335962871
2.randint() function:
To generate random integer beween two given numbers(inclusive)
Example:
Output
51
44
from random import * 39
for i in range(10): 70
49
print(randint(1,100)) 74
52
10
40
8
3.choice() function:
It wont return random number.
It will return a random object from the given list or tuple.
from random import *
list=["Sunny","Bunny","Chinny","Vinny","pinny"]
for i in range(10):
print(choice(list))
Output:

Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
Vinny
Bunny
Sunny
2. Platform module:
• Provides various details about the particular operating system in use.
• It has a in built function called system which specifies the name of os.

demo.py
Output
import platform
x = platform.system() WINDOWS

print(x)
Importing Modules:
• Various possibilities of import:
1. import modulename
2. import module1,module2,module3
3. import module1 as m
4. import module1 as m1,module2 as m2,module3
5. from module import member
6. from module import member1,member2,memebr3
7. from module import memeber1 as x
8. from module import *
member aliasing:

from mathop import x as y,add as sum


print(y)
sum(10,20)

• Once we defined as alias name , we should use alias name only and we
should not use original name.

Eg:
from mathop import x as y
print(x)==>NameError: name 'x' is not defined
• Reloading a Module:
• By default module will be loaded only once even though we are importing
multiple times. For example .

module1.py:
print("This is from module1")

test.py
import module1 Output
import module1 This is from module1
This is test module
import module1
import module1
print("This is test module")
• Note: The problem in this approach is after loading a module if it is updated
outside then updated version of module1 is not available to our program.

• To solve this problem by reloading module explicitly i.e by using reload()


function of imp module.

from imp import reload

• The main advantage of explicit module reloading is we can ensure that


updated version is always available to our program.
Example program for reloading module:
test.py
Output
import module1
this is from module 1:
import module1 this is from module 1:
from imp import reload this is from module 1:
reload(module1) This is test module

reload(module1)
reload(module1)
print("This is test module")

• In the above program module1 will be loaded 4 times in that 1 time by default
and 3 times explicitly.
Packages:
• It is an encapsulation mechanism to group related modules into a single
unit.
• Package is nothing but folder or directory which represents collection of
Python modules.
• Any folder or directory contains __init__.py file, is considered as a Python
package. This file can be empty.
• A package can contain sub packages also.

The __init__.py file can contain the same Python code that any other module can contain, and Python will add
some additional attributes to the module when it is imported.
• The main advantages of package statement are:
1. We can resolve naming conflicts
2. We can identify our components uniquely
3. It improves modularity of the application
• Eg 1:
C:\Users\Dell\Desktop>
|-test.py file in the above path
|-pack1------ folder name
|-module1.py Files inside the pack1 folder as a part of
|-__init__.py package.

__init__.py: it is empty file.


module1.py
def f1():
print("Hello this is from module1 present in pack1")

test.py Output:
import pack1.module1 Hello this is from module1 present in pack1
pack1.module1.f1()
Second way of accessing :
test.py
from pack1.module1 import f1
f1()
Output:

Hello this is from module1 present in pack1


• Eg 2:
• C:\Users\Dell\Desktop>
|-test.py
|-com
|-module1.py
|-__init__.py
|-python
|-module2.py
|-__init__.py

__init__.py: empty file


module1.py
def f1():
print("Hello this is from module1 present in com")

module2.py
def f2():
print("Hello this is from module2 present in com.python")
test.py
from com.module1 import f1
from com.python.module2 import f2
f1()
f2()

Output
C:Users\Dell\Desktop\py test.py
Hello this is from module1 present in com
Hello this is from module2 present in com.python
• Ex:3
C:\Users\Dell\Desktop>
|pckg1
|-a.py
|-__init__.py
|pckg2
|-client.py
|-__init__.py

__init__.py: empty file


A.py
def a():
print(“hello”)

Client.py
import sys
Output:
sys.path.append("C:\Users\Dell\Desktop")
import pckg1.A Hello
pckg1.A.a()
• Diagram of library, packages, modules which contains functions, classes and
variables.
Exception Handling:
In any programming language there are 2 types of errors are possible.
1. Syntax Errors
2. Runtime Errors

1.Syntax Errors:
The errors which occurs because of invalid syntax are called syntax errors.
Eg 1:
x=10
if x==10
print("Hello")
SyntaxError: invalid syntax
Eg 2:
print "Hello“
SyntaxError: Missing parentheses in call to 'print’ not valid in python 3.0.

• “Programmer is responsible to correct these syntax errors”. Once all syntax


errors are corrected then only program execution will be started.

2. Runtime Errors: (Also known as exceptions)


• While executing the program if something goes wrong because of end user
input or programming logic or memory problems etc., then we will get
Runtime Errors.
Eg:1 print(10/0) ==> ZeroDivisionError: division by zero
print(10/"ten") ==> TypeError: unsupported operand type(s) for /: 'int' and
'str’

Eg:2 test.py
x=int(input("Enter Number:"))
print(x)

Output:
D:\Python_classes>python test.py
Enter Number: ten
ValueError: invalid literal for int() with base 10: 'ten’.
Note: Exception Handling concept applicable for Runtime errors but not for
syntax errors.

Exception:
• An unwanted and unexpected event that disturbs normal flow of program is
called exception.
Eg: Stmt 1
ZeroDivisionError Stmt 2 Statements which are executed

TypeError Stmt 3
Stmt 4  Exception or Run time error at line 4
ValueError
Stmt 5
FileNotFoundError Stmt 6
Statements which are not executed
EOFError Stmt 7
SleepingError Stmt 8
TyrePuncturedError
• It is highly recommended to handle exceptions.
• The main objective of exception handling is Graceful Termination of the
program.

Exception Handling:
• It does not mean repairing an exception.
• Defining a alternative way to continue rest of the program normally.
Default Exception Handing:
• Every exception in Python is an object. For every exception type the
corresponding classes are available.

• Whenever an exception occurs PVM will create the corresponding exception


object and will check for handling code.

• If handling code is not available then Python interpreter terminates the


program abnormally and prints corresponding exception information to the
console.

• The rest of the program won't be executed.


• Eg:
print("Hello")
print(10/0)
print("Hi")

D:\Python_classes>py test.py
Hello
Traceback (most recent call last):
File "test.py", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero
Exception Handling by using try-except:
• It is highly recommended to handle exceptions.
• The code which may raise exception is called risky code.
• we have to take risky code inside try block. The corresponding handling code
we have to take inside except block i.e., similar to catch block in java.

try-except block:

try:
<Risky Code or error code>
except XXX: //XXX exception
<Handling code/Alternative Code>
Exception without try-except block:
print("Hi ") Output:
Hi
print(10/0)
ZeroDivisionError: division by zero
print("Hello") Abnormal termination/Non-Graceful Termination

Exception with try-except block:


print("Hi")
try: Output:
print(10/0) Hi
except ZeroDivisionError: 5.0
Hello
print(10/2)
print("Hello")
Ex 2: using try-except block:
try:
f = open("testfile", "w")
f.write("This is my test file for exception handling!!")
except IOError:
print("Error: can't find file or read data")
else:
print("Written content in the file successfully")
f.close()
To know exception information:
try:
print(10/0)
except ZeroDivisionError as msg:
print("exception raised and its description is:",msg)

Output:
exception raised and its description is: division by zero

• Here exception data is stored in a exception object i.e. msg.


• In the next statement we are printing the exception object to print the
exception details.
try with multiple except blocks:
try:
stmt 1 If try with multiple except blocks available then
stmt 2 based on raised exception the corresponding
except block will be executed.
-------
except Exception1:
stmt 3
stmt 4
----------
except Exception2:
stmt 5
stmt 6
----------
• Example program for try with multiple except blocks:

prog.py D:\Python_classes>prog test.py


Enter First Number: 10
try: Enter Second Number: 2
x=int(input("Enter First Number: ")) 5.0
-----------------------------------------------------
y=int(input("Enter Second Number: ")) D:\Python_classes>prog test.py
print(x/y) Enter First Number: 10
except ZeroDivisionError : Enter Second Number: 0
Can't Divide with Zero
print("Can't Divide with Zero") -----------------------------------------------------
except ValueError: D:\Python_classes>prog test.py
Enter First Number: 10
print("please provide int value only") Enter Second Number: ten
please provide int value only
Eg: 2
prog.py
try: D:\Python_classes>prog test.py
Enter First Number: 10
x=int(input("Enter First Number: ")) Enter Second Number: 0
y=int(input("Enter Second Number: ")) ??????????????????????
print(x/y)
except ArithmeticError :
print("ArithmeticError")
except ZeroDivisionError:
print("ZeroDivisionError")
• Note: If try with multiple except blocks available then the order of
these except blocks is important .
• Python interpreter will always consider from top to bottom until
matched except block identified.
Note: If try with multiple except blocks available then default except block
should be last, otherwise we will get SyntaxError.
Eg:
try:
print(10/0)
except:
print("Default Except")
except ZeroDivisionError:
print("ZeroDivisionError")

SyntaxError: default 'except:' must be last


• The following are various possible combinations of except blocks
1. except ZeroDivisionError:
2. except ZeroDivisionError as msg:
3. except (ZeroDivisionError,ValueError) :
4. except (ZeroDivisionError,ValueError) as msg:
5. except :
finally block:
• It is not recommended to maintain clean up code(Resource Deallocating
Code or Resource Releasing code) inside try block because there is no
guarantee for the execution of every statement inside try block always.

2. It is not recommended to maintain clean up code inside except block,


because if there is no exception then except block won't be executed.

3.To maintain clean up code which should be executed always irrespective of


whether exception raised or not raised and whether exception handled or
not handled. Such type of best place is nothing but finally block.
Syntax:

try:
Risky Code
except:
Handling Code
finally:
Cleanup code

• The speciality of finally block is it will be executed always whether


exception raised or not raised and whether exception handled or
not handled.
Case-1: If there is no exception Case-2: If there is an exception raised but
try: handled:
print("try") try:
except: print("try")
print("except") print(10/0)
except ZeroDivisionError:
finally: print("except")
print("finally") finally:
print("finally")
Output
try Output
try
finally
except
Finally
Case-3: If there is an exception raised but not handled:
try:
print("try")
print(10/0)
except NameError:
print("except")
finally:
print("finally")

Output
try
finally
ZeroDivisionError: division by zero(Abnormal Termination)
Note: If try with multiple except blocks available then default except block
should be last,otherwise we will get SyntaxError.
Eg:
try:
print(10/0)
except:
print("Default Except")
except ZeroDivisionError:
print("ZeroDivisionError")

SyntaxError: default 'except:' must be last


Note:
• Whenever we are using os._exit(0) function then Python Virtual Machine
itself will be shutdown.
• In this particular case finally won't be executed.
import os
try:
print("try") Output:
os._exit(0) try
except NameError: -----------------------------------------------------------------
print("except") os._exit(0) where 0 represents status code and it
indicates normal termination.
finally:
print("finally")
Nested try-except-finally blocks:
• We can take try-except-finally blocks inside try or except or finally blocks.i.e
nesting of try except finally is possible.
try:
----------
try:
-------------
except:
--------------
finally:
--------------
except:
----------
finally:
-----------
Eg:
finally:
try: print("outer finally block")
print("outer try block")
try: ---------------------------------------------
print("Inner try block")
print(10/0)
Output:
except ZeroDivisionError: outer try block
print("Inner except block") Inner try block
Inner except block
finally: Inner finally block
print("Inner finally block") outer finally block
except:
print("outer except block")
else block with try-except-finally:
• We can use else block with try-except-finally blocks.else block will be
executed if and only if there are no exceptions inside try block. It is optional.
try:
<Risky Code>
except:
<will be executed if exception inside try>
else:
<will be executed if there is no exception inside try>
finally:
<will be executed whether exception raised or not raised and handled or
not>
Eg:1 Eg: 2
try: try:
print("try") print("try")
except: print(10/0)
except:
print("except") print("except")
else: else:
print("else") print("else")
finally: finally:
print("finally") print("finally")
Output:
Output: try
try except
else finally
finally
Various possible combinations of try-except-else-finally:
• Whenever we are writing try block, compulsory we should write except or
finally block i.e without except or finally block we cannot write try block.

• Whenever we are writing except block, compulsory we should write try


block. i.e except without try is always invalid.

• Whenever we are writing finally block, compulsory we should write try


block. i.e finally without try is always invalid.

• We can write multiple except blocks for the same try, but we cannot write
multiple finally blocks for the same try.
• Whenever we are writing else block compulsory except block should be there.
i.e without except we cannot write else block.

• In try-except-else-finally order is important.

• We can define try-except-else-finally inside try, except,else and finally blocks.


i.e nesting of try-except-else-finally is always possible.
Types of Exceptions:
In Python there are 2 types of exceptions are possible.
1. Predefined Exceptions
2. User Defined Exceptions

Predefined Exceptions: (Also known as in-built exceptions)


The exceptions which are raised automatically by Python virtual machine
whenever a particular event occurs, are called pre defined exceptions.
Eg :
ZeroDivisionError.
ValueError
TypeError etc.,
User Defined Exceptions:
• Also known as Customized Exceptions or Programmatic Exceptions.

• To define and raise exceptions explicitly by programmer to indicate that


something goes wrong ,such type of exceptions are called User Defined
Exceptions or Customized Exceptions.

• Programmer is responsible to define these exceptions and Python not having


any idea about these.

• Hence we have to raise explicitly based on our requirement by using "raise"


keyword.
Eg:
InSufficientFundsException
InvalidInputException
InvalidAgeException
Define and Raise Customized Exceptions:
• raise keyword is best suitable for customized exceptions but not for pre
defined exceptions.
• It is used to raise an exception with customized message.
Syntax: raise exceptionname(“exception message”)
Ex:
raise NameError(“Name doesn’t match”)-- not preferred

raise InvalidAgeError(“Age is not valid”) preferred


def status(age):
if age<18: Output:
raise NameError("Invalid age data") enter a valid age:2
not eligible to vote: Invalid age data
elif age>=18:
Voter Eligibility Test
print("eligible to vote")
---------------------------------------------------------
try: Output:
enter a valid age:45
age=int(input("enter a valid age:"))
eligible to vote
status(age) User entered valid data
except NameError as e: Voter Eligibility Test
print("not eligible to vote:",e)
else:
print("User entered valid data")
finally:
print("Voter Eligibility Test")
• Every Exception in Python is a class.

• All exception classes are child classes of BaseException i.e., every exception
class extend BaseException either directly or indirectly.

• Hence BaseException acts as root for Python Exception Hierarchy.

• Most of the times being a programmer we have to concentrate Exception and


its child classes.
How to Define a class?
We can define a class by using class keyword.
Syntax:
class className:
''' documenttation string '''
variables:instance variables,static and local variables
methods: instance methods,static methods,class methods

Documentation string represents description of the class. Within the


class doc string is always optional. We can get doc string by using the
following 2 ways.
1. print(classname.__doc__)
2. help(classname)
Example:
class Student:
''''' This is student class with required data'''
print(Student.__doc__)
help(Student)
• Within the Python class we can represent data by using variables.
There are 3 types of variables are allowed.
1. Instance Variables (Object Level Variables)
2. Static Variables (Class Level Variables)
3. Local variables (Method Level Variables)
• Within the Python class, we can represent operations by
using methods. The following are various types of allowed
methods

1. Instance Methods
2. Class Methods
3. Static Methods
Example for class:
class Student:
'''''Developed by Gudio for python demo'''''
def __init__(self):
self.name=‘’hi”
self.age=40
self.marks=80

def talk(self):
print("Hello I am :",self.name)
print("My Age is:",self.age)
print("My Marks are:",self.marks)
What is Object:
Pysical existence of a class is nothing but object. We can create any
number of objects for a class.

Syntax to create object: referencevariable = classname()


Example: s = Student()

What is Reference Variable:


The variable which can be used to refer object is called reference
variable.
By using reference variable, we can access properties and methods of
object.
• Program: Write a Python program to create a Student class and Creates an
object to it. Call the method talk() to display student details
class Student:
def __init__(self,name,rollno,marks):
self.name=name
self.rollno=rollno
self.marks=marks
def talk(self):
print("Hello My Name is:",self.name)
print("My Rollno is:",self.rollno)
print("My Marks are:",self.marks)
s1=Student(“G",101,80)
s1.talk()
output
• Hello My Name is: G
• My Rollno is: 101
• My Marks are: 80
Self variable:
self is the default variable which is always pointing to current object
(like this keyword in Java)
By using self we can access instance variables and instance methods of
object.

Note:
1. self should be first parameter inside constructor
def __init__(self):
2. self should be first parameter inside instance methods
def talk(self):
Constructor Concept:
1. Constructor is a special method in python.
2. The name of the constructor should be __init__(self)
3. Constructor will be executed automatically at the time of object creation.
4. The main purpose of constructor is to declare and initialize instance
variables.
5. Per object constructor will be executed only once.
6. Constructor can take at least one argument(atleast self)
7. Constructor is optional and if we are not providing any constructor then
python will provide default constructor.
Example for default constructor
def __init__(self):
Program to demonstrate constructor will execute only once per object:

class Test:
def __init__(self):
print("Constructor execution...")
def m1(self):
print("Method execution...")
t1=Test()
t2=Test()
t3=Test()
t1.m1()
• Output
Constructor exeuction...
Constructor exeuction...
Constructor exeuction...
Method execution...
Types of Variables:
Inside Python class 3 types of variables are allowed.
1. Instance Variables (Object Level Variables)
2. Static Variables (Class Level Variables)
3. Local variables (Method Level Variables)
Where we can declare Instance variables:
1. Inside Constructor by using self variable
2. Inside Instance Method by using self variable
3. Outside of the class by using object reference variable

1. Inside Constructor by using self variable:


We can declare instance variables inside a constructor by using self keyword. Once
we create object, automatically these variables will be added to the object.
Example:
class Employee:
def __init__(self):
self.eno=100
self.ename=‘g’
self.esal=10000
e=Employee()
print(e.__dict__)

• Output: {'eno': 100, 'ename’: ‘g', 'esal': 10000}


2.Inside Instance Method by using self variable:
• We can also declare instance variables inside instance method by
using self variable. If any instance variable declared inside instance
method, that instance variable will be added once we call taht
method.
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t=Test()
t.m1()
print(t.__dict__)
3.Outside of the class by using object reference variable:

We can also add instance variables outside of a class to a particular


object.

class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t=Test()
t.m1()
t.d=40
print(t.__dict__)
How to access Instance variables:
• We can access instance variables with in the class by using self
variable and outside of the class by using object reference.
class Test:
def __init__(self):
self.a=10
self.b=20
def display(self):
print(self.a)
print(self.b)
t=Test()
t.display()
print(t.a,t.b)
Regular Expressions
• If we want to represent a group of Strings according to a particular
format/pattern then we should go for Regular Expressions.
• A regular expression is a special sequence of characters that helps you match or
find other strings or sets of strings, using a specialized syntax held in a pattern
• Regular Expressions is a declarative mechanism to represent a group of Strings
according to particular format/pattern.

Ex: Regular expressions to search the string to see if it starts with "The" and ends
with “India":
"^The.*India$"
Application areas of Regular Expressions :

The main important application areas of Regular Expressions are


1. To develop validation frameworks/validation logic
2. To develop Pattern matching applications (ctrl-f in windows, grep in
UNIX etc)
3. To develop Translators like compilers, interpreters etc
4. To develop digital circuits
5. To develop communication protocols like TCP/IP, UDP etc.
Special Characters in Regular Expressions

A special sequence is a \ followed by one of the


characters in the list below, and has a special
meaning:
Character Description Example

\A Returns a match if the specified characters are at the beginning of the string "\AThe"

\b Returns a match where the specified characters are at the beginning or at the end of r"\bain"
a word r"ain\b"
\B Returns a match where the specified characters are present, but NOT at the r"\Bain"
beginning (or at the end) of a word r"ain\B"
\d Returns a match where the string contains digits (numbers from 0-9) "\d"

\D Returns a match where the string DOES NOT contain digits "\D"
\s Returns a match where the string contains a white space character "\s"

\S Returns a match where the string DOES NOT contain a white space character "\S"

\w Returns a match where the string contains any word characters (characters from a to "\w"
Z, digits from 0-9, and the underscore _ character)

\W Returns a match where the string DOES NOT contain any word characters "\W"

\Z Returns a match if the specified characters are at the end of the string "Spain\Z"
Special Symbols or Meta characters:
Qunatifiers:

• We can use quantifiers to specify the number of occurrences to match.


a  Exactly one 'a'
a+  Atleast one 'a'
a* Any number of a's including zero number
a? Atmost one 'a' ie either zero number or one number
a{m} Exactly m number of a's
a{m,n} Minimum m number of a's and Maximum n number of a's
re module:
• We can develop Regular Expression Based applications by using
python module: re
• This module contains several inbuilt functions to use Regular
Expressions very easily in our applications.
Important functions of re module:

1. findall()
2. match()
3. fullmatch()
4. search()
5.finditer()
6. sub()
7.subn()
8. split()
9. compile()
1.findall():

To find all occurrences of the match.


This function returns a list object which contains all occurrences.
Eg:
import re
l=re.findall("[0-9]","a7b9c5kz")
print(l)

Output: ['7', '9', '5']


EXAMPLE 2:

import re
str = "The rain in Spain"
x = re.findall("ai", str)
print(x)

Outpu
C:\Users\My Name>python demo_regex_findall.py
['ai', 'ai']
If no matches are found, an empty list is returned:
Example:

import re
str = "The rain in Spain"
x = re.findall("Portugal", str)
print(x)

Output:
C:\Users\My Name>python demo_regex_findall2.py
[]
No match
2.match():
• We can use match function to check the given pattern at beginning of target
string.
• If the match is available then we will get Match object, otherwise we will get
None.
import re
s=input("Enter pattern to check: ")
m=re.match(s,"abcabdefg")
if m!= None:
print("Match is available at the beginning of the String")
print("Start Index:",m.start(), "and End Index:",m.end())
else:
print("Match is not available at the beginning of the String")
Output:

D:\python_classes>py test.py
Enter pattern to check: abc
Match is available at the beginning of the String
Start Index: 0 and End Index: 3

D:\python_classes>py test.py
Enter pattern to check: bde
Match is not available at the beginning of the String
3.fullmatch():
• We can use fullmatch() function to match a pattern to all of target string. i.e
complete string should be matched according to given pattern.
• If complete string matched then this function returns Match object otherwise it
returns None.
import re
s=input("Enter pattern to check: ")
m=re.fullmatch(s,"ababab")
if m!= None:
print("Full String Matched")
else:
print("Full String not Matched")
Output:
D:\python_classes>py test.py
Enter pattern to check: ab
Full String not Matched

D:\python_classes>py test.py
Enter pattern to check: ababab
Full String Matched
4.search():
We can use search() function to search the given pattern in the target string.
If the match is available then it returns the Match object which represents first
occurrence of the match. If the match is not available then it returns None
import re
s=input("Enter pattern to check: ")
m=re.search(s,"abaaabaaa")
if m!= None:
print("Match is available")
print("First Occurrence of match with start index:",m.start(),"and end
index:",m.end())
else:
print("Match is not available")
Output:

D:\python_classes>py test.py
Enter pattern to check: aaa
Match is available
First Occurrence of match with start index: 2 and end index: 5

D:\python_classes>py test.py
Enter pattern to check: bbb
Match is not available
5.finditer():
• Returns the iterator yielding a match object for each match.
• On each match object we can call start(), end() and group()
functions.

Eg:
import re
itr=re.finditer("[a-z]","a7b9c5k8z")
for m in itr:
print(m.start(),"...",m.end(),"...",m.group())
Output:

D:\python_classes>py test.py
0 ... 1 ... a
2 ... 3 ... b
4 ... 5 ... c
6 ... 7 ... k
6.sub():
• sub means substitution or replacement
• re.sub(regex,replacement,targetstring)
• In the target string every matched pattern will be replaced with
provided replacement.
Eg:
import re
s=re.sub("[a-z]","#","a7b9c5k8z")
print(s)
Output: #7#9#5#8#

Every alphabet symbol is replaced with # symbol


7.subn():
• It is exactly same as sub except it can also returns the number of
replacements.
• This function returns a tuple where first element is result string and
second element is number of replacements.
(resultstring, number of replacements)

Eg:
import re
t=re.subn("[a-z]","#","a7b9c5k8z")
print(t)
print("The Result String:",t[0])
print("The number of replacements:",t[1])
Output:

D:\python_classes>py test.py
('#7#9#5#8#', 5)
The Result String: #7#9#5#8#
The number of replacements: 5
8.split():
If we want to split the given target string according to a particular
pattern then we should go for split() function.
This function returns list of all tokens.
Eg:
import re
l=re.split("\,","sunny,bunny,chinny,vinny,pinny")
print(l)
for t in l:
print(t)
Output:
D:\python_classes>py test.py
['sunny', 'bunny', 'chinny', 'vinny', 'pinny']
sunny
bunny
chinny
vinny
pinny
EXAMPLE-2
import re
l=re.split("\.","www.w3schools.com")
for t in l:
print(t)

Output:
D:\python_classes>py test.py
www
w3schools
com
9. compile():
The compile() function returns the specified source as a code object, ready to be
executed.

Example:
x = compile('print(55)', print(test), input(“enter a”))
exec(x)
Output:55
Test
enter a
Example 2:
x = compile('print(55)', 'test', 'eval')
exec(x)

Output:
55
^ symbol:
We can use ^ symbol to check whether the given target string starts
with our provided pattern or not.

Eg:
res=re.search("^Learn",s)
if the target string starts with Learn then it will return Match
object,otherwise returns None.
Example:
import re
s="Learning Python is Very Easy"
res=re.search("^Learn",s)
if res != None:
print("Target String starts with Learn")
else:
print("Target String Not starts with Learn")

Output: Target String starts with Learn


$ symbol:
• We can use $ symbol to check whether the given target string ends
with our provided pattern or not

Eg: res=re.search("Easy$",s)

If the target string ends with Easy then it will return Match
object,otherwise returns None.
Example:
import re
s="Learning Python is Very Easy"
res=re.search("Easy$",s)
if res != None:
print("Target String ends with Easy")
else:
print("Target String Not ends with Easy")
Output: Target String ends with Easy

Note: If we want to ignore case then we have to pass 3rd argument


re.IGNORECASE for search() function.
Eg: res = re.search("easy$",s,re.IGNORECASE)
Example:
import re
s="Learning Python is Very Easy"
res=re.search("easy$",s,re.IGNORECASE)
if res != None:
print("Target String ends with Easy by ignoring case")
else:
print("Target String Not ends with Easy by ignoring case")

Output: Target String ends with Easy by ignoring case


Write a Regular Expression to represent all 10 digit mobile numbers.
Rules:
1. Every number should contains exactly 10 digits
2. The first digit should be 7 or 8 or 9

[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
Or

[7-9][0-9]{9}
or
[7-9]\d{9}
Write a Python Program to check whether the given number
is valid mobile number or not?

import re
n=input("Enter number:")
m=re.fullmatch("[7-9]\d{9}",n)
if m!= None:
print("Valid Mobile Number")
else:
print("Invalid Mobile Number")
Output:
D:\python_classes>py test.py
Enter number:9898989898
Valid Mobile Number

D:\python_classes>py test.py
Enter number:6786786787
Invalid Mobile Number

D:\python_classes>py test.py
Enter number:898989
Invalid Mobile Number
Write a Python Program to check whether the given email id is valid or not?

import re
n=input("enter email id: ")
x=re.search('\w+[.|\w]\w+@\w+[.]\w+[.|\w+]\w+',n)
if x!=None: Output:1
print("valid email",n)
enter email id: [email protected]
else: valid email [email protected]
print("not a valid email")
Output :2
enter email id:[email protected]
valid email [email protected]
Multi Threading
Multi Tasking:
Executing several tasks simultaneously is the concept of multitasking.

There are 2 types of Multi Tasking


1. Process based Multi Tasking
2. Thread based Multi Tasking

1. Process based Multi Tasking:


Executing several tasks simultaneously where each task is a separate
independent process is called process based multi tasking.
• Eg: while typing python program in the editor we can listen mp3 audio
songs from the same system. At the same time we can download a file
from the internet. All these tasks are executing simultaneously and
independent of each other.
• This type of multi tasking is best suitable at operating system level.
2. Thread based Multitasking:(Multi Threading)

Executing several tasks simultaneously where each task is a separate


independent part of the same program, is called Thread based multi
tasking, and each independent part is called a Thread.

This type of multi tasking is best suitable at programmatic level.


A word-processing application like MS Word, we can type text in one
thread and spell checker checks for mistakes in another thread.

Note: Whether it is process based or thread based, the main advantage


of multi tasking is to improve performance of the system by reducing
response time
The main important application areas of multi threading are:
1. To implement Multimedia graphics
2. To develop animations
3. To develop video games
4. To develop web and application servers

• Where ever a group of independent jobs are available, then it is highly


recommended to execute simultaneously instead of executing one by
one. For such type of cases we should go for Multi Threading.
• Python provides one inbuilt module "threading" to provide support for
developing threads. Hence developing multi threaded Programs is very easy
in python.
• Every Python Program by default contains one thread which is nothing but
Main Thread.
Program to print name of current executing thread:

import threading
print("Current Executing Thread:",threading.current_thread().getName())

Output : Current Executing Thread: MainThread


Threads and Processes:
Process:
• A process (sometimes called a heavyweight process) is a program in
execution. Each process has its own address space, memory, a data stack, and
other auxiliary data to keep track of execution.

• The operating system manages the execution of all processes on the system,
dividing the time fairly between all processes.

• Processes can also fork or spawn new processes to perform other tasks, but
each new process has its own memory, data stack, etc., and cannot generally
share information unless interprocess communication (IPC) is employed.
Thread:
• Threads (sometimes called lightweight processes) are similar to processes
except that they all execute within the same process, and thus all share the
same context.
• They can be thought of as "miniprocesses“ running in parallel within a main
process or "main thread.
• Multiple threads within a process share the same data space with the main
thread and can share information or communicate with one another more
easily than if they were separate processes.
Threading module:
• Threading is a predefined module which contains group of predefined
functions, variables and classes.
• Thread is the class which is mainly used to create thread it available in
threading module.
• The following are the methods available in Thread class:
start(),join(),isAlive(),setName(),getName(),active_count(),isDaemon(),
setDaemon(daemonic)………etc
• Thread Object Methods:
•To import the threading module, we do:
import threading
•To create a new thread, we create an object of Thread class. It takes
following arguments:

target: the function to be executed by thread


args: the arguments to be passed to the target function
Syntax: referncevariable=Thread(target=function name,args=(parmetervalues))
Here args is optional
name: name of the thread(optional).
• Creating a Thread(Without using Thread class): Child ThreadMain Thread

from threading import * Child ThreadMain Thread


def display(): Child ThreadMain Thread
for i in range(1,11): Child ThreadMain Thread
print("Child Thread")
Child ThreadMain Thread
t=Thread(target=display) #creating Thread object
Child ThreadMain Thread
t.start() #starting of Thread
Child ThreadMain Thread
for i in range(1,11):
Child ThreadMain Thread
print("Main Thread")
Child ThreadMain Thread

Child ThreadMain Thread

Note: Thread is a pre defined class present in threading module which can be
used to create our own Threads.
2. Creating a Thread by extending Thread class:
• We have to create child class for Thread class. In that child class we have to
override run() method with our required job. Whenever we call start() method
then automatically run() method will be executed and performs our job.
Example:
from threading import *
class MyThread(Thread):
def run(self):
for i in range(10):
print("Child Thread-1")
t=MyThread()
t.start()
for i in range(10):
print("Main Thread-1")
•To start a thread, we use start method of Thread class.
t1.start()
t2.start()

• In order to stop execution of current program until a thread is complete, we


use join method.

t1.join()
t2.join()

As a result, the current program will first wait for the completion of t1 and
then t2. Once, they are finished, the remaining statements of current program
are executed.
Example for join(): Child Thread
Child Thread
from threading import * Child Thread
Child Thread
def display(): Child Thread
for i in range(1,11): Child Thread
Child Thread
print("Child Thread") Child Thread
Child Thread
t=Thread(target=display) #creating Thread object Child Thread
t.start() #starting of Thread Main Thread
Main Thread
t.join() Main Thread
Main Thread
for i in range(1,11): Main Thread
print("Main Thread") Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Example: t1=Thread(target=simple)
from threading import * t1.start()
def display(): for i in range(1,11):
print("Main Thread")
for i in range(1,11): ----------------------------------------------------------------------------------
print("Child Thread ") Output:
Child Thread simple Thread Main Thread
def simple():
Child Thread simple Thread Main Thread
for i in range(1,11):
print("simple Thread ") Child Thread simple Thread Main Thread

Child Thread simple Thread Main Thread

t=Thread(target=display) Child Thread simple Thread Main Thread


t.start() Child Thread simple Thread Main Thread
-------------------------------------------------------
Setting and Getting Name of a Thread:

• Every thread in python has name. It may be default name generated by


Python or CustomizedName provided by programmer.
• We can get and set name of thread by using the following Thread class
methods.
• Every Thread has implicit variable "name" to represent name of Thread.

t.getName() Returns Name of Thread


t.setName(newName) To set our own name
Eg:
from threading import *
print(current_thread().getName())
current_thread().setName("Information Technology")
print(current_thread().getName())
print(current_thread().name)

Output:
MainThread
Information Technology
Information Technology
active_count():
• This function returns the number of active threads currently running.
from threading import *
import time
Output:
def display():
The Number of active Threads: 1
print(current_thread().getName(),"...started") ChildThread1 ...started
time.sleep(3) The Number of active Threads: 2
ChildThread1 ...ended
print(current_thread().getName(),"...ended")
print("The Number of active Threads:",active_count())
t1=Thread(target=display,name="ChildThread1")
t1.start()
print("The Number of active Threads:",active_count())
• Output:
D:\python_classes>py test.py
The Number of active Threads: 1
ChildThread1
The Number of active Threads: 2
ChildThread1
isAlive(): It checks whether a thread is still executing or not.
from threading import *
import time Output:
def display():
ChildThread1 ...started
print(current_thread().getName(),"...started") ChildThread1 is Alive : True
time.sleep(3) ChildThread1 ...ended
print(current_thread().getName(),"...ended") ChildThread1 is Alive : False
t1=Thread(target=display,name="ChildThread1")
t1.start()
print(t1.name,"is Alive :",t1.isAlive())
time.sleep(5)
print(t1.name,"is Alive :",t1.isAlive())
Daemon Threads:

• The threads which are running in the background are called Daemon
Threads.
• The main objective of Daemon Threads is to provide support for Non
Daemon Threads( like main thread)

• Eg: Garbage Collector

• Whenever Main Thread runs with low memory, immediately PVM runs
Garbage Collector to destroy useless objects and to provide free memory, so
that Main Thread can continue its execution without having any memory
problems.
• check whether thread is Daemon or not by using isDaemon() method of
Thread class by using daemon property.

from threading import *


print(current_thread().isDaemon()) #False
print(current_thread().daemon) #False

• To change Daemon nature by using setDaemon() method of Thread class.


setDaemon(True)

• Once thread started, we cannot change its Daemon nature, otherwise we


will get Runtime Exception.
Example program to set the nature of daemon thread:

from threading import *


def job():
print("Child Thread")
t=Thread(target=job)
print(t.isDaemon()) #False
t.setDaemon(True)
print(t.isDaemon()) #True

Note: By default Main Thread is always non-daemon, we cannot change its


nature.
Threading module objects
Threading module:
It is a High level threading module not only includes the thread class it also
provides variety of synchronization functions.

Synchronization:
• If multiple threads are executing simultaneously then there may be a chance
of data inconsistency problems.
from threading import * Output:
import time
Good Morning:Good Morning:Faculty
def welcome(name): Students
Good Morning:Good Morning:Faculty
for i in range(10): Students
-----------------------------
print("Good Morning:",end='') -----------------------------
-----------------------------
time.sleep(2)
print(name)
t1=Thread(target=welcome,args=("Students",))
t2=Thread(target=welcome,args=("Faculty",))
t1.start()
t2.start()
• We are getting irregular output because both threads are executing
simultaneously welcome() function.
• In synchronization the threads will be executed one by one so that we can
overcome data inconsistency problems.
• Synchronization means at a time only one Thread
• The main application areas of synchronization are
1. Online Reservation system
2. Funds Transfer from joint accounts

• In Python, we can implement synchronization by using the following:


1. Lock
2. RLock
3. Semaphore
Synchronization using Lock:

We can create Lock object by assigning any reference to Lock() method.


Syntax: l=Lock()
• The Lock object can be hold by only one thread at a time. If any other thread
required the same lock then it will wait until thread releases lock.

• A Thread can acquire the lock by using acquire() method.


l.acquire()

• A Thread can release the lock by using release() method.


l.release()
import time
l=Lock()
def wish(name):
l.acquire()
for i in range(10):
print("Good Evening:",end='')
time.sleep(2)
print(name)
l.release()
t1=Thread(target=wish,args=("Dhoni",))
t2=Thread(target=wish,args=("Yuvraj",))
t1.start()
t2.start()
from threading import *
Output:
l=Lock() D:\python_classes>py test.py
Main Thread trying to acquire Lock
print("Main Thread trying to acquire Lock") Main Thread trying to acquire Lock Again

l.acquire()
print("Main Thread trying to acquire Lock Again")
l.acquire()

• In the above Program main thread will be blocked because it is trying to


acquire the lock second time.
• To kill the blocking thread from windows command prompt we have to use
ctrl+break.
• If the Thread calls recursive functions or nested access to resources, then the
thread may trying to acquire the same lock again and again, which may
block our thread.
• Hence Traditional Locking mechanism won't work for executing recursive
functions.
• To overcome this problem, we should go for “RLock(Reentrant Lock)”.
Reentrant means the thread can acquire the same lock again and again.
• Reentrant facility is available only for owner thread but not for other
threads.

from threading import *


l=RLock()
print("Main Thread trying to acquire Lock")
l.acquire()
print("Main Thread trying to acquire Lock Again")
l.acquire()
• In this case Main Thread won't be Locked because thread can acquire the
lock any number of times.
• Difference between Lock and RLock:

Lock RLock

Lock object can be acquired by only one RLock object can be acquired by only one
thread at a time. Even owner thread also thread at a time, but owner thread can
cannot acquire multiple times. acquire same lock object multiple times.

. Not suitable to execute recursive Best suitable to execute recursive


functions and nested access calls. functions and nested access calls
In this case Lock object will takes care only In this case RLock object will takes care
Locked or unlocked and it never takes care whether Locked or unlocked and owner
about owner thread and recursion level. thread information, recursion level.
Synchronization by using Semaphore:
• In the case of Lock and RLock,at a time only one thread is allowed to
execute.
• Sometimes our requirement is at a time a particular number of threads are
allowed to access(like at a time 10 members are allowed to access database
server,4 members are allowed to access Network connection etc).
• To handle this requirement we cannot use Lock and RLock concepts and we
should go for Semaphore concept.
• Semaphore can be used to limit the access to the shared resources with
limited capacity.
• Semaphore is advanced Synchronization Mechanism
• We can create Semaphore object as follows.
s=Semaphore(counter)
• Here counter represents the maximum number of threads are
allowed to access simultaneously.
• The default value of counter is 1.
• Whenever thread executes acquire() method,then the counter value
will be decremented by 1 and if thread executes release() method
then the counter value will be incremented by 1.
• i.e for every acquire() call counter value will be decremented and for
every release() call counter value will be incremented.
Case-1: s=Semaphore()
• In this case counter value is 1 and at a time only one thread is
allowed to access. It is exactly same as Lock concept.

Case-2: s=Semaphore(3)
• In this case Semaphore object can be accessed by 3 threads at a
time.The remaining threads have to wait until releasing the
semaphore.
from threading import *
t1=Thread(target=wish,args=("Dhoni",))
import time t2=Thread(target=wish,args=("Yuvraj",))
s=Semaphore(2) t3=Thread(target=wish,args=("Kohli",))
t4=Thread(target=wish,args=("Rohit",))
def wish(name):
t5=Thread(target=wish,args=("Pandya",))
s.acquire() t1.start()
for i in range(10): t2.start()
t3.start()
print("Good Evening:",end='') t4.start()
time.sleep(2) t5.start()
print(name) In the above program at a time 2 threads are allowed to
s.release() access semaphore and hence 2 threads
are allowed to execute wish() function.
Bounded Semaphore:
• Normal Semaphore is an unlimited semaphore which allows us to
call release() method anynumber of times to increment counter.
• The number of release() calls can exceed the number of acquire()
calls also.
Eg:
from threading import *
ValueError: Semaphore released too many times
s=BoundedSemaphore(2)
It is invalid b'z the number of release() calls should
s.acquire() not exceed the number of acquire() calls in
s.acquire() BoundedSemaphore
s.release()
s.release()
Note: To prevent simple programming mistakes, it
s.release()
is recommended to use BoundedSemaphore
s.release() over normal Semaphore
print("End")
Difference between Lock and Semaphore
• At a time Lock object can be acquired by only one thread, but
Semaphore object can be acquired by fixed number of threads
specified by counter value
Python, Threads, and the Global Interpreter Lock:
• Execution of Python code is controlled by the Python Virtual Machine
(interpreter main loop).

• Python was designed in such a way that only one thread of control may be
executing in this main loop, similar to how multiple processes in a system share
a single CPU.

• Many programs may be in memory, but only one is live on the CPU at any given
moment. Likewise, although multiple threads may be "running" within the
Python interpreter, only one thread is being executed by the interpreter at any
given time.
Global Interpreter Lock:

• The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a
lock) that “allows only one thread to hold the control of the Python
interpreter”.

• This means that only one thread can be in a state of execution at any point in
time. GIL allows only one thread to execute at a time even in a multi-threaded
architecture with more than one CPU core, the GIL has gained a reputation as
an “infamous” feature of Python.

You might also like