UNIT-1 Modules
UNIT-1 Modules
• Introduction:
• Python is a general purpose high-level, interpreted, interactive and object-
oriented scripting language.
• 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
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.
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.
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.
a,b,c=5,10,15
print a
print b
print c
Keywords in Python(Reserved Words)
• 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
• 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)
(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:
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:
•print("Hello World")
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
Eg:
r[0]=100
TypeError: 'range' object does not support item assignment
Data types
<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
-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:
>>>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.
-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:
• 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
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
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.
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():
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)
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)
Output
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
Tuple vs immutability:
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.
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.
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}
Output
D:\Python_classes>py test.py
Enter List of values: [10,20,30,10,20,40]
{40, 10, 20, 30}
• Set Comprehension:
>>>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"]
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?
• 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([(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‘}
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.
• In python a type which holds a single literal object we will call atomic or
scalar storage.
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
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:
• 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:
• 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.
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'
Eg: x = eval(“10+20+30”)
print(x)
Output: 60
• But at the time of open, we have to specify mode, which represents the
purpose of opening file.
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()
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.
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
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
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.
• 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: 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:
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
os.mkdir("mysub/mysub2") C:\Users\Dell\Desktop\mysub\mysub2
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)
• 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)
Attribute notation:
module.function()
module.variable
Ex :
test.py: Output:
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):
>>>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.
Eg:
from mathop import x, add
print(x)
add(10,20)
We can import all members of a module by using *
test.py:
from mathop import *
print(x)
add(10,20)
product(10,20)
Built-in modules:
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:
• 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.
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.
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:
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
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.
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.
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
Output:
exception raised and its description is: division by zero
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
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")
• 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.
• All exception classes are child classes of BaseException i.e., every exception
class extend BaseException either directly or indirectly.
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.
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
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 :
\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:
1. findall()
2. match()
3. fullmatch()
4. search()
5.finditer()
6. sub()
7.subn()
8. split()
9. compile()
1.findall():
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#
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")
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
[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.
import threading
print("Current Executing Thread:",threading.current_thread().getName())
• 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:
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()
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
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)
• 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.
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
l.acquire()
print("Main Thread trying to acquire Lock Again")
l.acquire()
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.
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.