KEMBAR78
PYTHON | PDF | Parameter (Computer Programming) | Anonymous Function
0% found this document useful (0 votes)
26 views352 pages

PYTHON

The document provides an overview of Python's list and tuple data structures, detailing their characteristics, operations, and differences. Lists are mutable, allowing for dynamic changes, while tuples are immutable and suitable for fixed data. It also discusses how lists can contain various data types, indexing, and methods for manipulating both lists and tuples.

Uploaded by

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

PYTHON

The document provides an overview of Python's list and tuple data structures, detailing their characteristics, operations, and differences. Lists are mutable, allowing for dynamic changes, while tuples are immutable and suitable for fixed data. It also discusses how lists can contain various data types, indexing, and methods for manipulating both lists and tuples.

Uploaded by

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

CORE PYTHON

(from Collections)
List Data Structure / List collection Data Type
A List is a group of individual .
>>> l1=[10,20,30,40,50]
>>> type(l1)
<class 'list'>
>>> l1
[10, 20, 30, 40, 50]
In List, the elements will be placed within square
brackets and with comma separator.
 In List, insertion order preserved.
>>> l1
[10, 20, 30, 40, 50]
Note: elements are inserted in same order
 In list, duplicate objects are allowed
>>> l2=[10,10,20,20,20,30,30]
>>> l2
[10, 10, 20, 20, 20, 30, 30]
 In List, both homogeneous and heterogeneous
objects are allowed
>>> l3=[10,10.23,'Python',1+2j,True]
>>> l3
[10, 10.23, 'Python', (1+2j), True]
 Both +ve indexing and –ve indexing are allowed
>>> l3=[10,10.23,'Python',1+2j,True]
>>> l3[0]  It is called List Slice
10
>>> l3[1]
10.23
.
.
>>> l3[-1]
True
>>> l3[-2]
(1+2j)
.
.
List is dynamic because based on our requirement
we can increase the size and decrease the size.
>>> l3=[10,10.23,'Python',1+2j,True]
>>> l3
[10, 10.23, 'Python', (1+2j), True]
>>> l3.remove(True)  Deleting an element
>>> l3
[10, 10.23, 'Python', (1+2j)]
>>> l3.append(False)  Inserting/appending an
element
>>> l3
[10, 10.23, 'Python', (1+2j), False]
 If we want to insert an element at our desired
location then we can use ”insert()” function
>>> l3
[10, 10.23, 'Python', (1+2j), False]
>>> l3.insert(1,11)
>>> l3
[10, 11, 10.23, 'Python', (1+2j), False]
 So, Lists are Mutable. i.e. we can do whatever
changes we want.
List Indices:
List indices indicate indexes of list. To know the index
of particular element, we have to use index() function.
>>> l1=[10,20,30,40]
>>> l1
[10, 20, 30, 40]
>>> l1.index(10)
0
>>> l1.index(20)
1
>>> l1.index(40)
3
Traversing a list:
Travelling from one element to another element in a
list (or) accessing the elements from the list.
>>> l1=[10,20,30,40,50,60,70,80,90,100]
>>> l1
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> l1[0:5]
[10, 20, 30, 40, 50]
>>> l1[0:10:2]
[10, 30, 50, 70, 90]
>>> l1[5:]
[60, 70, 80, 90, 100]
List Operations are done with List Methods:
We perform the number of operations on the list by
using “List Methods”.
1) Creating a list
>>> l1=[10,20,30,40,50]
To accept the elements from the user:
>>> l1=eval(input("Enter the elements into list:"))
Enter the elements into list:[10,20,30,40,50]
>>> l1
[10, 20, 30, 40, 50]
>>> type(l1)
<class 'list'>
2) Displaying a list
>>> l1
[10, 20, 30, 40, 50]
>>> l1[0]
10
>>> l1[0:3]
[10, 20, 30]
>>> l1[::-1]
[50, 40, 30, 20, 10]
3) Inserting an element into a list at the last position
>>> l1.append(60)
>>> l1
[10, 20, 30, 40, 50, 60]
4) Inserting an element into a list at the required
position
>>> l1
[10, 20, 30, 40, 50, 60]
>>> l1.insert(2,21)
>>> l1
[10, 20, 21, 30, 40, 50, 60]
5) Insertion of multiple elements at a time at the end
of the list
>>> l1
[10, 20, 21, 30, 40, 50, 60]
>>> l1.extend([70,80,90,100])
>>> l1
[10, 20, 21, 30, 40, 50, 60, 70, 80, 90, 100]
6) Insertion of multiple elements in to the list at our
required position
>>> l1
[10, 20, 21, 30, 40, 50, 60, 70, 80, 90, 100]
>>> l1[4:4]=range(31,36) Inserting 31,32,33,34,35
Note: first 4 means position at which insertion should
be done; Next 4 means 0-4 i.e. 5 elements to be
inserted, they are 31,32,33,34,35
>>> l1
[10, 20, 21, 30, 31, 32, 33, 34, 35, 40, 50, 60, 70, 80,
90, 100]
Note: All these operations are also called as
“Updating a list”
7) Deleting an element in a list by specifying
element:
>>> l1
[10, 20, 21, 30, 31, 32, 33, 34, 35, 40, 50, 60, 70, 80,
90, 100]
>>> l1.remove(20)
>>> l1
[10, 21, 30, 31, 32, 33, 34, 35, 40, 50, 60, 70, 80, 90,
100]  20 is removed
8) Deleting last element from a list
>>> l1
[10, 21, 30, 31, 32, 33, 34, 35, 40, 50, 60, 70, 80, 90,
100]
>>> l1.pop()
100
>>> l1
[10, 21, 30, 31, 32, 33, 34, 35, 40, 50, 60, 70, 80, 90]
9) Deleting an element from a list by specifying an
index
>>> l1
[10, 21, 30, 31, 32, 33, 34, 35, 40, 50, 60, 70, 80, 90]
>>> l1.pop(1)
21
>>> l1
[10, 30, 31, 32, 33, 34, 35, 40, 50, 60, 70, 80, 90]
>>>
10) Deleting multiple elements from a list by
specifying an indexes
>>> l1
[10, 30, 31, 32, 33, 34, 35, 40, 50, 60, 70, 80, 90]
>>> del l1[1:5]  30, 31, 32, 33 elements removed
>>> l1
[10, 34, 35, 40, 50, 60, 70, 80, 90]
11) Deleting multiple elements in a list from
specified index to last
>>> l1
[10, 34, 35, 40, 50, 60, 70, 80, 90]
>>> del l1[4:]  50, 60, 70, 80, 90 element removed
>>> l1
[10, 34, 35, 40]
12) Deleting all elements from the list
>>> l1
[10, 34, 35, 40]
>>> l1
[10, 34, 35, 40]
>>> l1.clear()
>>> l1
[]
13) Deleting total list
>>> del l1
>>> l1

NameError: name 'l1' is not defined
14) Reversing the elements of a list
>>> l1=[100,5,10,300,4,500]
>>> l1
[100, 5, 10, 300, 4, 500]
>>> l1.reverse()
>>> l1
[500, 4, 300, 10, 5, 100]
15) Sorting a list
>>> l1=[50,20,30,40,10]
>>> l1
[50, 20, 30, 40, 10]
>>> l1.sort()
>>> l1
[10, 20, 30, 40, 50]
16) Sorting in a reversed order
>>> l1
[10, 20, 30, 40, 50]
>>> l1.sort(reverse=True)
>>> l1
[50, 40, 30, 20, 10]
17) Copying a list
>>> l1=['apples','mangoes','bananas']
>>> l2=l1.copy()
>>> l1
['apples', 'mangoes', 'bananas']
>>> l2
['apples', 'mangoes', 'bananas']
>>> id(l1)
46515080
>>> id(l2)
46549704
18)Concatenation of lists:
>>> list1=[10,20,30,40]
>>> list2=[50,60,70,80]
>>> list3=list1+list2
>>> list3
[10, 20, 30, 40, 50, 60, 70, 80]
19) Comparison of lists:
>>> list1=[100,200,300,400]
>>> list2=[100,200,300,400]
>>> list1==list2
True

>>> list1=[10,20,30,40]
>>> list2=[10,20,30,40,50]
>>> list1==list2
False
20) Creation of Nested lists
>>> list1=[100,200,300,400,[500,600,700]]
>>> list1
[100, 200, 300, 400, [500, 600, 700]]
>>> list1[0]
100
>>> list1[4]
[500, 600, 700]
>>> list1[4][0]
500
>>> list1[4][1]
600
>>> list1[4][2]
700
Lists and Strings
List is a collection of individual elements or individual
objects.
String is a sequence of characters.
>>> l1=[5,6,7,8]
>>> type(l1)
<class 'list'>
>>> l1
[5, 6, 7, 8]
>>> type(l1[0])
<class 'int'>
>>> l1[0]+l1[1]+l1[2]+l1[3]
26
>>> s1='5678'
>>> s1
'5678'
>>> s1[0]
'5'
>>> s1[1]
'6'
>>> type(s1[0])
<class 'str'>
>>> int(s1[0])+int(s1[1])+int(s1[2])+int(s1[3])
26
Tuple Data Structure
Tuple is exactly same as List but the difference is
“tuple” object is immutable object and “list” object is
mutable object. i.e. “tuple” object can not be changed
and “list” object can be changed
 If our data is fixed and never changes then we
should go for Tuple.
 So, “tuple” is also a collection of individual objects.
“tuple” is represented in “parenthesis” and with
comma separated values.
>>> t1=(10,20,30,40,50)
>>> type(t1)
<class 'tuple'>
>>> t1
(10, 20, 30, 40, 50)
>>> t2=60,70,80,90  we can also represent the tuple
without parenthesis.
>>> type(t2)
<class 'tuple'>
>>> t2
(60, 70, 80, 90)
Tuple object is immutable
>>> t1=(10,20,30,40,50)
>>> type(t1)
<class 'tuple'>
>>> t1
(10, 20, 30, 40, 50)
>>> t1[0]
10
>>> t1[0]=100
……………
TypeError: 'tuple' object does not support item
assignment
So, “tuple” object is immutable
Where as “list” object is mutable
>>> l1=[10,20,30,40,50]
>>> type(l1)
<class 'list'>
>>> l1
[10, 20, 30, 40, 50]
>>> l1[0]
10
>>> l1[0]=100
>>> l1
[100, 20, 30, 40, 50]

In tuple, Insertion order is preserved like in list


In tuple, Duplicates are allowed
>>> t3=(10,10,20,20,20,30,30)
>>> t3
(10, 10, 20, 20, 20, 30, 30)
In tuple, Both homogeneous and heterogeneous
elements are allowed
>>> t4=(10,20.45,'Python',True,1+2j)
>>> type(t4)
<class 'tuple'>
>>> t4
(10, 20.45, 'Python', True, (1+2j))
In tuple, both +ve indexing and –ve indexing are
allowed
>>> t4
(10, 20.45, 'Python', True, (1+2j))
>>> t4[0]
10
>>> t4[1]
20.45
>>> t4[-1]
(1+2j)
>>> t4[-2]
True
>>> t4[0:3]
(10, 20.45, 'Python')
>>> t4[::-1]
Advantages of Tuple over List:
 “Tuple” is write-protected because of immutable nature
 Dictionary is a collection of “key : value” pairs. “keys”
are unique i.e. “keys” can not have duplicates.
Ex: d1={1122: “samsung mobile”}
Here 1122 is the key and “samsung mobile” is the value.
If the “tuple” is passed as a key then it is accepted in
dictionary because “tuple” is immutable object, but if
“list” is passed as a key then it is not accepted in
dictionary because “list” is mutable object.
So, immutable objects are accepted as keys and mutable
objects are accepted as values into a “dictionary”
>>> l1=[1122]
>>> type(l1)
<class 'list'>
>>> t1=(1122)
>>> type(t1)
<class 'int'>
>>> l1
[1122]
>>> t1
1122
>>> d1={l1:'Samsung Mobile'}
….
TypeError: unhashable type: 'list'
>>> d1={t1:'Saumsung Mobile'}
>>> d1
{1122: 'Saumsung Mobile'}
>>> type(d1)
<class 'dict'>
 Generally, “tuple” is used for heterogeneous
(different) data types and “list” is used for
homogeneous (similar) data types
Using tuple as keys in dictionary and list as values in
dictionary:
MobilesDictionary.py
t1=(1122,2233,3344,4455)
l1=['Samsung Galaxy M30','Sony Mobile XZ2','Redmi
Mobile A2','Lenovo Mobile K8']
Mobiles_Dictionary={}
i=0
while i<=3:
Mobiles_Dictionary[t1[i]]=l1[i]
i=i+1
print("MOBILE ID \t","MOBILE Name")
print("******************************")
for i in Mobiles_Dictionary:
print(i,"\t\t",Mobiles_Dictionary[i])
MOBILE ID MOBILE Name
******************************
1122 Samsung Galaxy M30
2233 Sony Mobile XZ2
3344 Redmi Mobile A2
4455 Lenovo Mobile K8
Packing and Unpacking:
Packing means combining all elements into a single tuple
>>> a=10
>>> b=20
>>> c=30
>>> d=40
>>> t1=(a,b,c,d)
>>> t1
(10, 20, 30, 40)
>>> type(t1)
<class 'tuple'>
Unpacking means dividing all elements from a tuple into
multiple variables
>>> i,j,k,l=t1
>>> i
10
>>> j
20
>>> k
30
>>> l
40
Comparing Tuples:
>>> t1
(10, 20, 30, 40)
>>> t2=(10,20,30,40)
>>> t2
(10, 20, 30, 40)
>>> t1==t2
True
>>> t3=(100,200)
>>> t4=(300,400)
>>> t3<t4
True
>>> t4>t3
True
>>>
>>> t3!=t4
True
>>>
Creating Nested Tuple:
>>> t1=(10,20,(30,40))
>>> t1[0]
10
>>> t1[1]
20
>>> t1[2]
(30, 40)
>>> t1[2][0]
30
>>> t1[2][1]
40
Deleting Tuples
>>> t1=(10,20,30,40)
>>> del t1
>>> t1
….
NameError: name 't1' is not defined
Slicing of Tuples
>>> t1=(10,20,30,40,50,60,70,80,90,100)
>>> type(t1)
<class 'tuple'>
>>> t1
(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
>>> t1[0]
10
>>> t1[1]
20
>>> t1[-1]
100
>>> t1[-2]
90
>>> t1[0:10:3]
(10, 40, 70, 100)
>>> t1[::-1]
(100, 90, 80, 70, 60, 50, 40, 30, 20, 10)

Tuple Membership Test


>>> t1=(10,20,30,40,50)
>>> 10 in t1
True
>>> 60 in t1
False
>>> 60 not in t1
True
Built-in Functions with Tuple
 Converting list into tuple by using tuple() function
>>> l1=[10,20,30,40,50]
>>> t1=tuple(l1)
>>> t1
(10, 20, 30, 40, 50)
>>> type(t1)
<class 'tuple'>

 len() function: returns the number of elements present in


the tuple
>>> len(t1)
5
 count() function: returns number of occurrences of
given element in the tuple.
>>> t1=(10,10,20,20,20)
>>> t1.count(20)
3

 Index() function: returns index of first occurrence of


the given element.
>>> t2=(1000,2000,3000,40000)
>>> type(t2)
<class 'tuple'>
>>> t2.index(3000)
2
 min() and max() functions: These functions return min
and max values of tuple
>>> t2
(1000, 2000, 3000, 40000)
>>> min(t2)
1000
>>> max(t2)
40000
 eval() function
>>> t1=eval(input("Enter the elements into tuple:"))
Enter the elements into tuple:(10,20,30,40,50)
>>> t1
(10, 20, 30, 40, 50)
>>> type(t1)
<class 'tuple'>
Set Data Structure
If we want to represent a group of unique values as
a single entity then we should go for set.
We represent set elements within curly braces and
with comma separation
>>> s1={10,20,30,40,50}  Creating a Set
>>> type(s1)
<class 'set'>
>>> s1
{40, 10, 50, 20, 30}  Iteration over set
 In Set, Insertion order is not preserved (in the
above example we can observe this)
Duplicates are not allowed.
>>> s2={10,10,20,20,30,30,40,40,50,50}
>>> type(s2)
<class 'set'>
>>> s2
{40, 10, 50, 20, 30}
Indexing and slicing not allowed for the set.
>>> s2
{40, 10, 50, 20, 30}
>>> s2[0]
TypeError: 'set' object is not subscriptable
>>> s2[0:2]
TypeError: 'set' object is not subscriptable
Both Homogeneous and Heterogeneous elements
are allowed.
>>> s1={10,10.23,'Python',True,1+2j}
>>> s1
{True, (1+2j), 10, 10.23, 'Python'}
>>> type(s1)
<class 'set'>
Set objects are mutable i.e once we creates set
object we can perform any changes in that object
based on our requirement.
>>> set1={10,20,30,40}
>>> type(set1)
<class 'set'>
>>> set1
{40, 10, 20, 30}
>>> set1.add(50)
>>> set1
{40, 10, 50, 20, 30}
>>> set1.remove(50)
>>> set1
{40, 10, 20, 30}
Set Operations are done with built-in Set Methods:
set() function:
set() function is used to convert the sequence of
objects into set objects.
>>> l1=[10,20,30,40,50]
>>> type(l1)
<class 'list'>
>>> l1
[10, 20, 30, 40, 50]
>>> s1=set(l1)
>>> s1
{40, 10, 50, 20, 30}
>>> type(s1)
<class 'set'>
>>> t1=(10,20,30,40,50)
>>> type(t1)
<class 'tuple'>
>>> t1
(10, 20, 30, 40, 50)
>>> s2=set(t1)
>>> s2
{40, 10, 50, 20, 30}
>>> type(s2)
<class 'set'>
>>>
copy() function:
One set is copied into another set.
>>> s1={1000,2000,3000}
>>> type(s1)
<class 'set'>
>>> s1
{1000, 3000, 2000}
>>> s2=s1.copy()
>>> s2
{1000, 3000, 2000}
>>> type(s2)
<class 'set'>
>>> id(s1)
46408200
>>> id(s2)
46408424
clear():
To remove all elements from the Set.
>>> s1={"apple","banana","cherry"}
>>> type(s1)
<class 'set'>
>>> s1
{'cherry', 'apple', 'banana'}
>>> s1.clear()
>>> s1
set()
Union of Sets:
union() function is used to union or combine the sets.
Syntax:
x.union(y) or x|y
>>> s1={10,20,30,40}
>>> type(s1)
<class 'set'>
>>> s2={50,60,70,80}
>>> s3=s1.union(s2)
>>> s3
{70, 40, 10, 80, 50, 20, 60, 30}
>>> s4=s1|s2
>>> s4
{70, 40, 10, 80, 50, 20, 60, 30}
Intersection of sets():
intersection() function returns common elements
from the sets.
Syntax:
x.intersection(y) or x&y
>>> s1={10,20,30,40}
>>> s2={10,20,50,60}
>>> s3=s1.intersection(s2)
>>> s3
{10, 20}
>>> s4=s1&s2
>>> s4
{10, 20}
Frozenset:
Frozen set is an immutable version set object. Where
as set is mutable.
>>> fs=frozenset({1,2,3,4})
>>> type(fs)
<class 'frozenset'>
>>> list1=[10,20,30,40]
>> frozenset1=frozenset(list1)
>>> type(frozenset1)
<class 'frozenset'>
>>> frozenset1
frozenset({40, 10, 20, 30})
>>> frozenset1.add(50)
…..
AttributeError: 'frozenset' object has no attribute
'add'

Note: So, we can not add the element to frozenset,


because frozenset immutable type.
Dictionary Data Structure
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.
Format: dictionary={key:value, key:value}
>>> FruitsDictionary={'apple':'An apple a day keeps
the doctor away','banana':'It is good for
digestion','cherry':'cherry is a good source for
fibre,vitamins'}  Creation of Dictionary
>>> type(FruitsDictionary)
<class 'dict'>
>>> FruitsDictionary
{'apple': 'An apple a day keeps the doctor away',
'banana': 'It is good for digestion', 'cherry': 'cherry is a
good source for fibre,vitamins'}
>>> FruitsDictionary['apple']
'An apple a day keeps the doctor away'
>>> FruitsDictionary['banana']
'It is good for digestion'
>>> FruitsDictionary['cherry']
'cherry is a good source for fibre,vitamins'
Duplicate keys are not allowed but values can be
duplicated.
>>> FruitsDictionary={'apple':'An apple a day keeps
the doctor away','banana':'It is good for
digestion','cherry':'cherry is a good source for
fibre,vitamins','apple':'good fruit'}

>>> FruitsDictionary
{'apple': 'good fruit', 'banana': 'It is good for
digestion', 'cherry': 'cherry is a good source for
fibre,vitamins'}
Hetrogeneous objects are allowed for both key and
values.
>>> FruitsDictionary={'apple':'An apple a day keeps
the doctor away','banana':'It is good for
digestion','cherry':'cherry is a good source for
fibre,vitamins'}

>>> FruitsDictionary
{'apple': 'An apple a day keeps the doctor away',
'banana': 'It is good for digestion', 'cherry': 'cherry is a
good source for fibre,vitamins'}
>>>
FruitsDictionary1={1122:'apple',2233:'banana',3344:'c
herry'}

>>> FruitsDictionary1
{1122: 'apple', 2233: 'banana', 3344: 'cherry'}
Dictionaries are mutable
>>>
FruitsDictionary1={1122:'apple',2233:'banana',3344:'c
herry'}
>>> FruitsDictionary1
{1122: 'apple', 2233: 'banana', 3344: 'cherry'}
>>> del FruitsDictionary1[3344]
>>> FruitsDictionary1
{1122: 'apple', 2233: 'banana'}
>>> FruitsDictionary1[4455]='mango'
>>> FruitsDictionary1
{1122: 'apple', 2233: 'banana', 4455: 'mango'}
>>> FruitsDictionary1[1122]='orange'
>>> FruitsDictionary1
{1122: 'orange', 2233: 'banana', 4455: 'mango'}

Note: performing deletion, insertion, modification


operations on dictionary is called as updationg
dictionary
indexing and slicing concepts are not applicable
>>>
FruitsDictionary1={1122:'apple',2233:'banana',3344:'c
herry'}
>>> FruitsDictionary1
{1122: 'apple', 2233: 'banana', 3344: 'cherry'}
>>> FruitsDictionary1[0]
...
KeyError: 0
>>> FruitsDictionary1[0:2]
.....
TypeError: unhashable type: 'slice'
Python Hashing (or) Performing Hashing in python
by using hash():
In Python, hash() method is used to check whether
an object is “Mutable” or “immutable”

 If “hash code” is generated by hash() function then


that object is “immutable object” otherwise “mutable
object”
>>> t1=(10,20,30,40)  tuple is immutable object
>>> hash(t1)
-2011598043616273961
>>> l1=[10,20,30,40]  list is mutable object
>>> hash(l1)
TypeError: unhashable type: 'list'
So, hash() method is used check whether object is
“Mutable object” or “Immutable object”

Note: Hashingis one way to enable security during the


process of message transmission when the message is
intended for a particular recipient only.
Python Dictionary Methods:
keys(): Returns keys of dictionary
>>>
EmployeeDictionary={'eid':1001,'ename':'Raju','dept':'
IT','desg':'SE','salary':100000}
>>> EmployeeDictionary
{'eid': 1001, 'ename': 'Raju', 'dept': 'IT', 'desg': 'SE',
'salary': 100000}
>>> EmployeeDictionary.keys()
dict_keys(['eid', 'ename', 'dept', 'desg', 'salary'])
values(): Return values of dictionary
EmployeeDictionary={'eid':1001,'ename':'Raju','dept':'
IT','desg':'SE','salary':100000}
>>> EmployeeDictionary
{'eid': 1001, 'ename': 'Raju', 'dept': 'IT', 'desg': 'SE',
'salary': 100000}
>>> EmployeeDictionary.values()
dict_values([1001, 'Raju', 'IT', 'SE', 100000])
>>>
dict(): Creates an empty dictionary
>>> ProductsDictionary=dict()
>>> type(ProductsDictionary)
<class 'dict'>
(or)
>>> dictionary1={}
>>> type(dictionary1)
<class 'dict'>
>>> ProductsDictionary["pid"]=1001
>>> ProductsDictionary["name"]="Samsung Mobile"
>>> ProductsDictionary["price"]=50000
>>> ProductsDictionary
{'pid': 1001, 'name': 'Samsung Mobile', 'price': 50000}
clear(): removes all “key:value” pairs from the
dictionary.
>>> ProductsDictionary={1122:'Samsung
Mobile',2233:'Lenovo Mobile',3344:'Redmi Mobile'}
>>> ProductsDictionary
{1122: 'Samsung Mobile', 2233: 'Lenovo Mobile',
3344: 'Redmi Mobile'}
>>> ProductsDictionary.clear()
>>> ProductsDictionary
{}
>>> del ProductsDictionary
>>> ProductsDictionary

NameError: name 'ProductsDictionary' is not defined
To delete total dictionary
>>> del ProductsDictionary
>>> ProductsDictionary

NameError: name 'ProductsDictionary' is not defined
len()
Returns the number of items in the dictionary
>>>
ProductsDictionary={"PID":1001,"PNAME":"iPhone","MOD
EL":"SE2","PRICE":80000}
>>> type(ProductsDictionary)
<class 'dict'>
>>> len(ProductsDictionary)
4
pop():
It removes the entry associated with the specified
key
>>>
StudentsDictionary={"Raju":65,"Ravi":70,"Rani":80}
>>> type(StudentsDictionary)
<class 'dict'>
>>> StudentsDictionary.pop("Raju")
65
>>> StudentsDictionary
{'Ravi': 70, 'Rani': 80}
Copying Dictionary with copy():
To create exactly duplicate dictionary(cloned copy)
>>> MobilesDictionary={1001:"iPhone",1002:"Lenovo
Mobile"}
>>> MobilesDictionary
{1001: 'iPhone', 1002: 'Lenovo Mobile'}
>>> m=MobilesDictionary.copy()
>>> m
{1001: 'iPhone', 1002: 'Lenovo Mobile'}
>>> type(m)
<class 'dict'>
Updating dictionary with update():
All items present in one dictionary will be updated to
another dictionary.
>>>
MobilesDictionary1={1001:"iPhone",1002:"Samsung
Mobile"}
>>> MobilesDictionary2={1003:"Lenovo
Mobile",1004:"LG Mobile"}
>>> MobilesDictionary1.update(MobilesDictionary2)
>>> MobilesDictionary1
{1001: 'iPhone', 1002: 'Samsung Mobile', 1003:
'Lenovo Mobile', 1004: 'LG Mobile'}
Duplicates are removed when we use “update()”
function:
>>>
MobilesDictionary1={1001:"iPhone",1002:"Samsung
Mobile"}
>>> MobilesDictionary2={1002:"Samsung
Mobile",1004:"LG Mobile"}
>>> MobilesDictionary1.update(MobilesDictionary2)
>>> MobilesDictionary1
{1001: 'iPhone', 1002: 'Samsung Mobile', 1004: 'LG
Mobile'}
Delete Keys from the dictionary
>>>
FruitsDictionary1={1122:'apple',2233:'banana',3344:'c
herry'}
>>> FruitsDictionary1
{1122: 'apple', 2233: 'banana', 3344: 'cherry'}
>>> del FruitsDictionary1[3344]
>>> FruitsDictionary1
{1122: 'apple', 2233: 'banana'}
Note: When key is deleted then its related value will
be deleted. Because without key, its value should not
be existed.
Dictionary items() method:
It returns key-value pairs.
>>>
EmployeesDictionary={1001:"Raju",1002:"Ravi",1003:
"Rani",1004:"Roja"}
>>> EmployeesDictionary.items()
dict_items([(1001, 'Raju'), (1002, 'Ravi'), (1003, 'Rani'),
(1004, 'Roja')])
sorted():
This function sorts the dictionary.
>>> ProductsDictionary={1001:"Pears
Soap",1003:"Lux Soap",1002:"Mysoor Sandle soap"}
>>> ProductsDictionary
{1001: 'Pears Soap', 1003: 'Lux Soap', 1002: 'Mysoor
Sandle soap'}
>>> sorted(ProductsDictionary.items())
[(1001, 'Pears Soap'), (1002, 'Mysoor Sandle soap'),
(1003, 'Lux Soap')]
Sorting based on keys:
>>> sorted(ProductsDictionary.keys())
[1001, 1002, 1003]
(or)
>>> sorted(ProductsDictionary)
[1001, 1002, 1003]
Sorting based on values:
>>> sorted(ProductsDictionary.values())
['Lux Soap', 'Mysoor Sandle soap', 'Pears Soap']
FUNCTIONS
What is a function?
A function is a group of statements that together
perform a task.
The main advantage of functions is code Reusability.
The functions can also be called as Methods,
Procedures, and subroutines.
Python supports two types of functions
1. Built in Functions
2. User Defined Functions

1. Built in Functions:
The functions which are coming along with Python software
automatically, are called built in functions or pre defined
functions or System defined functions.
Eg: id(), type(), input(), eval(), etc..
2. User Defined Functions:
The functions which are developed by programmer
explicitly according to business requirements ,are
called user defined functions.
Example: Writing simple function
>>> def display():  Defining a function
print("Welcome to FUNCTIONS")
>>> display()  calling a function
Welcome to FUNCTIONS

Either System-defined function or user-defined


function are again divided into four categories:
1) Function with parameter(s) and with return value(s)
2) Function with parameter(s) and without return value(s)
3) Function without parameter(s) and with return value(s)
4) Function without parameter(s) and without return
value(s)
Note: Parameters are inputs to the function.
1) Function with parameter(s) and with return value(s)
addition.py
def addition(a,b):  Defining the function
c=a+b
return c
Execution: Run Menu  Run Module
>>> addition(10,20)  calling the function
30
Note: a,b are formal parameters. 10, 20 are actual
parameters.
Parameters are also called as arguments
We can also directly type at Python prompt as
follows:
>>> def addition(a,b):  defining the function
c=a+b
return c
>>> addition(10,20)  calling the function
30
Note: a,b are formal parameters. 10, 20 are actual
parameters.
Parameters are also called as arguments
2) Function with parameter(s) and without return
value(s)
addition.py
def addition(a,b):
print("Addition of two integers=",a+b)
Execute: Run Menu  Run Module
>>> addition(10,20)
Addition of two integers=30
3) Function without parameter(s) and with return
value(s)
addition.py
def addition():
a=int(input("Enter first integer:"))
b=int(input("Enter second integer:"))
c=a+b
return c
Execution: Run Menu  Run Module
>>> addition()
Enter first integer:100
Enter second integer:200
300
4) Function without parameter(s) and without return
value(s)
def addition():
a=int(input("Enter first integer:"))
b=int(input("Enter second integer:"))
print("Addition=",a+b)
Execution: Run Menu  Run Module
>>> addition()
Enter first integer:100
Enter second integer:200
Addition= 300
Returning multiple values from a function:
Operations.py
def ao(a,b):
c=a+b
d=a-b
e=a*b
f=a/b
g=a//b
h=a%b
i=a**b
return c,d,e,f,g,h,i
Execution: Run Menu  Run Module
>>> ao(10,2)
(12, 8, 20, 5.0, 5, 0, 100)
Another style of above program:
Operations.py
def ao(a,b):
c=a+b
d=a-b
e=a*b
f=a/b
g=a//b
h=a%b
i=a**b
return
('addition',c,'Subtraction',d,'Multiplication',e,'Division'
,f,'Floor Division',g,'Modulation',h,'power',i)
Execution: Run Menu  Run Module
>>> ao(10,2)
('addition', 12, 'Subtraction', 8, 'Multiplication', 20,
'Division', 5.0, 'Floor Division', 5, 'Modulation', 0,
'power', 100)
Types of arguments / Types of parameters:
1) Formal arguments
2) Actual arguments
3) positional arguments
4) keyword arguments
5) default arguments
6) Variable length arguments
Note: 3,4,5,6 can also be called as sub types of actual
parameters.
Note: In the above topics, we have already seen
Formal arguments and Actual arguments
3) Positional Arguments
These are the arguments passed to function in correct
positional order.
Eg:
>>> def subtraction(a,b):
print(a-b)
>>> subtraction(20,10)
10
>>> subtraction(10,20)
-10
Note: The number of arguments and position of
arguments must be matched. If we change the
order then result may be changed and If we change
the number of arguments then we will get error.
4) keyword arguments
We can pass argument values by keyword i.e. by
parameter name.
>>> def person_name(firstname,lastname):
print("How are you ",firstname,lastname)
>>> person_name(firstname="Ravi",lastname="kumar")
How are you Ravi kumar
Note: firstname and lastname parameters are treated as
keyword arguments
>>> person_name(lastname="kumar",firstname="Ravi")
How are you Ravi kumar
>>> person_name("Ravi","kumar")
How are you Ravi kumar
>>> person_name("kumar","Ravi")
How are you kumar Ravi
Note: Here the order of arguments is not important
but number of arguments must be matched. Except
these keyword arguments , remaining all arguments
are also called as non key word arguments
5) default arguments
we can provide default values to arguments.
>>> def welcome(person_name="Guest"):
print("welcome ",person_name)
>>> welcome("Ravi")
welcome Ravi
>>> welcome()
welcome Guest
Note: If we are not passing any name then only
default value will be considered.
Another example of default arguments:
>>> def addition(a=1,b=2,c=3):
print(a+b+c)
>>> addition()
6
>>> addition(10)
15
>>> addition(10,20)
33
>>> addition(10,20,30)
60
Another example of default arguments:
>>> def addition(a,b=2,c=3):
print(a+b+c)
>>> addition()

TypeError: addition() missing 1 required positional
argument: 'a'
>>> addition(1)
6
>>> addition(1,2)
6
>>> addition(10,20,30)
60
Note: variable “a” is non default parameter
6) Variable length arguments
Sometimes we can pass any number of arguments to
function, such type of arguments are called variable
length arguments.

We can declare a variable length argument with *


symbol as follows:
def function1(*n):

We can call this function by passing any number of


arguments including zero number. Internally all these
values represented in the form of tuple.
Note: Variable length arguments are also called as
arbitrary arguments.
>>> def sum(*n):
total=0
for i in n:
total=total+i
print("Sum=",total)
>>> sum()
Sum= 0
>>> sum(1)
Sum= 1
>>> sum(1,2)
Sum= 3
>>> sum(1,2,3)
Sum= 6
>>> sum(1,2,3,4)
Sum= 10
Another example on “Variable length arguments”:
>>> def ls(*n): # finding largest and smallest number
large=small=n[0]
j=0
for i in n:
if large<n[j]:
large=n[j]
if small>n[j]:
small=n[j]
j=j+1
print(large,small)
Output:
>>> ls(100,1000,500,600)
1000 100
Handling return values:
ReturnValue.py
def addition():
a=float(input("Enter first float number:"))
b=float(input("Enter second float number:"))
return a+b
def multiplication():
f1=addition()
f2=float(input("Enter a float number:"))
f3=f1*f2
print("Result=",f3)
Execution: Run Menu  Run Module
>>> multiplication()
Enter first float number:1.1
Enter second float number:2.2
Enter a float number:3.3
Result= 10.89
Types of variables:
Python supports two types of variables.
1. Global Variables
2. Local Variables

1. Global Variables
The variables which are declared outside of function
or class are called global variables.
These variables can be accessed in all functions of
that module. So, Scope of the Global variables is they
can be accessed throughout the module.
Example of global variable:
gv.py
i=10  Global Variable
def m1():
print(i)
def m2():
print(i)
Execution: Run Menu  Run Module
>>> m1()
10
>>> m2()
10
Another Example on global variable:
Note: For accessing global variable “global” keyword
is not required in methods but to perform any
operations on global variables within the functions
then “global” keyword is required.
gv.py
g=100 #global variable
def function1():
global g
g=g+200
print("In function1(),g=",g)
Save the program and select “Run Module” option
from “Run” Menu
Output:
>>> function1()
In function1(),g= 300
2. Local Variables:
The variables which are declared inside a function
are called local variables.
Local variables are available only for the function in
which we declared i.e. from outside of function we
cannot access.
 So, Scope of local variables is they can be accessed
within the function only where they are declared.
lv.py
def m1():
i=10  Local Variable
print(i)
def m2():
print(i)
Execution: Run Menu  Run Module
>>> m1()
10
>>> m2()

NameError: name 'i' is not defined
Passing collections to a function
Function1.py
def display(list1):
for i in list1:
print(i)
Execute: Run Menu  Run Module
>>> list1=[10,20,30,40,50]
>>> display(list1)
10
20
30
40
50
Lambda Functions / Lambda Expressions:
By using Lambda Functions we can write very
concise code (very short code) so that readability of
the program will be improved.
We can define lambda functions by using lambda
keyword
Syntax of lambda Function:
lambda argument_list : expression
Write a program to create a lambda function to find
square of given number?
>>> square=lambda n:n*n
>>> print("Square of 4 is:",square(4))
Square of 4 is: 16

Lambda function to find sum of 2 given numbers:


>>> sum=lambda a,b:a+b
>>> print("sum of 10,20:",sum(10,20))
sum of 10,20: 30
Lambda Function internally returns expression value
and we are not required to write return statement
explicitly.
Sometimes we can pass function as argument to
another function. In such cases lambda functions are
best choice.
We can use lambda functions very commonly with
filter(),map() and reduce() functions, because these
functions expect function as argument.
filter() function:
We can use filter() function to filter values from the
given sequence based on some condition.
Syntax: filter(function,sequence)
where function argument is responsible to perform
conditional check and sequence can be list or tuple or
string.
filter() function with lambda function:
>>> list1=[10,20,30,40,50,60,70,80,90,100]
>>> even=list(filter(lambda x:x%2==0,list1))
>>> even
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1=[0,1,2,3,4,5,6,7,8]
>>> even=list(filter(lambda x:x%2==0,list1))
>>> even
[0, 2, 4, 6, 8]

>>> odd=list(filter(lambda x:x%2!=0,list1))


>>> odd
[1, 3, 5, 7]
map() function:
For every element present in the given sequence,
apply same functionality and generate new element.
For this requirement we should go for map() function.
Ex: Write a program to find square of given numbers
>>> list1=[100,200,300,400,500]
>>> list2=list(map(lambda x:x*x,list1))
>>> list2
[10000, 40000, 90000, 160000, 250000]

We can apply map() function on multiple lists


also.But make sure all list should have same
length.
Syntax: map(lambda x,y:x*y,list1,list2))
x is from list1 and y is from list2

>>> list1=[10,20,30,40,50]
>>> list2=[60,70,80,90,100]
>>> list3=list(map(lambda x,y:x*y,list1,list2))
>>> list3
[600, 1400, 2400, 3600, 5000]
reduce() function:
reduce() function reduces sequence of elements into
a single element by applying the specified function.
Syntax: reduce(function, sequence)
reduce() function present in functools module and
hence we should write import statement.
>>> from functools import *
>>> list1=[10,20,30,40,50]
>>> result=reduce(lambda x,y:x+y,list1)
>>> result
150
MODULES
What is a Module?
Ans: A Module is a collection of variables, functions,
and classes. Every Python file (.py) acts as a module.
Types of Modules:
1) System-defined Modules:
Examples of System-defined Modules: math,
datetime, string….
2) User-defined Modules
To see the list of system-defined modules :
>>> help("modules")
Output:
Please wait a moment while I gather a list of all
available modules...
Note: All system modules will be displayed
Creating an User-defined Module:
aomodule.py
def addition(a,b):
print("sum=",a+b)
def subtraction(a,b):
print("Subtraction",a-b)
def multiplication(a,b):
print("Multiplication",a*b)
def division(a,b):
print("Division=",a/b)
Save the file and open new file
textmodule.py
import aomodule (or) from aomodule import *
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
aomodule.addition(i,j)
aomodule.subtraction(i,j)
aomodule.multiplication(i,j)
aomodule.division(i,j)
Execution: Run Menu  Run Module
Enter first integer:20
Enter second integer:10
sum= 30
Subtraction 10
Multiplication 200
Division= 2.0
from ... import:
We can import particular members or functions of
module by using from ... import .
The main advantage of this is we can access members
directly without using module name.
Ex: If we want to import addition() function from
above aomodule
textmodule.py
from aomodule import addition
print(addition(10,20))
Execution: Run Menu  Run Module
30
Module aliases (or) Renaming a Module:
Programmer can rename a module at the time of writing
import statement.
Syntax: import module-name as alias-name
Ex: import aomodule as m1
Here, aomodule is original module name and m1 is alias
name.
textmodule.py
import aomodule as m1
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
m1.addition(i,j)
m1.subtraction(i,j)
m1.multiplication(i,j)
m1.division(i,j)
To get help on a module:
test.py
import aomodule
help(aomodule)
Execution: Run menu  Run Module
Note: aomodule should be existed before executing
this program
Help on module aomodule:
NAME
aomodule
FUNCTIONS
addition(a, b)
division(a, b)
multiplication(a, b)
subtraction(a, b)
To get help on system-defined modules:
>>> import math
>>> help(math)

Right click on this button and select view option.


Then we see list of functions of math module.
All system-defined modules are in small letters.
All system-defined modules are existed in “lib”
folder python software folder (i.e. Python37 in C-
drive)
Reloading a Module:
By default module will be loaded only once with
import statement. If we want to reload the module
whenever we want then we have to use “reload()”
function. So that we will get the latest updates of the
module.
 reload() function comes from importlib module and
it is system-defined module.
Without reload() function:
module1.py
print("Welcome to Module1")
Save it and open another file write the following
python program:
testmodule1.py
import module1
import module1
import module1
Execution: Run Menu  Run Module
Welcome to Module1
Note: Even though we imported module1 for three
times but it is imported for only one time
With reload() function:
module1.py
print("Welcome to Module1")
Save it and open another file write the following
python program:
testmodule1.py
from importlib import reload
import module1
reload(module1)
reload(module1)
Execution: Run Menu  Run Module
Welcome to Module1
Welcome to Module1
Welcome to Module1
We used reload() function two times, So module1 is
reloaded for two times
dir() function
Python provides inbuilt function dir() to list out all
members of module.
aomodule.py
def addition(a,b):
return a+b
def subtraction(a,b):
return a-b
def multiplication(a,b):
return a*b
def division(a,b):
return a/b
Save the file and open another file and write the
following code:
dir1.py
import aomodule
print(dir(aomodule))
Execution: Run Menu  Run Module
['__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__',
'addition', 'division', 'multiplication', 'subtraction']
Command Line arguments
Python program can also take input from the user at
command prompt.
commandlinearguments.py
from sys import argv
print("The List of Command Line Arguments:", argv)
sum=0
args=argv[1:]
for x in args:
sum=sum+int(x)
print("Sum=",sum)
Save the program and open windows command
prompt as follows:
Start Menu  type cmd  command prompt will be
opened and type as follows:
Another example for command line arguments:
commandlinearguments.p
from sys import argv
print("The list of command-line arguments=",argv)
args=argv[1:]
strings=''
for x in args:
strings=strings+' '+x
print("strings=",strings)
Save the program and open windows command
prompt as follows:
Start Menu  type cmd  command prompt will be
opened and type as follows:
Working with pre-defined modules:
Working with “math” module:
>>> import math
>>> math.factorial(4)
24
>>> math.log(10)
2.302585092994046
>>> math.sin(10)
-0.5440211108893698
>>> math.cos(10)
-0.8390715290764524
>>> math.tan(10)
0.6483608274590866
Packages
A package is a collection of modules. A module is a
collection of classes, methods, and variables. Every
python file is a module. (Every python file is saved
with .py extension)
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 contains sub packages also.
Defining Packages:
Steps to Create a Python Package
Working with Python packages is really simple. All you
need to do is:
1. Create a directory and give it your package's name.
2. Put your modules in it.
3. Create a __init__.py file in the directory
Let us create the following package:
1) Create “package1” Directory
Open Windows Explorer and go to C:\Python37\
CCReddy and create package1 directory.
2) Put “ao_module” and “string_module” in
package1 directory
 Open Python IDLE window  File Menu  New File
 and type the following code:
ao_module.py
def addition(a,b):
return a+b
def subtraction(a,b):
return a-b
def multiplication(a,b):
return a*b
def division(a,b):
return a/b
def modulation(a,b):
return a%b
Save the file under C:\Python37\CCReddy\package1
directory
Open another file and type the following code:
string_module.py
def string_length(string1):
return len(string1)
def string_reverse(string):
return string[::-1]
Save this file under C:\Python37\CCReddy\package1
directory
3) Create an empty __init__.py file C:\Python37\
CCReddy\package1 directory

Next step is create test.py file under C:\Pythpn37\


CCReddy directory and write the following code:
Note: This step is also called as “importing from
packages”
import package1.ao_module as a
import package1.string_module as s
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("addition=",a.addition(i,j))
print("subtraction=",a.subtraction(i,j))
print("multiplication=",a.multiplication(i,j))
print("division=",a.division(i,j))
print("modulation=",a.modulation(i,j))
print("*"*40)
string=input("Enter a string:")
print("String length=",s.string_length(string))
string1=input("Enter a string:")
print("Reversed string=",s.string_reverse(string1))
Execution: Run Menu  Run Module
Enter first integer:20
Enter second integer:10
addition= 30
subtraction= 10
multiplication= 200
division= 2.0
modulation= 0
****************************************
Enter a string:Python
String length= 6
Enter a string:Python
Reversed string= nohtyP
Defining Sub Packages

After defining the sub packages, we can import he


required modules and their functions from the sub
packages.
Differences between python 2.x and python 3.x
versions:
Refer the word document namely:
Important differences between Python 2.x and
3.x.doc

***********Core Python is completed***********


ADVANCED PYTHON
(from Exception Handling)
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:
print "Hello"
SyntaxError: Missing parentheses in call to 'print'
Note:
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: print(10/0) ==>ZeroDivisionError: division by zero
Eg:
>>> print(10/"ten")
TypeError: unsupported operand type(s) for /: 'int'
and 'str'

Eg: Test.py
num=int(input("Enter any integer:"))
print(num)
Execution: Run Menu  Run Module
Enter any integer:ten
ValueError: invalid literal for int() with base 10: 'ten'
Note: Integer should be entered but word “ten” is
entered. Because of this exception is happened.
Note: Exception Handling concept applicable for
Runtime Errors but not for syntax errors

What is Exception:
An unwanted and unexpected event that disturbs
normal flow of program is called exception.

The following example shows that if an exception is


raised then remaining flow of program will be
disturbed:
Test.py
a=int(input("Enter first integer:"))
b=int(input("Enter second integer:"))
print("addition=",a+b)
print("Subtraction=",a-b)
print("Multiplication=",a*b)
print("Division=",a/b)
print("Floor Division=",a//b)
print("Modulation=",a%b)
print("Power=",a**b)
print("Power through pow() function=",pow(a,b))
Execution: Run Menu  Run Module
Enter first integer:20
Enter second integer:ten
ValueError: invalid literal for int() with base 10: 'ten'
Note: Because of entering word “ten”, exception is
occurred and remaining flow of program is disturbed.
So, if end user enters proper integer values then only
program will be executed. Now, enter proper integer
values:
Execution: Run menu  Run Module
Enter first integer:20
Enter second integer:10
addition= 30
Subtraction= 10
Multiplication= 200
Division= 2.0
Floor Division= 2
Modulation= 0
Power= 10240000000000
Power through pow() function= 10240000000000
The above hierarchy is also called as predefined
exception hierarchy and it contains predefined exceptions
Every Exception in Python is a class.
All exception classes are child classes of BaseException
i.e every exception class extends
BaseException either directly or indirectly. Hence
BaseException acts as root for Python Exception
Hierarchy.
Customized Exception Handling by using try-except:
It is highly recommended to handle exceptions.
The code which may raise exception is called risky code
and we have to take risky code
inside try block. The corresponding handling code we
have to take inside except block.
Syntax of try-except:
try:
Risky Code
except XXX:
Handling code/Alternative Code
Note: XXX indicates Exception Class Name
Program without “try-except” blocks:
Test.py
a=int(input("Enter first integer:"))
b=int(input("Enter Second integer:"))
print("Division=",a/b)
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Addition=",i+j)
Exectuion: Run Menu  Run Module
Output:
Enter first integer:10
Enter Second integer:0
ZeroDivisionError: division by zero
Program with “try-except” blocks:
Test.py
a=int(input("Enter first integer:"))
b=int(input("Enter Second integer:"))
try:
print("Division=",a/b)
except ZeroDivisionError:
print("can’t divide with zero")
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Addition=",i+j)
Execution: Run Menu  Run Module
Output:
Enter first integer:10
Enter Second integer:0
Can’t divide with zero
Enter first integer:20
Enter second integer:30
Addition= 50
Execute again:
Enter first integer:10
Enter Second integer:2
Division= 5.0
Enter first integer:20
Enter second integer:30
Addition= 50
Printing exception information (or) Printing System-
defined exception information:
Test.py
a=int(input("Enter first integer:"))
b=int(input("Enter Second integer:"))
try:
print("Division=",a/b)
except ZeroDivisionError as exceptioninformation:
print("exception information
is:",exceptioninformation)
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Addition=",i+j)
Execution: Run Menu  Run Module
Enter first integer:10
Enter Second integer:0
exception information is: division by zero
Enter first integer:20
Enter second integer:30
Addition= 50
try with multiple except blocks:
If try with multiple except blocks available then based
on raised exception, the corresponding except block
will be executed.
Test.py
try:
a=int(input("Enter first integer:"))
b=int(input("Enter Second integer:"))
print("Division=",a/b)
except ZeroDivisionError:
print("can’t divide with zero")
except ValueError:
print("Please enter integer value only")
print("ADDITION OPERATION:")
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Addition=",i+j)
Execution: Run Menu  Run Module
Output:
Enter first integer:10
Enter Second integer:0
can’t divide with zero
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:10
Enter Second integer:two
Please enter integer value only
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:ten
Please enter integer value only
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:10
Enter Second integer:2
Division= 5.0
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Single except block can handle multiple exceptions:
We can write a single except block that can handle
multiple types of exceptions.
Test.py
try:
a=int(input("Enter first integer:"))
b=int(input("Enter Second integer:"))
print("Division=",a/b)
except (ZeroDivisionError,ValueError) as
ExceptionInformation:
print("Exception Information:",ExceptionInformation)
print("ADDITION OPERATION:")
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Addition=",i+j)
Execution: Run Menu  Run Module
Enter first integer:10
Enter Second integer:0
Exception Information: division by zero
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:10
Enter Second integer:two
Exception Information: invalid literal for int() with
base 10: 'two'
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:ten
Exception Information: invalid literal for int() with
base 10: 'ten'
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:10
Enter Second integer:2
Division= 5.0
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Default except block:
We can use default except block to handle any type
of exceptions.
In default except block generally we print error
message which is suitable to all types of exceptions
Test.py
try:
a=int(input("Enter first integer:"))
b=int(input("Enter Second integer:"))
print("Division=",a/b)
except:
print("Enter valid input")
print("ADDITION OPERATION:")
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Addition=",i+j)
Execution: Run Menu  Run Module
Enter first integer:10
Enter Second integer:0
Enter valid input
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:10
Enter Second integer:two
Enter valid input
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:ten
Enter valid input
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
Execute again:
Enter first integer:10
Enter Second integer:2
Division= 5.0
ADDITION OPERATION:
Enter first integer:1
Enter second integer:2
Addition= 3
finally block:
The main purpose of finally block is to maintain clean
up code (Resource De-allocation Code or Resource
Releasing code).
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
The specialty 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 an exception is not raised
Test.py
try:
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Addition=",i+j)
except:
print("Enter valid input")
finally:
print("finally block is executed")
i=j=None #Resources are deallocated
print("i=",i," j=",j)
Execution: Run Menu  Run Module
Enter first integer:10
Enter second integer:20
Addition= 30
finally block is executed
i= None j= None
Note: Exception is not raised but “finally” block is
executed and the memory for “i“ and “j” variables are
de-allocated. Hence “finally” block is executed always.
Case-2: If an exception is raised and handled:
Test.py
try:
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Addition=",i+j)
except:
print("Enter valid input")
finally:
print("finally block is executed")
i=j=None #Resources are deallocated
print("i=",i," j=",j)
Execution: Run Menu  Run Module
Enter first integer:10
Enter second integer:$
Enter valid input
finally block is executed
i= None j= None
Note: $ symbol is entered instead of entering integer.
So exception is raised and still “finally” block is
executed and the memory for “i“ and “j” variables are
de-allocated. Hence “finally” block is executed always.
Case-3: If an exception is raised but not handled:
In the following program “ValueError” exception is
only handled but “ZeroDivisionError” i.e. Division by
zero exception is not handled.
Test.py
try:
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Division=",i/j)
except ValueError:
print("Enter integer only")
finally:
print("finally block is executed")
i=j=None #Resources are deallocated
print("i=",i," j=",j)
Execution: Run Menu  Run Module
Enter first integer:10
Enter second integer:0
finally block is executed
i= None j= None
….
ZeroDivisionError: division by zero
Note: Eventhough “ZeroDivisionError” exception i.e.
division by zero exception not handled still “finally”
block is executed and the memory for “i“ and “j”
variables are de-allocated. Hence “finally” block is
executed always.
Note: There is only one situation where finally block
won't be executed ie whenever we are using
os._exit(0) function.
The following program is the proof:
Test.py
import os
try:
i=int(input("Enter first integer:"))
j=int(input("Enter second integer:"))
print("Division=",i/j)
os._exit(0)
except:
print("Enter valid input")
finally:
print("finally block is executed")
i=j=None #Resources are deallocated
print("i=",i," j=",j)
Execution: Run Menu  Run Module
Enter first integer:10
Enter second integer:2
Division= 5.0
Execute again: Now give input which causes to raise
the exception then “finally” block will be executed.
Enter first integer:10
Enter second integer:0
Enter valid input
finally block is executed
i= None j= None
Note: 0 is entered as second integer. So it causes to raise
“Division by zero” exception. So, os_exit(0) is skipped then
exception is handled and finally block is executed.
Nested try-except-finally blocks:
Programmer can place “try-except-finally blocks” in
another “try” block. Syntax is:
try:  Outer try block
---------
---------
try:  Inner try block
-----------
-----------
except:
----------
----------
finally:
---------
---------

except:
------------
------------
finally:
------------
------------
Test.py
try:
print("outer try block")
try:
print("Inner try block")
print(10/0)
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
Execution: Run Menu  Run Module
outer try block
Inner try block
Inner except block
Inner finally block
outer finally block

Note: To see outer except block also then change the


code as follows:
Test.py
try:
print("outer try block")
try:
print("Inner try block")
print(10/0)
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
a=int(input("Enter integer:"))
except:
print("outer except block: Enter valid input")
finally:
print("outer finally block")
Execute: Run Menu  Run Module
outer try block
Inner try block
Inner except block
Inner finally block
Enter integer:@
outer except block: Enter valid input
outer finally block
Types of Exceptions:
1. Predefined Exceptions
2. User Defined Exceptions

1. 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: Whenever we are trying to perform Division by
zero, automatically Python will raise ZeroDivisionError
exception.
print(10/0)
2. User Defined Exceptions:
Also known as Customized Exceptions or
Programmatic Exceptions.
Some time we have to define and raise exceptions
explicitly 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.
 Examples of User Defined Exceptions:
InSufficientFundsException, InvalidInputException,
etc.
Define and Raise Customized Exceptions:
Every exception in Python is a class that extends
Exception class either directly or indirectly.
Syntax:
class classname(predefined exception class name):
def __init__(self,arg):
self.msg=arg
Eg: write an Exception class namely
“InsufficientFundsException” and it should be raised
whenever the amount is withdrawn more than
available account balance amount. If the withdraw
amount is less than available account balance amount
then deduct than withdraw amount from account
balance and display the remaining balance.
InsufficientFunds.py
class InsufficientFundsException(Exception):
def __init__(self,argument):
self.ExceptionMessage=argument

account_balance=100000
withdraw_amount=int(input("Enter the amount to
withdraw:"))
if withdraw_amount>account_balance:
raise InsufficientFundsException("Withdraw amount is
more than available balance")
else:
account_balance=account_balance-withdraw_amount
print("Available acoount balance=",account_balance)
Execute: Run Menu  Run Module
Enter the amount to withdraw:110000
….
InsufficientFundsException: Withdraw amount is
more than available balance

Execute again:
Enter the amount to withdraw:100000
Available acoount balance= 0
assertions (or) assert statements
The process of identifying and fixing the bug is called
debugging.
The main purpose of assertions is to perform
debugging.
 Assertions concept can be used to alert
programmer to resolve development time errors.
AssertExample.py
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
Execution: Run Menu  Run Module
>>> marks=[]
>>> avg(marks)
…….
assert len(marks) != 0
AssertionError  Assertion Error is raised because marks
is empty
Execute again:
>>> marks=[60,70,80,90,100]
>>> avg(marks)
80.0
File Handling
Storage Areas
As the Part of our Applications, we required to store
our Data like Customers Information, Billing
Information, Calls Information etc..
To store this Data, we required Storage Areas. There
are 2 types of Storage Areas.
1) Temporary Storage Areas
2) Permanent Storage Areas
1.Temporary Storage Areas:
These are the Memory Areas where Data will be
stored temporarily.
Eg: Python objects like List, Tuple, Dictionary.
Once Python program completes its execution then
these objects will be destroyed automatically
and data will be lost.
2. Permanent Storage Areas:
Also known as Persistent Storage Areas. Here we can
store Data permanently.
Eg: File Systems, Databases, Data warehouses, Big
Data Technologies etc
File Systems:
File Systems can be provided by Local operating
System. File Systems are best suitable to store
very less Amount of Information.
Limitations:
1) We cannot store huge Amount of Information.
2) There is no Query Language support and hence
operations will become very complex.
3) There is no Security for Data.
3) There is no Security for Data.
4) There is no Mechanism to prevent duplicate Data.
Hence there may be a chance of Data
Inconsistency Problems.
To overcome the above Problems of File Systems, we
should go for Databases.
We will discuss about Databases in Database Access
chapter (or database programming) .
Now, we will discuss about Files.
What is a file?
A file stores data permanently.
Types of Files:
There are two 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...
Operations on files:
Opening a file
Writing data to a file
Reading data from a file
Closing a file
Writing Data to a file:
FileHandling.py
f=open("PythonFile.txt",'w') ”Write” mode replaces
the content of the file, i.e. old data is replaced with
new data
f.write("Python Progrmming language is used to
develop all types of applications\n")
f.write("With Python programming language,
Application Development is fast\n")
print("Data written to the file successfully")
f.close()  Closing a file
Execution: Run Menu  Run Module
Data written to the file successfully
Note: PythonFile.txt is stored in present working directory i.e.
CCReddy directory.
File Modes:
r Read operation
w Write operation
a append operation (new data is appended or
added to old data)
r+ read and write
w+ write and read
a+ append and read
rb read data from binary file
wb write data to binary file
ab append data to binary file
r+b read and write on binary file
w+b write and read on binary file
a+b appen and read on binary file
Reading the data from a file:
FileReading.py
f=open("PythonFile.txt",'r')  Opening a file for
reading data from a file
data=f.read()
print(data)
Execution: Run Menu  Run Module
Python Programming language is used to develop all
types of applications
With Python programming language, Application
Development is fast
Example-2: Writing Data to a File with append mode
appending.py
f=open("PythonFile.txt",'a')
data=input("Enter the text:")
f.write(data)
print("Data written to the file successfully")
f.close()
Execution: Run Menu  Run Module
Enter the text:added line of text
Data written to the file successfully
For reading the data:
>>> f=open("PythonFile.txt",'r')
>>> data=f.read()
>>> data
Output:
Python Programming language is used to develop all
types of applications
With Python programming language, Application
Development is fast
added line of text
Working with the methods of file object
The following methods we have used with file object.
open()
write()
read()
close()
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 etc...

To perform these operations, Python provides inbuilt


module os, which contains several functions to
perform directory related operations.
To Know Current Working Directory:
>>> import os
>>> cwd=os.getcwd()
>>> cwd
'C:\\Python37'

To create a sub directory in the current working


directory:
>>> import os
>>> os.mkdir("SubDirectory1")
Note: SubDirctory1 is created in C:\Python37
directory
To see whether “SubDirectory1” is created or not:
>>> os.listdir()
['CCReddy', 'DLLs', 'Doc', 'include', 'Lib', 'libs',
'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll',
'python37.dll', 'pythonw.exe', 'Scripts',
'SubDirectory1', 'tcl', 'Tools', 'vcruntime140.dll‘,]
To create SubDirectory2 under C:\Python37\
CCReddy:
>>> import os
>>> os.mkdir("C:\Python37\CCReddy\SubDirectory2")
Note: Check in C:\Python37\CCReddy directory by
opening windows explorer, Here SubDirectory2 exist.
To create a file in Subdirectory i.e. in C:\Python37\
CCReddy\SubDirectory2
Note: SubDirectory2 should be existed in CCReddy
directory, otherwise run time error comes.
FileHandling.py
f=open("C:\Python37\CCReddy\SubDirectory2\
PythonFile.txt",'w')
f.write("Python Progrmming language is used to
develop all types of applications\n")
f.write("With Python programming language,
Application Development is fast\n")
print("Data written to the file successfully")
f.close()
Execution: Run Menu  Run Module
>>> Data Written to file successfully
Now, open Windows Explorer and see in C:\
Python37\CCReddy\SubDirectory2 , Here
PythonFile.txt file is found.
Handling Binary Data:
It is very common requirement to read or write binary
data like images, video files, audio files etc.
Note: Place picture.png file (paint file) in present
directory i.e. c:\python37\ccreddy
Filehandling.py
f1=open("picture.png","rb")
f2=open("newpic.png","wb")
bytes=f1.read()
f2.write(bytes)
f1.close()
f2.close()
Execution: Run Menu  Run Module and see in
present directory i.e. ccreddy, here newpic.png exist.
Handling IO Exceptions
Task: Create Employees.txt file under C:\Python37\
CCReddy\Employees directory and
Imagine that Employees directory is not existed in C:\
Python37\CCReddy directory then exception comes.
Whenever exception comes then create Employees
directory and in this directory create Employees.txt
file by using try, except and finally blocks
Note: Remove Employees directory if exists and
execute the following code:
import os
try:
f=open("C:\Python37\CCReddy\Employees\Employees.txt",'w')
except IOError:  (or) except:
print("Employees sub directory is not available")
os.mkdir("C:\Python37\CCReddy\Employees")
print("Now, Employees Sub directory is created")
finally:
f=open("C:\Python37\CCReddy\Employees\Employees.txt",'w')
f.write("1001,Raju,100000")
print("Employee record is written successfully")
f.close()
Execution: Run menu  Run Module
Employees sub directory is not available
Now, Employees sub directory is created
Employee record is written successfully
Now, Open Windows explorer and see in C:\
Python37\CCReddy\Employees directory, Here
Employees.txt file is found
Regular Expressions
Introduction to Regular Expressions
A RegEx, or Regular Expression, is a sequence of
characters that forms a search pattern. (or) A regular
expression in a programming language is a special text
string used for describing a search pattern. It is
extremely useful for extracting information from text
such as code, files, log, spreadsheets or even
documents.
RegEx can be used to check if a string contains the
specified search pattern.
 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
 To see re module: help(“re”)
 To import re type the following import statement:
import re
Examples for Simple Character Matches:
RegularExpression.py
import re
count=0
pattern=re.compile("TCS“)
match=pattern.finditer("TCS stands for Tata
Consultancy Services. TCS is a top rated software
cosultancy company")
for i in match:
count=count+1
print("TCS word is existed for ",count," times")
Execution: Run Menu  Run Module
TCS word is existed for 2 times
RegularExpression.py
import re
count=0
data=input("Enter any text:")
word=input("What word you want to search:")
pattern=re.compile(word)
match=pattern.finditer(data)
for i in match:
count=count+1
print(word," word is existed for ",count," times")
Execution: Run Menu  Run Module
Enter any text:TCS stands for Tata Consultancy
Services. TCS is top rated Software consultancy.
What word you want to search:TCS
TCS word is existed for 2 times

Execute again:
Enter any text: apple is a good fruit. Eat an apple
keeps a doctor away.
What word you want to search: apple
apple word is existed for 2 times
On Match object we can call the following methods.
1. start()  Returns start index of the match
2. end()  Returns end+1 index of the match
3. group()  Returns the matched string
RegularExpression.py
import re
count=0
pattern=re.compile("WIPRO“)
matcher=pattern.finditer("WIPRO,Facebook,Microsoft
,twitter,WIPRO,TCS,Amazon,Flipcart,snapdeal,WIPRO,T
echMahendra")
for match in matcher:
count+=1
print(match.start(),"...",match.end(),"...",
match.group())
print("The number of occurrences: ",count)
Execution: Run Menu  Run Module
0 ... 5 ... WIPRO
33 ... 38 ... WIPRO
68 ... 73 ... WIPRO
The number of occurrences: 3
Character classes:
We can use character classes to search a group of
characters
1. [abc]===>Either a or b or c
2. [^abc] ===>Except a and b and c
3. [a-z]==>Any Lower case alphabet symbol
4. [A-Z]===>Any upper case alphabet symbol
5. [a-zA-Z]==>Any alphabet symbol
6. [0-9] Any digit from 0 to 9
7. [a-zA-Z0-9]==>Any alphanumeric character
8. [^a-zA-Z0-9]==>Except alphanumeric
characters(Special Characters)
Special Characters
b7c@k9z
[abc]
0 ...... b
2 ...... c

[^abc]
1 ...... 7
3 ...... @
4 ...... k
5 ...... 9
6 ...... z
[a-z]
0 ...... b
2 ...... c
4 ...... k
6 ...... z

[0-9]
1 ...... 7
5 ...... 9
[a-zA-Z0-9]
0 ...... b
1 ...... 7
2 ...... c
4 ...... k
5 ...... 9
6 ...... z

[^a-zA-Z0-9]
3 ...... @
RegularExpression.py
import re
pattern=re.compile("[abc]")
match=pattern.finditer("b7c@k9z")
for i in match:
print(i.start(),"...",i.group())
Execution: Run Menu  Run Module
0 ... b
2 ... c
RegularExpression.py
import re
pattern=re.compile("[^abc]")
match=pattern.finditer("b7c@k9z")
for i in match:
print(i.start(),"...",i.group())
Execution: Run Menu  Run Module
1 ... 7
3 ... @
4 ... k
5 ... 9
6 ... z
Note: Like this you can try: [a-z] [0-9] [a-zA-Z0-9]
[^a-zA-Z0-9]
Pre defined Character classes:
\s  Space character
\S  Any character except space character
\d  Any digit from 0 to 9
\D  Any character except digit
\w  Any word character [a-zA-Z0-9]
\W  Any character except word character (Special
Characters)
\s  Space character
RegularExpression.py
import re
pattern=re.compile("\s")
match=pattern.finditer("b7c@k9z")
for i in match:
print(i.start(),"...",i.group())
Execution: Run Menu  Run Module
No output because there is no space
\S  Any character except space character
RegularExpression.py
import re
pattern=re.compile("\S")
match=pattern.finditer("b7c@k9z")
for i in match:
print(i.start(),"...",i.group())
Execution: Run Menu  Run Module
0 ... b
1 ... 7
2 ... c
3 ... @
4 ... k
5 ... 9
\d  Any digit from 0 to 9
RegularExpression.py
import re
pattern=re.compile("\d")
match=pattern.finditer("b7c@k9z")
for i in match:
print(i.start(),"...",i.group())
Execution: Run Menu  Run Module
1 ... 7
5 ... 9
Note: Like this try: \D \w [a-zA-Z0-9] \W .
Quantifiers:
We can use quantifiers to specify the number of
occurrences to match.
RegularExpression.py
import re
pattern=re.compile("a") a: Exactly one 'a'
match=pattern.finditer("apple,banana,cherry")
for i in match:
print(i.start(),"...",i.group())
Execution: Run Menu  Run Module
0 ... a
7 ... a
9 ... a
11 ... a
RegularExpression.py
import re
pattern=re.compile("a{2}")  a{m} : Exactly m
number of a's (side by side)
match=pattern.finditer("apple,banana,aa")
for i in match:
print(i.start(),"...",i.group())
Execution: Run Menu  Run Module
13 ... aa
RegularExpression.py
import re
pattern=re.compile("a{2,3}")  a{m,n} : Minimum m
number of a's and Maximum n number of a's
match=pattern.finditer("apple,banana,aa,aaa")
for i in match:
print(i.start(),"...",i.group())
Execution: Run Menu  Run Module
13 ... aa
16 ... aaa
Greedy Matches:
Let's say we have the following string in Python,
shown below:
string1= "<ul><li>Item 1</li> <li>Item 2</li> <li>Item
3</li><ul>"
If you're familiar with HTML, you know that we're
making an unordered list of items.
Now let's say we want to write a regular expression so
that we get all content from all of the <li> </li> tags.
Greedy matching will grab all of the li tags and return
them as if a single unit. It will be "greedy" and grab
the first to the last li tags from the above string.
This is greedy matching, when the program takes the
whole code (all the li tags) and grabs them as if a
single li tag.
Lazy matching, on the other hand, will take the small
occurrence of <li></li> tags and, in so doing, returns
each <li></li> individually. Many times, lazy matching
is what we want.
greedymatch.py
import re
string1= "<html><head><title>Web
Page1</title></head><body><ul><li>Item 1</li>
<li>Item 2</li> <li>Item 3</li><ul></body></html>"
regex= re.compile("<li>.*</li>")
matches= re.findall(regex, string1)
print(matches)
Execution: Run Menu  Run Module
['<li>Item 1</li> <li>Item 2</li> <li>Item 3</li>']
Important functions of re module:
1.compile()
2. finditer()
3. findall()
4. match()
5. fullmatch()
6. sub()
7.subn()
8.split()
Note: We have already seen “compile(), findall(),
finditer()” functions
Let us see the remaining functions.
1. match():
If we want to search a string at the beginning of the
paragraph or text then we can prefer this match()
function.
test.py
import re
string=input("Enter a pattern to check: ")
m=re.match(string,"apple is a good fruit")
if m!=None:
print("Match is available at the beginning of the
String")
else:
print("Match is not available at the beginning of the
String")
Execution: Run Menu  Run Module
Enter a pattern to check: apple
Match is available at the beginning of the String

Change the code as follows:


m=re.match(string,"Good fruit is apple")
Note: remaining code is same as above
Execute now:
Enter a pattern to check: apple
Match is not available at the beginning of the String
2. fullmatch()
If exactly entire text should be matched then we can
use fullmatch() function (or) If searching pattern is
exactly matched with entire data or entire text then
we can use fullmatch() function.
test.py
import re
string=input("Enter a pattern to check: ")
m=re.fullmatch(string,"apple is a good fruit")
if m!=None:
print("Full Match is available")
else:
print("Full Match is not available")
Execution: Run Menu  Run Module
Output:
Enter a pattern to check: apple is a good fruit
Full Match is available
3. sub():
sub means substitution or replacement
re.sub(regex,replacement,targetstring)
In the target string every matched pattern will be
replaced with provided replacement
test.py
import re
string=re.sub("apple","grapes","apple banana cherry
apple")
print(string)
Execution: Run Menu  Run Module
grapes banana cherry grapes
4. 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)
test.py
import re
text=input("Enter any text:")
old=input("Enter old string:")
new=input("Enter new string:")
string=re.subn(old,new,text)
print(string)
Execution: Run Menu  Run Module
Enter any text:apple banana cherry apple
Enter old string:apple
Enter new string:grapes
('grapes banana cherry grapes', 2)
5. 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.
test.py
import re
list1=re.split(" ","apple banana cherry")
print(list1)
Execution: Run Menu  Run Module
['apple', 'banana', 'cherry']
Note: 9) compile() function is seen for multiple times
in the above examples
Database Access /
Python Database
Programming
Introduction to Database:
A database is a collection of Tables.

A table is a collection of rows and columns.

 A column is also called as a field

 A row is also called as a record.


Steps:
1) Import database module:
Eg: import mysql.connector
2) Establish Connection between Python Program
and database:
We can create connection object by using connect()
function.
Eg: con=mysql.connector.connect(host='localhost',
user='root',password='root')
3) Execute sql queries:
To execute sql queries and to hold query results,
Cursor object is required. Cursor object is created by
using cursor() method.
Eg: cursor=con.cursor()
We can execute SQL Queries By using Cursor object.
Eg: cursor.execute("show databases")

4) Fetch(get) the result from the Cursor object


We can fetch the results from the cursor object by
using fetchall() method
Eg: databases=cursor.fetchall()

5)Display the fetched results:


We can display the fetched results by using for loop:
Eg: for i in databases:
print(i)
6) Close the database connection (or) close the
database objects (or) Closing mysql database
connections
Once Database related operations are completed then
it is always recommended to close the database
objects.
Eg:
cursor.close()
con.close()
All the above steps are written in python program as
follows:

Open Python IDLE window, then select "New File"


from File menu and type the following python
program:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',u
ser='root',password='root')
cursor=con.cursor()
cursor.execute("show databases")
databases=cursor.fetchall()
for i in databases:
print(i)
except mysql.connector.DatabaseError as e:
print(e)
finally:
cursor.close()
con.close()
print("Database connection is disconnected successfully")
Note: The Database runtime errors(Database
exceptions) are handled with “try-except-finally” blocks
Save the file and select "Run Module" option from
"File Menu"
Output:
('information_schema',)
('mysql',)
('performance_schema',)
('sakila',)
('sys',)
('world',)
Database connection is disconnected successfully
In the output, the list of databases are displayed
from mysql database server.
Task:
i) Establish connection mysql database
ii) Create employees Database
iii) After creation of employees database, display the
list of databases
iv) Close the database connection

Open Python IDLE window, then select "New File"


from File menu and type the following python
program:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',u
ser='root',password='root')
cursor=con.cursor()
cursor.execute("create database employees")
print("employees database is created
successfully")
print("LIST OF DATABASES:")
cursor.execute("show databases")
databases=cursor.fetchall()
for i in databases:
print(i)
except mysql.connector.DatabaseError as e:
print(e)
finally:
con.close()
print("Database connection is disconnected
successfully")

Save the file and select “Run Module option from Run
Menu
Output:
employees database is created successfully
LIST OF DATABASES:
('employees',)
('information_schema',)
('mysql',)
('performance_schema',)
('sys',)
('world',)
Database connection is disconnected successfully
The following exception comes when executed again
1007 (HY000): Can't create database 'employees';
database exists
Database connection is disconnected successfully
Task:
i) Establish the connection to mysql database
ii) Create “emp” table under “employees” database
with the following columns:
ID, name, department, designation, salary
iii) Once “emp” table is created then give a message
that “emp table is created”
iv) Display the list of tables from “employees”
database
v) If already “emp” table is existed under
“employees” database then give an error message
Open Python IDLE window, then select "New File"
from File menu and type the following python
program:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',u
ser='root',password='root')
cursor=con.cursor()
cursor.execute("use employees")
print("Present Database is employees")
cursor.execute("create table emp(ID int,name
char(20),department char(20),designation
char(10),salary int)")
print("emp table is created successfully")
cursor.execute("show tables")
tables=cursor.fetchall()
for i in tables:
print(i)
except mysql.connector.DatabaseError as e:
print(e)
finally:
con.close()
print("Database connection is disconnected
successfully")

Save the file and select “Run Module” option from


Run Menu
Output:
Present Database is employees
emp table is created successfully
('emp',)
Database connection is disconnected successfully
The following exception comes when executed again
Present Database is employees
1050 (42S01): Table 'emp' already exists
Database connection is disconnected successfully
Another similar type of task:
i) Establish the connection to mysql database
ii) Under “employees” database, Create
“departments” table with the following columns:
department_ID, department_name,
department_address
iii) Once “departments” table is created then give a
message that “department table is created”
iv) Display the list of tables from “employees”
database
v) If already “department” table is existed under
“employees” database then give an error message
Open Python IDLE window, then select "New File“ from
File menu and type the following python program:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',u
ser='root',password='root')
cursor=con.cursor()
cursor.execute("use employees")
print("Present Database is employees")
cursor.execute("create table
departments(department_ID
int,department_name
char(20),department_address char(20))")
print("departments table is created
successfully")
print("LIST OF TABLES")
cursor.execute("show tables")
tables=cursor.fetchall()
for i in tables:
print(i)
except mysql.connector.DatabaseError as e:
print(e)
finally:
con.close()
print("Database connection is disconnected
successfully")
Save the program and select “Run Module” option
from “Run Menu”
Output:
Present Database is employees
departments table is created successfully
LIST OF TABLES
('departments',)
('emp',)
Database connection is disconnected successfully
The following exception comes when executed again
Present Database is employees
1050 (42S01): Table 'departments' already exists
Database connection is disconnected successfully
Task:
i) Establish the connection to MySQL rdbms
ii) Use employees database
iii) Insert the records into “emp” tables
iv) After insertion of records, display a message that
“records are inserted successfully”
v) Display the employees records
vi) Close the database connection

Open python IDLE window, select “New File” option


from “File Menu” and type the following program:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',u
ser='root',password='root')
cursor=con.cursor()
cursor.execute("use employees")
print("Present Database is employees")
cursor.execute("insert into emp
values(1001,'Raju','IT','SE',100000)")  It is also
called as “Execution of insert command or insert
query”
cursor.execute("insert into emp
values(1002,'Roja','IT','SE',150000)")
con.commit()
print("Records are inserted successfully...")
print("EMPLOYEE RECORDS")
cursor.execute("select * from emp")  It is also
called as “Execution of select query”
employees_records=cursor.fetchall()
for i in employees_records:
print(i)
except mysql.connector.DatabaseError as e:
print(e)
finally:
cursor.close()
con.close()
print("Database connection is disconnected
successfully")
Save the program and select “Run Module” option
from “Run” Menu

Output:
Present Database is employees
Records are inserted successfully...
EMPLOYEE RECORDS
(1001, 'Raju', 'IT', 'SE', 100000)
(1002, 'Roja', 'IT', 'SE', 150000)
Database connection is disconnected successfully
Another similar type of Task:
i) Establish the connection to MySQL rdbms
ii) Use employees database
iii) Insert the records into “departments” tables
iv) After insertion of records, display a message that
“records are inserted successfully”
v) Display the records of departments
vi) Close the database connection

Open python IDLE window, select “New File” option


from “File Menu” and type the following program:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',u
ser='root',password='root')
cursor=con.cursor()
cursor.execute("use employees")
print("Present Database is employees")
cursor.execute("insert into departments
values(10,'IT','Hyd')")
cursor.execute("insert into departments
values(11,'Testing','Chennai')")
con.commit()
print("Records are inserted successfully...")
print("RECORDS OF DEPARTMENTS")
cursor.execute("select * from departments")
employees_records=cursor.fetchall()
for i in employees_records:
print(i)
except mysql.connector.DatabaseError as e:
print(e)
finally:
cursor.close()
con.close()
print("Database connection is disconnected
successfully")
Save the program and select “Run Module” option
from “Run Menu”
Output:
Present Database is employees
Records are inserted successfully...
RECORDS OF DEPARTMENTS
(10, 'IT', 'Hyd')
(11, 'Testing', 'Chennai')
Database connection is disconnected successfully
Task:
1)Establish the connection to MySQL database
2)Go to “Employees” Database
3)Ask the user to enter the following employee
details:
i) Employee ID
ii) Employee Name
iii) Department Name
iv) Designation
v) Salary
4)After entering a record, display a message that:
“Record is inserted Successfully”
5)Next, ask the user that “Do you want to enter one
more record(yes/no)”
6)If user says “yes” then repeat 3, 4, and 5 steps
7)If user says “no” then display all employees records
8)Finally close database connection

Open python IDLE and select “New File” option from


“File” menu and type the following code:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',u
ser='root',password='root')
cursor=con.cursor()
cursor.execute("use employees")
print("Present Database is employees")
ans="yes"
while ans=="yes":
eid=int(input("Enter Employee ID:"))
ename=input("Enter Employee Name:")
edept=input("Enter Department Name:")
edesg=input("Ener Designation:")
esal=int(input("Enter Employee salary:"))
records="insert into emp
values(%d,'%s','%s','%s',%d)"
cursor.execute(records
%(eid,ename,edept,edesg,esal))
print("Record Inserted Successfully")
ans=input("Do you want to enter one more
record(yes/no):")
if ans=="no":
con.commit()
break
#while loop is completed
print("RECORDS OF EMPLOYEES")
cursor.execute("select * from emp")
employees_records=cursor.fetchall()
for i in employees_records:
print(i)
#try block is completed
except mysql.connector.DatabaseError as e:
print(e)
#except block is completed
finally:
cursor.close()
con.close()
print("Database connection is disconnected
successfully")
#finally block is completed
Save the file and select “Run Module” option from
“Run” Menu
Output:
Present Database is employees
Enter Employee ID:1001
Enter Employee Name:Raju
Enter Department Name:IT
Ener Designation:SE
Enter Employee salary:100000
Record Inserted Successfully
Do you want to enter one more record(yes/no):yes
Enter Employee ID:1002
Enter Employee Name:Roja
Enter Department Name:IT
Ener Designation:SE
Enter Employee salary:120000
Record Inserted Successfully
Do you want to enter one more record(yes/no):no
RECORDS OF EMPLOYEES
(1001, 'Raju', 'IT', 'SE', 100000)
(1002, 'Roja', 'IT', 'SE', 120000)
Database connection is disconnected successfully
Task:
i) Connect to MySQl database
ii) Go to “Employees” database
iii) Display the records of “department” table
iv) Ask the user that “which department address you
want to change (Enter department ID)”
v) Ask the user to enter new address of the department
vi) Update the department address
vii) After updation, display a confirmation message that
“Record is updated successfully”
viii) Display the records of “department” table to show
the updated record
ix) Finally close the database connection
Open Python IDLE, select “New File” option from “File
Menu” and type the following program:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',user
='root',password='root')
cursor=con.cursor()
cursor.execute("use employees")
print("Present Database is employees")
print("EMPLOYEES RECORDS:")
print("RECORDS OF DEPARTMENTS TABLE")
cursor.execute("select * from departments")
department_records=cursor.fetchall()
for i in department_records:
print(i)
dept_id=int(input("which department address you
want to change (Enter department ID):"))
new_address=input("Enter new address of the
department:")
records="update departments set
department_address='%s' where department_ID=%d"
cursor.execute(records %(new_address,dept_id))
print("Record is updated successfully")
con.commit()
print("RECORDS OF DEPARTMENTS TABLE")
cursor.execute("select * from departments")
department_records=cursor.fetchall()
for i in department_records:
print(i)
#try block is completed
except mysql.connector.DatabaseError as e:
print(e)
#except block is completed
finally:
cursor.close()
con.close()
print("Database connection is disconnected
successfully")
Save the program and select “Run Module” option from
“Run Menu”
Output:
Present Database is employees
EMPLOYEES RECORDS:
RECORDS OF DEPARTMENTS TABLE
(10, 'IT', 'Banglore')
(11, 'Testing', 'Chennai')
which department address you want to change (Enter
department ID):11
Enter new address of the department:Delhi
Record is updated successfully
RECORDS OF DEPARTMENTS TABLE
(10, 'IT', 'Banglore')
(11, 'Testing', 'Delhi')
Database connection is disconnected successfully
Task:
1) Connect to MySQL database
2) Display the list of tables under “Employees” Database
3) Ask the user that "Records of which table you want to
delete:"
4) After deleting the records of specified table then
display a confirmation message that “Records are
displayed successfully
5) Close the Database Connection
Open Python IDLE window and select “new file” option
from “file menu” and type the following program:
import mysql.connector
try:
con=mysql.connector.connect(host='localhost',user
='root',password='root')
cursor=con.cursor()
cursor.execute("use employees")
print("Present Database is employees")
print("LIST OF TABLES IN EMPLOYEES DATABASE:")
cursor.execute("show tables")
tables=cursor.fetchall()
for i in tables:
print(i)
table=input("Records of which table you want to
delete:")
delete_table_records="delete from %s”
cursor.execute(delete_table_records %(table))
con.commit()
print("Records of",table," deleted successfully")
except mysql.connector.DatabaseError as e:
print(e)
finally:
cursor.close()
con.close()
print("Database connection is disconnected
successfully")
Save the program and select “Run Module” option from
“Run Menu”
Output:
Present Database is employees
LIST OF TABLES IN EMPLOYEES DATABASE:
('departments',)
('emp',)
Records of which table you want to delete:departments
Records of departments deleted successfully
Database connection is disconnected successfully
Advanced Concepts
Python Iterator:
If we want to split a given string into characters then
we use “Python Iterator”.
Note: Each character is again a string in python.

Open Python IDLE, select “New File” option from


“file menu” and type the following code:
string=input("Enter a string:")
iterator1=iter(string)
print(type(iterator1))
print(list(iterator1))

Save the program and select “Run Module” option


from “Run Menu”
Output:
Enter a string:PythonProgramming
<class 'str_iterator'>
['P', 'y', 't', 'h', 'o', 'n', 'P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i',
'n', 'g']
Python Generator
Generator is a function which is responsible to
generate a sequence of values.
Let us see an example without “Python Generator”
concept:
Example.py:
def decrement(n):
list1=[]
for i in range(n,0,-1):
list1.append(i)
return list1

values=decrement(10)
for i in values:
print(i)
Save the program. Select “Run Module” option from
“Run” Menu
Output:
10
9
8
7
6
5
4
3
2
1
Let us try same above example with “Python
Generator” concept as follows:
PythonGenerator.py
def decrement(n):
while n>0:
yield n  This line is related to Python Generator
n=n-1

values=decrement(10)
for i in values:
print(i)
Save the file and select “Run Module” option from
Run Menu
Output:
10
9
8
7
6
5
4
3
2
1
Python Closure
When do we have a closure?
1)We must have a nested function (function inside a
function).
2)The nested function must refer to a value defined in
the enclosing function.
3)The enclosing function must return the nested
function.
ClosureExample.py
def enclosure_function(n): #enclosing function
def nested_function(x): #nested function
return x * n
return nested_function

times3 = enclosure_function(3) #n=3

times5 = enclosure_function(5) #n=5

print(times3(9)) #x=9 Output:27 i.e. x*n 9*3=27

print(times5(3)) #x=3 Output:15 i.e. x*n 3*5=15


Save the program and select “Run Module” option
from “Run” Menu
Output:
27
15
Python Decorators:
Decorator is a function which takes a function as
argument and extend its functionality and returns
modified function with extended functionality.
(or)
Decorators are very powerful and useful tool
in Python since it allows programmers to modify the
behavior of function or class.
The main objective of decorator function is that we
can extend the functionality of existing function
without modifying the existed function.
>>> def wishes(name):  defining the function
print(name,“ Good morning")
>>> wishes('Ravi')  Calling the function
Ravi Good morning
Note: Here, wishes() function is a normal function and
for every given name it gives same message i.e “Good
morning”
Now, we write a decorator function to extend the
functionality of “wishes()” function without
disturbing the “wishes()” function.
decorator.py
def blessed_day_decorator(function):
def inner(name):
if name=="Juido Van Rossum":
print("Father of Python, have a blessed day")
else:
function(name)
return inner
Save the file and select “Run Module” option from
“Run” Menu
>>> @blessed_day_decorator
def wishes(name):
print(name," Good morning")

>>> wishes("ravi")
ravi Good morning
>>> wishes("Juido Van Rossum")
Father of Python, have a blessed day
So, when “Juido van Rossum” name is given then
special wishes are displayed i.e. “Father of Python
have a blessed day” and when other names are
given then just “Good morning” is displayed.
So, without disturbing “wishes” function, we can
extend the functionality of “wishes” function through
decorator function.
PIP
 PIP stands for “Python Package Index (PyPI)”.
 PIP is used to install python modules.
Steps to install python modules through PIP
command:
1) click on start menu
2) type cmd (i.e command prompt)
Now perform as follows:
 To test whether “cx_Oracle oracle connector for
python” is installed or not:
Open Python IDLE and execute the help() functions as
follows:
>>>help(“modules”)
 Now, uninstall “cx_Oracle” module as follows:
Start Menu  type cmd and go to D: drive and give
as follows:
 To test whether “cx_Oracle oracle connector for
python” is uninstalled or not:
Open Python IDLE and execute the help() functions as
follows:
>>>help(“modules”)
cx_Oracle module will not be found
(OR)
>>> help("cx_Oracle")
No Python documentation found for 'cx_Oracle'.
Working with CSV (Comma Separated Values):
The programmer can process “CSV” files in python.
Steps:
Open Python IDLE window  File Menu  New File
Option and type the following data:
1001,Ravi,IT,SE,100000
1002,Raju,IT,SE,120000
After typing the above data, File Menu  save option
Select CCReddy directory and type “employees.csv” in
File name text box.
Next, File Menu  New File option and type the
following code:
import csv
'''In python the "with" keyword is used when working
with file streams'''
with open('employees.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
csvfile.close()
Save the program and select Run Module option
from Run Menu
Output:
['1001', 'Ravi', 'IT', 'SE', '100000']
['1002', 'Raju', 'IT', 'SE', '120000']
Working with json:
JSON=Java Script Object Notation
 Java Script Object Notation represents the data in
the form of {Key: value} pairs
Steps:
Open Python IDLE window  File Menu  New File
Option and type the following data:
{
"EmployeeID": 1001,
"EmployeeName": "Raju",
"Department": "IT",
"Designation": "SE",
"Salary": 100000
}
After typing the above data, File Menu  save option
Select CCReddy directory and type “employees.json”
in File name text box.
Next, File Menu  New File option and type the
following code:
import json
with open('person.json', 'r') as jsonfile:
data = json.load(jsonfile)
for i in data.items():
print(i)
jsonfile.close()
Save the program and select Run Module option
from Run Menu
Output:
('EmployeeID', 1001)
('EmployeeName', 'Raju')
('Department', 'IT')
('Designation', 'SE')
('Salary', 100000)
Working with xml:
XML = eXtensible Markup Language
XML format is tags format
Programmer can process XML files with Python
Programming language.
Steps:
First create an XML file. Eg: employees.xml
Open Python IDLE window, File Menu  New File
option  type the following xml coding  select save
option from File Menu and type “employees.xml” in
File name text box
<EmployeeRecords>
<employee title="Employee Record-1">
<id>1001</id>
<name>Raju</name>
<dept>IT</dept>
<desg>SE</desg>
<salary>100000</salary>
</employee>
<employee title="Employee Record-2">
<id>1002</id>
<name>Rani</name>
<dept>IT</dept>
<desg>SE</desg>
<salary>100000</salary>
</employee>
</EmployeeRecords>

Next, Open New File by selecting New File option


from File Menu and type the following Python
program code and save the file as xmlprocessing.py
xmlprocessing.py
import xml.sax #sax stands for "structure for an XML"
class Employees(xml.sax.ContentHandler):
def __init__(self):
self.CurrentData = ""
self.id = ""
self.name = ""
self.dept = ""
self.desg = ""
self.salary = ""
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "employee":
print("*****EMPLOYEE*****")
title = attributes["title"]
print("Title:", title)
# Call when an elements ends
def endElement(self, tag):
self.CurrentData = tag
if self.CurrentData == "id":
print("ID:", self.id)
elif self.CurrentData == "name":
print("Name:", self.name)
elif self.CurrentData == "dept":
print("Department:", self.dept)
elif self.CurrentData == "desg":
print("Designation:", self.desg)
elif self.CurrentData == "salary":
print("Salary:", self.salary)
# Call when a character is read
def characters(self, content):
if self.CurrentData == "id":
self.id = content
elif self.CurrentData == "name":
self.name = content
elif self.CurrentData == "dept":
self.dept = content
elif self.CurrentData == "desg":
self.desg = content
elif self.CurrentData == "salary":
self.salary = content

# create an XMLReader
parser = xml.sax.make_parser()
# override the default ContextHandler
emp = Employees()
parser.setContentHandler(emp)
parser.parse("employees.xml")
Save the file and select Run Module option from Run
Menu
Output:
*****EMPLOYEE*****
Title: Employee Record-1
ID: 1001
Name: Raju
Department: IT
Designation: SE
Salary: 100000
*****EMPLOYEE*****
Title: Employee Record-2
ID: 1002
Name: Rani
Department: IT
Designation: SE
Salary: 100000

**************COMPLETED*******************

You might also like