0% found this document useful (0 votes)
15 views

PYTHON Unit 2

The document is a course outline for Python Programming at Hindusthan College of Engineering & Technology, covering core topics such as input/output, lists, tuples, dictionaries, string manipulation, errors, exceptions, functions, modules, classes, and regular expressions. It includes examples and programs demonstrating various Python functionalities, including reading user input, list operations, and tuple creation. The document serves as a comprehensive guide for students learning Python programming concepts and practices.

Uploaded by

nirmala.mca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

PYTHON Unit 2

The document is a course outline for Python Programming at Hindusthan College of Engineering & Technology, covering core topics such as input/output, lists, tuples, dictionaries, string manipulation, errors, exceptions, functions, modules, classes, and regular expressions. It includes examples and programs demonstrating various Python functionalities, including reading user input, list operations, and tuple creation. The document serves as a comprehensive guide for students learning Python programming concepts and practices.

Uploaded by

nirmala.mca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY

16CA5202 – PYTHON PROGRAMMING


(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Files – Input and Output – Errors and Exceptions – Functions – Modules –
Classes and Objects – regular Expressions
Table of Contents

INPUT AND OUTPUT .............................................................................................................. 1


LISTS .......................................................................................................................................... 3
TUPLES ...................................................................................................................................... 8
DICTIONARIES....................................................................................................................... 15
STRING MANIPULATION .................................................................................................... 20
ERRORS AND EXCEPTIONS ................................................................................................ 32
ASSERTIONS .......................................................................................................................... 38
FUNCTIONS ............................................................................................................................ 41
SEARCHING, SORTING IN PYTHON .............................................................................. 48
HASH TABLES IN PYTHON ............................................................................................ 51
MODULES ............................................................................................................................... 53
CLASSES AND OBJECTS ...................................................................................................... 56
REGULAR EXPRESSIONS .................................................................................................... 65

INPUT AND OUTPUT

Reading Keyboard Input


Python provides two built-in functions to read a line of text from standard input
 input

The input Function


The input([prompt]) function is used to get the input from the user until ENTER key
or RETURN key ispressed

Program No : 1

str = input("Enter your input : ");


print ("Received input is : ", str)
# to get integer input values
num1 = int(input("Enter a Number : "))
sum = num1+10
print(sum)

num2 = float(input("Enter a Float Number : "))


sum = num2+10
print(sum)

num3 = complex(input("Enter a Complex Number : "))


sum = num3 + 10

Page No : 1 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print(sum)

Output No : 1

Enter your input : hari


Received input is : hari
Enter a Number : 12
22
Enter a Float Number : 12.5
22.5
Enter a Complex Number : 3+4j
(13+4j)

Python Output Using print() function


The print() function to output data to the standard output device (screen).

The actual syntax of the print() function is


print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

 Here, objects is the value(s) to be printed.


 The sep separator is used between the values. It defaults into a space character.
 After all values are printed, end is printed. It defaults into a new line.
 The file is the object where the values are printed and its default value
is sys.stdout(screen).

Program No : 2

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

Output No : 2

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

Output formatting

 str.format is used to make the output attractive. This method is visible to any
string object.
 Keyword arguments can be used to format the string.

Page No : 2 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
 % operator is used to format strings line the old sprintf() style used in C
programming language.
 The curly braces {} are used as placeholders. The order of the values to be
printed can be specified by tuple index.

Program No : 3

x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
print('I love {0} and {1}'.format('mom','dad'))
print('I love {1} and {0}'.format('mom','dad'))
print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
x = 12.3456789
print('The value of x is %3.2f' %x)
print('The value of x is %3.4f' %x)
name= "education"
print('The value of name is %10.6s' %name)
print('The value of name is %-10.6s' %name)

Output No : 3

The value of x is 5 and y is 10


I love mom and dad
I love dad and mom
Hello John, Goodmorning
The value of x is 12.35
The value of x is 12.3457
The value of name is educat
The value of name is educat

LISTS

 Python lists are the data structure that is capable of holding different type of data.
 Python lists are mutable i.e., Python will not create a new list if we modify an
element in the list.
 It is a container that holds other objects in a given order.
 Different operation like insertion and deletion can be performed on lists.
 A list can be composed by storing a sequence of different type of values separated
by commas.
 A python list is enclosed between square([]) brackets and each item is separated
by a comma.

Page No : 3 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
The elements are stored in the index basis with starting index as 0.
eg:
1. data1=[1,2,3,4];
2. data2=['x','y','z'];
3. data3=[12.5,11.6];
4. data4=['raman','rahul'];
5. data5=[];
6. data6=['abhinav',10,56.4,'a'];

Methods of List objects


Calls to list methods have the list they operate on appear before the method
name separated by a dot, e.g. L.reverse()

Program No : 4

# Creation of List
L = ['yellow', 'red', 'blue', 'green', 'black']
print (L)

# Accessing or Indexing
print (L[0])

#Slicing
print(L[1:4])
print(L[2:])
print(L[:2])
print(L[-1])
print(L[1:-1])

#length of the List


print(len(L))
print(sorted(L))

# appending an ietm into the List


L.append("Pink")
print(L)

#inserting element inbetween by specifying the index


L.insert(4,"White")
print(L)

#extends - grow list as that of others


L2 = ['purple', 'grey', 'violet']

Page No : 4 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
L.extend(L2)
print(L)

#Remove - remove first item in list with value "white" based on value
L.remove("White")
print(L)

# Remove an item from a list given its index instead of its value
del L[0]
print(L)

# pop - removes last item from the list


L.pop()
print(L)

#pops element based on index provided


L.pop(1)
print(L)

#reversing the List


L.reverse()
print(L)

#Search list and return number of instances found - count


print(L.count("purple"))

Output No : 4

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/list2.py
['yellow', 'red', 'blue', 'green', 'black']
yellow
['red', 'blue', 'green']
['blue', 'green', 'black']
['yellow', 'red']
black
['red', 'blue', 'green']
5
['black', 'blue', 'green', 'red', 'yellow']
['yellow', 'red', 'blue', 'green', 'black', 'Pink']
['yellow', 'red', 'blue', 'green', 'White', 'black', 'Pink']
['yellow', 'red', 'blue', 'green', 'White', 'black', 'Pink', 'purple', 'grey', 'violet']
['yellow', 'red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey', 'violet']

Page No : 5 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
['red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey', 'violet']
['red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey']
['red', 'green', 'black', 'Pink', 'purple', 'grey']
['grey', 'purple', 'Pink', 'black', 'green', 'red']

Program No : 5
Write a Python program to check whether a list contains a sublist.

LL=[]
SL=[]
N = int(input("Enter the Number of elements in List :"))
for i in range(0,N):
item = int(input("Enter Elements for List :"))
LL.append(item)

N = int(input("Enter the Number of elements in sublist :"))


for i in range(0,N):
item = int(input("Enter Elements for List :"))
SL.append(item)
print(LL)
print(SL)

sub_set = False
if SL == []:
sub_set = True
elif SL == LL:
sub_set = True
elif len(SL) > len(LL):
sub_set = False
else:
for i in range(len(LL)):
if LL[i] == SL[0]:
n=1
while (n < len(SL)) and (LL[i+n] == SL[n]):
n += 1
if n == len(SL):
sub_set = True

print(sub_set)

Output No : 5

Page No : 6 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36-32/sample
programs/list2.py
Enter the Number of elements in List :6
Enter Elements for List :1
Enter Elements for List :2
Enter Elements for List :3
Enter Elements for List :4
Enter Elements for List :5
Enter Elements for List :6
Enter the Number of elements in sublist :3
Enter Elements for List :1
Enter Elements for List :2
Enter Elements for List :3
[1, 2, 3, 4, 5, 6]
[1, 2, 3]
True
>>>
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/sample programs/list2.py
Enter the Number of elements in List :5
Enter Elements for List :1
Enter Elements for List :2
Enter Elements for List :3
Enter Elements for List :4
Enter Elements for List :5
Enter the Number of elements in sublist :3
Enter Elements for List :6
Enter Elements for List :7
Enter Elements for List :8
[1, 2, 3, 4, 5]
[6, 7, 8]
False

Program No : 6

Write a Python program to count the number of elements in a list within a


specified range.

LL=[]
N = int(input("Enter the Number of elements in List :"))
for i in range(0,N):
item = int(input("Enter Elements for List :"))
LL.append(item)

Page No : 7 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
min = int(input("Enter the Minimum Range Value :"))
max = int(input("Enter the Maximum Range Value :"))
ctr = 0
for x in LL:
if min <= x <= max:
ctr += 1
print(" Count of Elements between the range ",min, "and" ,max ,"=",ctr)

Output No : 6

RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -32/sample


programs/list3.py
Enter the Number of elements in List :10
Enter Elements for List :34
Enter Elements for List :12
Enter Elements for List :56
Enter Elements for List :78
Enter Elements for List :23
Enter Elements for List :11
Enter Elements for List :89
Enter Elements for List :90
Enter Elements for List :100
Enter Elements for List :121
Enter the Minimum Range Value :50
Enter the Maximum Range Value :100
Count of Elements between the range 50 and 100 = 5

Program No : 7

Write a Python program to generate all permutations of a list in Python.

import itertools
print(list(itertools.permutations([1,2,3])))

Output No : 7
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -32/sample
programs/list3.py
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

TUPLES
A Tuple is a collection of immutable Python objects separated by commas.
The difference between the two is that we cannot change the elements of a tuple once
it is assigned whereas in a list, elements can be changed.

Page No : 8 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

Advantages of Tuple over List


Since, tuples are quite similiar to lists, both of them are used in similar situations as
well.
 Tuple are generally used for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
 Since tuple are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
 Tuples that contain immutable elements can be used as key for a dictionary.
With list, this is not possible.
 Tuple will guarantee that it remains write-protected.

Creating a Tuple
A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).

Description Sample Input Output


Tuple Creation mytuple = 1,2,3,4 (1, 2, 3, 4)
A tuple is created by placing print(mytuple) (6, 2, 1, 3)
all the items (elements) mytuple1 = (6,2,1,3)
inside a parentheses (), print(mytuple1)
separated by comma. The
parentheses are optional but
is a good practice to write it.

Empty Tuples Creation tup1 = (); ()


The empty tuple is written as print(tup)
two parentheses containing
nothing −

Concatenation of Tuples tuple1 = (0, 1, 2, 3) (0, 1, 2, 3, 'python',


tuple2 = ('python', 'geek') 'geek')
Tuples can be concatenates # Concatenating above two
using + operator print(tuple1 + tuple2)

Page No : 9 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Nesting of Tuples tuple1 = (0, 1, 2, 3) ((0, 1, 2, 3), ('python',
# Code for creating nested tuple2 = ('python', 'geek') 'geek'))
tuples tuple3 = (tuple1, tuple2)
print(tuple3)

Repetition in Tuples tuple3 = ('python',)*3 ('python', 'python',


Tuples can be repeated print(tuple3) 'python')
using Repetition operator
(*)
Immutable Tuples tuple1 = (0, 1, 2, 3) Traceback (most
#code to test tuple1[0] = 4 recent call last):
that tuples are print(tuple1) File
immutable "C:/Users/MCA/AppD
ata/Local/Programs/P
ython/sample
programs/tuple1.py",
line 5, in <module>
tuple1[0] = 4
TypeError: 'tuple'
object does not
support item
assignment
Slicing a=(1,2,3,4,5,6,7,8) (2, 3, 4)
The slice object initialization # starts from initial index value 1 (2, 4)
takes in 3 arguments with the and ends with final index value - 1 (8, 7, 6, 5, 4, 3, 2, 1)
last one being the optional print(a[1:4]) (8, 6, 4, 2)
index increment. The general #last colon mentions the slicing [2, 3]
method format is: slice(start, increment
stop, increment), and it is #By default, Python sets this
analogous to increment to 1, but that extra colon
start:stop:increment when at the end of the numbers allows us
applied to a list or tuple. to specify the slicing increment
print(a[1:4:2])

#reverse print
print(a[::-1])
#reverse with slicing increment
print(a[::-2])

#using slice
a = [1, 2, 3, 4, 5]

Page No : 10 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
sliceObj = slice(1, 3)
print(a[sliceObj])
In order to delete a tuple, the tuple3 = ( 0, 1) NameError: name
del keyword is used del tuple3 'tuple3' is not defined
print(tuple3)
Built in Tuple Functions
Finding Length of a Tuple tuple2 = ('python', 'program') 2
print(len(tuple2))
Converting a list to a tuple # Code for converting a list and a (0, 1, 2)
string into a tuple ('p', 'y', 't', 'h', 'o', 'n')

list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string
'python'
Using cmp(), max() , min() Maximum element in
tuple1 = ('python', 'good') tuples 1 = python
tuple2 = (4,6,7,1) Maximum element in
tuples 2 = 7
print ('Maximum element in tuples Minimum element in
1 = ' +str(max(tuple1))) tuples 1 = good
print ('Maximum element in tuples Minimum element in
2 = ' +str(max(tuple2))) tuples 2 = 1

print ('Minimum element in tuples 1


= ' +str(min(tuple1)))
print ('Minimum element in tuples 2
= ' +str(min(tuple2)))
Take elements in the tuple ('python', 'good',
and return a new sorted list tuple1 = ('python', 'good','able') 'able')
(does not sort the tuple tuple2 = (4,6,7,1) ['able', 'good',
itself). print(tuple1) 'python']
print(sorted(tuple1)) ('python', 'good',
print(tuple1) 'able')
Return the sum of all tuple2 = (4,6,7,1) 18
elements in the tuple. print(sum(tuple2))

Program No : 8

1. Create a tuple named as TUPLE1 with the following items in the tuple
a. TUPLE1 = (‘tupleexample', False, 3.2, 1)
b. TUPLE2 = tuplex = ("p", "y", "t", "h", "o", "n", "c", "o",“d”,"e")
2. Display the TUPLE1, TUPLE2

Page No : 11 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
3. Display the 4th Item from the TUPLE2
4. Display the 4th Item from TUPLE2 using Negative Indexin g
5. Check whether the element 3.2 exist in TUPLE1
6. Convert the List1 = [1,2,3,4,5,6] to a Tuple
7. Unpack the TUPLE3 = 4,8,3 into Several variables
8. Count the frequency of the Item “o” from the TUPLE2
9. Display the length of the TUPLE2
10. Reverse the TUPLE2

'''Create a tuple named as TUPLE1 with the following items in the tuple
a. TUPLE1 = (‘tupleexample', False, 3.2, 1)
b. TUPLE2 = tuplex = ("p", "y", "t", "h", "o", "n", "c", "o",“d”,"e") '''

TUPLE1 = ("tupleexample", False, 3.2, 1)


TUPLE2 = tuplex = ("p", "y", "t", "h", "o", "n", "c", "o","d","e")

'''Display the TUPLE1, TUPLE2'''


print(TUPLE1)
print(TUPLE2)

#Display the 4th Item from the TUPLE2


print(TUPLE2[4])

#Display the 4th Item from TUPLE2 using Negative Indexing


print(TUPLE2[-4])

#Check whether the element 3.2 exist in TUPLE1


print(3.2 in TUPLE1)

#Convert the List1 = [1,2,3,4,5,6] to a Tuple


List1 =[1,2,3,4,5,6]
tuplex = tuple(List1)

print(tuplex)

#Unpack the TUPLE3 = 4,8,3 into Several variables


TUPLE3 = 4,8,3
n1,n2,n3 = TUPLE3
print(n1,n2,n3)

#Count the frequency of the Item “o” from the TUPLE2


print(TUPLE2.count("o"))

Page No : 12 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
#Display the length of the TUPLE2
print(len(TUPLE2))

#Reverse the TUPLE2


y = reversed(TUPLE2)
print(y)
T = tuple(y)
print(T)

Output No : 8

('tupleexample', False, 3.2, 1)


('p', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'd', 'e')
o
c
True
(1, 2, 3, 4, 5, 6)
483
2
10
<reversed object at 0x01C42B10>
('e', 'd', 'o', 'c', 'n', 'o', 'h', 't', 'y', 'p')

Program No : 9
Write a program in python to add and remove and item from tuple.

tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#direct addiotn of value into a tuple through append or insert is not possible
# no direct methods of insert or append.
#tuplex.append(100)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an element and it will create
a new tuple
tuplex = tuplex + (9,)
print(tuplex)
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[5:]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to add items in list
listx.append(30)

Page No : 13 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
tuplex = tuple(listx)
print(tuplex)

# to remove an item from the List


# convert a tuple to a list and remove item
listx = list(tuplex)
# to remove an item from list
listx.remove(1)
print(listx)
# converting back to Tuple
tuplex = tuple(listx)
print(tuplex)

Output No : 9

(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 1, 9, 30)
[4, 6, 2, 8, 3, 15, 20, 25, 9, 30]
(4, 6, 2, 8, 3, 15, 20, 25, 9, 30)

Demonstrate the concept of Slicing


Program No : 10

#Demonstrate the concept of Slicing


#create a tuple
tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
#used tuple[start:stop] the start index is inclusive and the stop index
slice1 = tuplex[3:5]
#is exclusive
print(slice1)
#if the start index isn't defined, is taken from the beg inning of the tuple
slice1 = tuplex[:6]
print(slice1)
#if the end index isn't defined, is taken until the end of the tuple
slice1 = tuplex[5:]
print(slice1)
#if neither is defined, returns the full tuple
slice1 = tuplex[:]
print(slice1)
#The indexes can be defined with negative values
slice1 = tuplex[-8:-4]

Page No : 14 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print(slice1)
#create another tuple
tuplex = tuple("HELLO WORLD")
print(tuplex)
#step specify an increment between the elements to cut of the tuple
#tuple[start:stop:step]
slice1 = tuplex[2:9:2]
print(slice1)
#returns a tuple with a jump every 3 items
slice1 = tuplex[::4]
print(slice1)
#when step is negative the jump is made back
slice1 = tuplex[9:2:-4]
print(slice1)

Output No : 10

(5, 4)
(2, 4, 3, 5, 4, 6)
(6, 7, 8, 6, 1)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
(3, 5, 4, 6)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
('L', 'O', 'W', 'R')
('H', 'O', 'R')
('L', ' ')

DICTIONARIES
 Dictionary is an unordered set of key and value pair.
 It is a container that contains data, enclosed within curly braces.
 The pair i.e., key and value is known as item. The key passed in the item must
be unique.
 The key and the value is separated by a colon(:). This pair is known as item.
 Items are separated from each other by a comma(,).
 Different items are enclosed within a curly brace a nd this forms Dictionary.
Create a Dictionary
data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print (data)

 Dictionary is mutable i.e., value can be updated.


 Key must be unique and immutable. Value is accessed by key. Value can be
updated while key cannot be changed.

Page No : 15 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
 Dictionary is known as Associative array since the Key works as Index and
they are decided by the user.
Python Dictionary Example
1. plant={}
2. plant[1]='Ravi'
3. plant[2]='Manoj'
4. plant['name']='Hari'
5. plant[4]='Om'
6. print plant[2]
7. print plant['name']
8. print plant[1]
9. print plant
Output:
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name': 'Hari'}

Accessing Dictionary Values


Since Index is not defined, a Dictionary values can be accessed by their keys only. It
means, to access dictionary elements key has to be passed, associated to the value.

Python Accessing Dictionary Element Syntax


1. <dictionary_name>[key]
2. </dictionary_name>

Accessing Elements Example


data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
print ("Id of 1st employer is",data1['Id'] )
print ("Id of 2nd employer is",data2['Id'] )
print ("Name of 1st employer:",data1['Name'] )
print ("Profession of 2nd employer:",data2['Profession'] )
Output:
>>>
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer is Trainer

Updating Python Dictionary Elements


The item i.e., key-value pair can be updated. Updating means new item can be added.
The values can be modified.

Page No : 16 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
data1['Profession']='Manager'
data2['Salary']=20000
data1['Salary']=15000
print (data1)
print (data2)
Output:
{'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name': 'Suresh'}
{'Salary': 20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}

Deleting Python Dictionary Elements Example


del statement is used for performing deletion operation.
An item can be deleted from a dictionary using the key only.
Delete Syntax
1. del <dictionary_name>[key]
2. </dictionary_name>

Whole of the dictionary can also be deleted using the del statement.
Example
data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102]
print data
del data
print data #will show an error since dictionary is deleted.
Output:
{100: 'Ram', 101: 'Suraj'}

Traceback (most recent call last):


File "C:/Python27/dict.py", line 5, in
print data
NameError: name 'data' is not defined

Python Dictionary Functions and Methods


Functions Description Code Output
data1={'Id':100, 3
'Name':'Suresh', 3
It returns number of 'Profession':'Developer'}
len(dictionary)
items in a dictionary. data2={'Id':101,
'Name':'Ramesh',
'Profession':'Trainer'}

Page No : 17 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print(len(data1))
print(len(data2))
dict = {'Name': 'Zara', 'Age': Equivalent String :
It gives the string
7}; {'Age': 7, 'Name':
str(dictionary) representation of a
print ("Equivalent 'Zara'}
dictionary
String : %s" % str (dict))
dict = {'Name': 'Zara', 'Age': Variable Type :
Return the type of 7}; <class 'dict'>
type(dictionary)
the variable print ("Variable Type : %s" %
type (dict)
Python Dictionary Methods
Methods Description Code Output
It returns all data1={100:'Ram', 101:'Suraj', dict_keys([100,
the keys 102:'Alok'} 101, 102])
keys()
element of a print(data1.keys())
dictionary.
It returns all data1={100:'Ram', 101:'Suraj', dict_values(['R
the values 102:'Alok'} am', 'Suraj',
values()
element of a print(data1.values()) 'Alok'])
dictionary.
It returns all data1={100:'Ram', 101:'Suraj', dict_items([(10
the 102:'Alok'} 0, 'Ram'), (101,
items() items(key- print(data1.items()) 'Suraj'), (102,
value pair) of 'Alok')])
a dictionary.
data1={100:'Ram', 101:'Suraj', {100: 'Ram',
It is used to 102:'Alok'} 101: 'Suraj',
add items of data2={103:'Sanjay'} 102: 'Alok',
update(dictionary2) dictionary2 data1.update(data2) 103: 'Sanjay'}
to first print (data1 ) {103: 'Sanjay'}
dictionary. print (data2) >>>

It is used to data1={100:'Ram', 101:'Suraj', {100: 'Ram',


remove all 102:'Alok'} 101: 'Suraj',
items of a print (data1) 102: 'Alok'}
clear() dictionary. It data1.clear() {}
returns an print (data1)
empty
dictionary.
fromkeys(sequence,val It is used to sequence=('Id' , 'Number' , {'Id': None,

Page No : 18 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
ue1)/ create a new 'Email') 'Number':
fromkeys(sequence) dictionary data={} None, 'Email':
from the data1={} None}
sequence data=data.fromkeys(sequence) {'Id': 100,
where print (data) 'Number': 100,
sequence data1=data1.fromkeys(sequen 'Email': 100}
elements ce,100)
forms the print (data1 )
key and all
keys share
the
values ?value
1?. In case
value1 is not
give, it set
the values of
keys to be
none.
data={'Id':100 , {'Id': 100,
It returns an
'Name':'Aakash' , 'Age':23} 'Name':
copy() ordered copy
data1=data.copy() 'Aakash', 'Age':
of the data.
print (data1) 23}
It returns the data={'Id':100 , 23
value of the 'Name':'Aakash' , 'Age':23} None
given key. If print (data.get('Age') )
get(key)
key is not print (data.get('Email'))
present it
returns none.

Program No : 11
Write a Python program to concatenate following dictionaries to create a new
one.

dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)

Output No : 11

Page No : 19 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Program No : 12
Write a Python program to sort (ascending and descending) a dictionary by
value.
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=T rue)
print('Dictionary in descending order by value : ',sorted_d)

Output No : 12

Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}


Dictionary in ascending order by value : [(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]
Dictionary in descending order by value : [(4, 3), (3, 4), (2, 1), (1, 2), (0, 0)]

STRING MANIPULATION

 String is a sequence of Unicode characters enclosed within single or double


quotes
 Python does not support a character type; these are treated as strings of length
one, thus also considered a substring.
 To access substrings, use the square brackets for slicing along with the index
or indices to obtain your substring.
 String pythons are immutable.(error : It does not support assignment)
o a = 'Geeks'
o print a # output is displayed
o a[2] = 'E'
o print a # causes error
 Strings in Pythons can be appended
o a = 'Geeks'
o print a # output is displayed
o a = a + 'for'a
o print a # works fine
 Concatenation of strings are created using + operator

String Creation
Strings can be created by enclosing characters inside a single quote or double quotes

Example

Page No : 20 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

Accessing Strings:
 In Python, Strings are stored as individual characters in a contiguous memory
location.
 The benefit of using String is that it can be accessed from both the directions
in forward and backward.
 Both forward as well as backward indexing are provided using Strings in
Python.
o Forward indexing starts with 0,1,2,3,....
o Backward indexing starts with -1,-2,-3,-4,....

Printing of single quote or double quote on screen


It can be done in the following two ways
 First one is to use escape character to display the additional quote.
 The second way is by using mix quote, i.e., when we wan t to print single
quote then using double quotes as delimiters and vice -versa.

\newline Backslash and newline ignored


\\ Backslash
\' Single quote
\" Double quote

Program No : 13
print( "Hi Mr Ram.")
# use of escape sequence
print ("He said, \"Welcome to the Show\"")
print ('Hey so happy to be here')
# use of mix quotes

Page No : 21 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print ('Getting Excited, "Loving it"' )

Output No : 13

Hi Mr Ram.
He said, "Welcome to the Show"
Hey so happy to be here
Getting Excited, "Loving it"

Program No : 14
Simple program to retrieve String in reverse as well as normal form.

name="MCA"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print (name[i],"\t",name[n])
i= i+1

Output No : 14
C:/Users/MCA/AppData/Local/Programs/Python/sample programs/str1.py
M A
C C
A M

Strings Operators
There are basically 3 types of Operators supported by String:
1. Basic Operators.
2. Membership Operators.
3. Relational Operators.
https://py3.codeskulptor.org/#user305_tw0W4ofIHP_0.py

Basic Operators:
There are two types of basic operators in String. They are "+" and
"*".
String Concatenation Operator :(+)
The concatenation operator (+) concatenate two Strings and forms a new String

print ("MCA" + "DEPARTMENT")


print('mca'+'department')
print (1+3)
print(10.4+11.5)
print("a"+1)

Page No : 22 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
RESTART: C:/Users/MCA/AppData/Local/Programs/P ython/sample
programs/str1.py
MCADEPARTMENT
mcadepartment
4
21.9
Traceback (most recent call last):
File "C:/Users/MCA/AppData/Local/Programs/Python/sample programs/str1.py",
line 5, in <module>
print("a"+1)
TypeError: must be str, not int

Replication Operator: (*)


 Replication operator uses two parameter for operation. One is the integer
value and the other one is the String.
 The Replication operator is used to repeat a string number of times. The string
will be repeated the number of times which is given by the integer value.
 Replication operator can be used in any way i.e., int * string or string * int.
Both the parameters passed cannot be of same type.
o print(5 * "MCA")
o print ("MCA" * 5)

Membership Operators
 Membership Operators are already discussed in the Operators section. Let see
with context of String.
 There are two types of Membership operators:
o in:"in" operator return true if a character or the entire substring is
present in the specified string, otherwise false.
o not in:"not in" operator return true if a character or entire substring
does not exist in the specified string, otherwise false.

Program No : 15

str1="javatpoint"
str2='sssit'
str3="seomount"
str4='java'
st5="it"
str6="seo"
print(str4 in str1)
print(st5 in str2)
print(str6 in str3)
print(str4 not in str1)

Page No : 23 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print(str1 not in str4)

Output No : 15

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/str1.py
True
True
True
False
True

Relational Operators:
All the comparison operators i.e., (<,><=,>=,==,!=,<>) are also applicable to strings.
The Strings are compared based on the ASCII value or Unicode(i.e., dictionary
Order).
Eg:
>>> "RAJAT"=="RAJAT"
True
>>> "afsha">='Afsha'
True
>>> "Z"<>"z"
True

Slice Notation:
String slice can be defined as substring which is the part of string. Therefore further
substring can be obtained from a string.
There can be many forms to slice a string. As string can be accessed or indexed from
both the direction and hence string can also be sliced from both the direction that is
left and right.
Syntax:
<string_name>[startIndex:endIndex:Stepvalue],
<string_name>[:endIndex],
<string_name>[startIndex:]
Program No : 16

str="Nikhil"
str[0:6]
print(str[0:3])
print(str[2:5])
print(str[:6])

Page No : 24 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print(str[3:])

Output No : 16
Nik
khi
Nikhil
Hil

How to change or delete a string?

Strings are immutable.


This means that elements of a string cannot be changed once they have been
assigned.
We can simply reassign different strings to the same name.

a="raja"
a="ram"
print(a)
del a
print(a)

Line 48: NameError: name 'a' is not defined

Python String Formatting

The format() Method for Formatting Strings.


The format() method that is available with the string object is very versatile and
powerful in formatting strings. Format strings contain curly braces {} as
placeholders or replacement fields which get replaced.

Strings and Numbers cannot be combined

TypeError: cannot concatenate 'str' and 'int' objects

But we can combine strings and numbers by using the format() method!

Page No : 25 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

O/P

I want 3 pieces of item 567 for 49.95 dollars.


You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

O/P

I want to pay 49.95 dollars for 3 pieces of item 567.

Page No : 26 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

String Functions and Methods:


There are many predefined or built in functions in String. They are as follows:
It capitalizes the first character of 'abc'.capitalize() Abc
capitalize()
the String.
msg = "MISSISIPPI"; 3
Counts number of times substring substr1 = "I"; 2
count(string,begin,end) occurs in a String between begin print (msg.count(substr1, 4, 16))
and end index. substr2 = "P";
print (msg.count(substr2))
string1="Welcome to SSSIT"; True
substring1="SSSIT"; False
substring2="to"; False
substring3="of"; False
Returns a Boolean value if the
print (string1.endswith(substring1));
endswith(suffix ,begin=0,end=n) string terminates with given suffix
print
between begin and end.
(string1.endswith(substring2,2,16));
print
(string1.endswith(substring3,2,19));
print (string1.endswith(substring3));
str="Welcome to SSSIT"; 3
It returns the index value of the substr1="come"; 8
string where substring is found substr2="to"; 3
find(substring ,beginIndex, endIndex) between begin index and end print (str.find(substr1) ) ; -1
index. If find option fails it result print (str.find(substr2));
in -1 print (str.find(substr1,3,10));
print (str.find(substr2,15));

Page No : 27 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
str="Welcome to SSSIT"; 3
substr1="come"; 8
substr2="to"; 3
print (str.index(substr1) ) ; Traceback (most recent
print (str.index(substr2)); call last):
print (str.index(substr1,3,10)); File
print (str.index(substr2,15)); "C:/Users/Nirmalaa/Ap
Same as find() except it raises an
index(substring, beginIndex, pData/Local/Programs/
exception if string is not found. If
endIndex) Python/Python36-
index option fails it raises an error
32/sample
programs/string1.py",
line 7, in <module>
print
(str.index(substr2,12));
ValueError: substring
not found
It returns True if characters in the str="Welcome to sssit"; False
string are alphanumeric i.e., print (str.isalnum()); True
isalnum() alphabets or numbers and there is str1="Python47";
at least 1 character. Otherwise it print (str1.isalnum());
returns False.
string1="HelloPython"; # Even True
It returns True when all the
space is not allowed False
characters are alphabets and there
isalpha() print (string1.isalpha());
is at least one character, otherwise
string2="This is Python2.7.4"
False.
print (string2.isalpha())
isdigit() It returns True if all the characters string1="HelloPython"; False

Page No : 28 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
are digit and there is at least one print (string1.isdigit()) True
character, otherwise False. string2="98564738"
print (string2.isdigit())
string1="Hello Python"; False
It returns True if the characters of print(string1.islower()) True
islower() a string are in lower case, string2="welcome to "
otherwise False. print (string2.islower())

string1="Hello Python"; False


It returns False if characters of a print string1.isupper(); True
isupper() string are in Upper case, otherwise string2="WELCOME TO"
False. print string2.isupper();

string1=" "; True


print (string1.isspace()) False
It returns True if the characters of
string2="WELCOME TO WORLD
isspace() a string are whitespace, otherwise
OF PYT"
false.
print (string2.isspace())

string1=" "; 4
print (len(string1)); 16
len(string) len() returns the length of a string. string2="WELCOME TO SSSIT"
print (len(string2));

string1="Hello Python"; hello python


Converts all the characters of a
lower() print (string1.lower()) welcome to sssit
string to Lower case.
string2="WELCOME TO SSSIT"

Page No : 29 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print (string2.lower());

string1="Hello Python"; HELLO PYTHON


Converts all the characters of a
upper() print (string1.upper()); WELCOME TO SSSIT
string to Upper Case.

string1="Hello Python"; True


Returns a Boolean value if the print string1.startswith('Hello'); True
startswith(str ,begin=0,end=n) string starts with given str string2="welcome to SSSIT"
between begin and end. print string2.startswith('come',3,7);

string1="Hello Python"; hELLOpYTHON


print (string1.swapcase()); WELCOME TO sssit
Inverts case of all characters in a
swapcase() string2="welcome to SSSIT"
string.
print (string2.swapcase());

string1=" Hello Python"; Hello Python


Remove all leading whitespace of print (string1.lstrip()); welcome to world to
a string. It can also be used to string2="@@@@@@@@welcome SSSIT
lstrip()
remove particular character from to SSSIT"
leading. print (string2.lstrip('@'));

string1=" Hello Python "; Hello Python


Remove all trailing whitespace of
print (string1.rstrip()); @welcome to SSSIT
a string. It can also be used to
rstrip() string2="@welcome to SSSIT!!!"
remove particular character from
print (string2.rstrip('!'));
trailing.

Page No : 30 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Remove all trailing & leading string1=" Hello Python "; Hello Python
whitespace of a string. It can also print (string1.strip()); @welcome to SSSIT
strip()
be used to remove particular
character from trailing.

Page No : 31 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

The constants defined in this module are:


string.ascii_letters
The concatenation of the ascii_lowercase and ascii_uppercase constants
described below. This value is not locale-dependent.
string.ascii_lowercase
The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale -
dependent and will not change.
string.ascii_uppercase
The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is
not locale-dependent and will not change.
string.digits
The string '0123456789'.
string.hexdigits
The string '0123456789abcdefABCDEF'.
string.octdigits
The string '01234567'.
string.punctuation
String of ASCII characters which are considered punctuation characters in the
C locale.
string.printable
String of ASCII characters which are considered printable. This is a
combination of digits, ascii_letters, punctuation, and whitespace.
string.whitespace
A string containing all ASCII characters that are considered whitespace. This
includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

ERRORS AND EXCEPTIONS

An exception is an unexpected error or abnormal condition that happens during the


program execution. The exception needs to be handled to avoid the program getting
crashed.

Python provides two very important features to handle any unexpected error in
Python programs.
 Exception Handling
 Assertions

Common Exceptions
 ZeroDivisionError: Occurs when a number is divided by zero .
 NameError: It occurs when a name is not found. It may be local or global.
 IndentationError: If incorrect indentation is given.
 IOError: It occurs when Input Output operation fails.

Page No : 32 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

 EOFError: It occurs when end of the file is reached and yet operations ar e
being performed.

Exception Handling:
The suspicious code can be handled by using the try block. Enclose the code which
raises an exception inside the try block. The try block is followed except statement.
It is then further followed by statements which are executed during exception and in
case if exception does not occur.
Syntax:

try:
malicious code
except Exception1:
execute code
except Exception2:
execute code
....
....
except ExceptionN:
execute code
else:
In case of no exception, execute the else block code.

try:
a=10/0
print (a)
except ArithmeticError:
print ("This statement is raising an exception" )
else:
print ("Welcome" )

This statement is raising an exception

Explanation:
1. The malicious code (code having exception) is enclosed in the try block.
2. Try block is followed by except statement. There can be multiple except
statement with a single try block.
3. Except statement specifies the exception which occurred. In case that
exception is occurred, the corresponding statement will be executed.
4. At last an else statement can be provided. It is executed when no exception is
occurred.

Python Exception(Except with no Exception) Example

Page No : 33 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Except statement can also be used without specifying Exception.


Syntax:
try:
code
except:
code to be executed in case exception occurs.
else:
code to be executed in case exception does not occur.

try:
a=10/0;
except:
print ("Arithmetic Exception" )
else:
print ("Successfully Done" )

Arithmetic Exception

while True:
try:
n = int(input("Please enter an integer: "))
break
except ValueError:
print("No valid integer! Please try again ...")
print ("Great, you successfully entered an integer!")

Please enter an integer: a


No valid integer! Please try again ...
Please enter an integer: s
No valid integer! Please try again ...
Please enter an integer: 12
Great, you successfully entered an integer!

List of Standard Exceptions

Sr.No. Exception Name & Description


Exception
1
Base class for all exceptions
StopIteration
2
Raised when the next() method of an iterator does not point to any object.
SystemExit
3
Raised by the sys.exit() function.

Page No : 34 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

StandardError
4
Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError
5
Base class for all errors that occur for numeric calculation.
OverflowError
6
Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError
7
Raised when a floating point calculation fails.
ZeroDivisionError
8
Raised when division or modulo by zero takes place for all numeric types.
AssertionError
9
Raised in case of failure of the Assert statement.
AttributeError
10
Raised in case of failure of attribute reference or assignment.
EOFError
11 Raised when there is no input from either the raw_input() or input() function
and the end of file is reached.
ImportError
12
Raised when an import statement fails.
KeyboardInterrupt
13 Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
LookupError
14
Base class for all lookup errors.
IndexError
15
Raised when an index is not found in a sequence.
KeyError
16
Raised when the specified key is not found in the dictionar y.
NameError
17
Raised when an identifier is not found in the local or global namespace.
UnboundLocalError
18 Raised when trying to access a local variable in a function or method but no
value has been assigned to it.
EnvironmentError
19
Base class for all exceptions that occur outside the Python environment.
IOError
20 Raised when an input/ output operation fails, such as the print statement or
the open() function when trying to open a file that does not exist.
21 IOError

Page No : 35 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Raised for operating system-related errors.


SyntaxError
22
Raised when there is an error in Python syntax.
IndentationError
23
Raised when indentation is not specified properly.
SystemError
24 Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.
SystemExit
25 Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.
TypeError
26 Raised when an operation or function is attempted that is invalid for the
specified data type.
ValueError
27 Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
RuntimeError
28
Raised when a generated error does not fall into any category.
NotImplementedError
29 Raised when an abstract method that needs to be implemented in an inherited
class is not actually implemented.

Finally Block:
In case if there is any code which the user want to be executed, whether exception
occurs or not then that code can be placed inside the finally block. Finally block will
always be executed irrespective of the exception.
try:
a=10/5
print (a)
except ArithmeticError:
print ("This statement is raising an exception" )
finally:
print (" final block executed " )

2.0
final block executed

Raising Exception:
The raise statement allows the programmer to force a specific exception to occur.

Page No : 36 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

The sole argument in raise indicates the exception to be raised. This must be either
an exception instance or an exception class.

def enterage(age):
if age < 0:
raise ValueError("Only positive integers are allowed")

if age % 2 == 0:
print("age is even")
else:
print("age is odd")

try:
num = int(input("Enter your age: "))
enterage(num)
except:
print("something is wrong")

Enter your age: 12


age is even
>>>
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/raise.py
Enter your age: -4
Only positive integers are allowed
>>>
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/raise.py
Enter your age: asd
Only positive integers are allowed
>>>
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/raise.py
Enter your age:
Only positive integers are allowed
>>>
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/raise.py
Enter your age: 11
age is odd

10
An exception occurred
Hello

Page No : 37 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Write a program to get 2 numbers and perform the division operation and perform
exceptional handling

try:
num1, num2 = eval(input("Enter two numbers, separated by a comma : "))
result = num1 / num2
print("Result is", result)

except ZeroDivisionError:
print("Division by zero is error !!")

except SyntaxError:
print("Comma is missing. Enter numbers separated by comma like this 1, 2")

except:
print("Wrong input")

else:
print("No exceptions")

finally:
print("This will execute no matter what")

Enter two numbers, separated by a comma : 12 45


Comma is missing. Enter numbers separated by comma like this 1, 2
This will execute no matter what
>>>
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/excep1.py
Enter two numbers, separated by a comma : 12,6
Result is 2.0
No exceptions
This will execute no matter what
>>>
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/excep1.py
Enter two numbers, separated by a comma : 12,0
Division by zero is error !!
This will execute no matter what

ASSERTIONS
Assertions are Boolean expressions used for expressing and validating the
correctness of modules, classes, sub programs

Page No : 38 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

 Assertions are simply boolean expressions that checks if the conditions return
true or not. If it is true, the program does nothing and moves to the next line
of code. However, if it's false, the program stops and throws an error.
 It is also a debugging tool as it brings the program on halt as soon as any error
is occurred
 Assertions are the condition or boolean expression which are always supposed
to be true in the code.
 assert statement takes an expression and optional message.
 assert statement is used to check types, values of argument and the output of
the function.

Syntax for using Assert in Pyhton:


assert <condition>
assert <condition>,<error message>

In Python we can use assert statement in two ways as mentioned above.


1. assert statement has a condition and if the condition is not satisfie d the
program will stop and give AssertionError.
2. assert statement can also have a condition and a optional error message. If the
condition is not satisfied assert stops the program and gives AssertionError
along with the error message.

Simple program to check whether the entered mark value is valid number, (ie) it
should be greater than zero. If greater than zero assert statement will be
skipped else assertion error will be generated

Using assert without Error Message

n = int(input("Enter a mark value : "))


assert(n > 0)
print(" The Valid Mark entered is ",n)

Page No : 39 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/assert2.py
Enter a mark value : -12
Traceback (most recent call last):
File "C:/Users/MCA/AppData/Local/Programs/Python/sample programs/assert2.py",
line 2, in <module>
assert(n > 0)
AssertionError
>>>
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/assert2.py
Enter a mark value : 67
The Valid Mark entered is 67

Using assert with error message

n = int(input("Enter a mark value : "))


assert(n > 0)," Mark cannot be Negative"
print(" The Valid Mark entered is ",n)

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/assert2.py
Enter a mark value : -21
Traceback (most recent call last):
File "C:/Users/MCA/AppData/Local/Programs/Python/sample programs/assert2.py",
line 2, in <module>
assert(n > 0)," Mark cannot be Negative"
AssertionError: Mark cannot be Negative

Write a program using assertion to check whether the sum of the given marks is not
equal to zero

def avg(marks):
assert (sum(marks) != 0),"Total Marks cannot be Empty"
return sum(marks)/len(marks)

mark1=[]
n = int(input("Enter the number of Subjects "))
for i in range(0,n):
item = int(input("Enter Elements for List :"))
mark1.append(item)

print("Average of mark1:",avg(mark1))

Page No : 40 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/assert1.py
Enter the number of Subjects 3
Enter Elements for List :0
Enter Elements for List :0
Enter Elements for List :0
[0, 0, 0]
Traceback (most recent call last):
File "C:/Users/MCA/AppData/Local/Programs/Python/sample programs/assert1.py",
line 14, in <module>
print("Average of mark1:",avg(mark1))
File "C:/Users/MCA/AppData/Local/Programs/Python/sample programs/assert1.py",
line 3, in avg
assert (sum(marks) != 0),"Total Marks cannot be Empty"
AssertionError: Total Marks cannot be Empty
>>>
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/assert1.py
Enter the number of Subjects 4
Enter Elements for List :56
Enter Elements for List :67
Enter Elements for List :78
Enter Elements for List :89
Average of mark1: 72.5

FUNCTIONS

A function is a block of organized, reusable code that is used to perform a task. A


function can return data as a result.

Advantages

 Functions provide better modularity.


 High degree of code reusability
 It helps to organize and manage the code

Defining a Function

 Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses.
 The first statement of a function can be an optional statement - the
documentation string of the function or docstring.

Page No : 41 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller.

Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)

Example of a Function
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

Calling a Function
The created function can be called from another function or directly from the Python
prompt.
>>>greet('Paul')
Program No : 17

To define a function and call it

def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

greet('Paul')

Output No : 17
Hello, Paul. Good morning! # calling from python program
>>>greet("paul") # calling from python prompt
Hello, paul. Good morning!
>>> greet("jaya")
Hello, jaya. Good morning!

Docstring
The first string after the function header is called the docst ring and is short for
documentation string. It is used to explain in brief, what a function does.

The documentation for the function can be enclosed within triple quotes

Page No : 42 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

""" aaaaaa """

Any information given within triple quotes can be retrieved using


>>> print(greet.__doc__)
This function greets to
the person passed in as
parameter

Python uses a mechanism, which is known as "Call-by-Object", sometimes also


called "Call by Object Reference" or "Call by Sharing".

Usage of id() in Function


Return the “identity” of an object. This is an integer (or long integer) which is
guaranteed to be unique and constant for this object during its lifetime. This is the
address of the object in memory.

Program No : 18

def ref_demo(x):
print ("x=",x," id=",id(x))
x=42
print ("x=",x," id=",id(x))

x=9
print(x,id(x))
ref_demo(x)
print(x,id(x))

Output No : 18

9 1641075888
x= 9 id= 1641075888
x= 42 id= 1641076416
9 1641075888

Program No : 19

def func1(list):
print (list)
list = list + [47,11]
print (list)

fib = [0,1,1,2,3,5,8]
func1(fib)

Page No : 43 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

print (fib)

Output No : 19

[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 47, 11]
[0, 1, 1, 2, 3, 5, 8]

Return Values

To Return a value from a function use the return statement:

Program No : 20
Program using function to find the sum of 2 numbers
def add_numbers(x,y):
sum = x + y
return sum

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))

Output No : 20

The sum is 11

Lambda Functions
 In python, the keyword lambda is used to create what is known as anonymous
functions. These are essentially functions with no pre-defined name. They are
good for constructing adaptable functions, and thus good for event handling.
 While normal functions are defined using the def keyword, in Python
anonymous functions are defined using the lambda keyword.
 Hence, anonymous functions are also called lambda functions.
 Lambda functions are used when we require a nameless function for a short
period of time.

Syntax of Lambda Function in python

lambda arguments: expression

Program No : 21

# Program to show the use of lambda functions

Page No : 44 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

double = lambda x: x * 2
print(double(5))

Output No : 21
10

Python Program That Returns Multiple Values From Function

Program No : 22

To return multiple values, we can use normal values or simply return a tuple.
def karlos():
return 1, 2, 3

a, b, c = karlos()

print (a)
print (b)
print (c)

Output No : 22

1
2
3

Program No : 23
Python Program For Calculates The Fibonacci Series By Using Function.

def fibo(n):
a=0
b=1
for i in range(0, n):
temp = a
a=b
b = temp + b
return a

# Show the first 13 Fibonacci numbers.


n = int(input("Enter the Value of N : "))
for c in range(0, n):
print(fibo(c)) #Function call

Output No : 23

Page No : 45 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Enter the Value of N : 10


0
1
1
2
3
5
8
13
21
34

Program No : 24

#Program make a simple calculator that can add, subtract, multiply and divide using
functions '''
# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user


choice = int(input("Enter choice(1/2/3/4):"))

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))

Page No : 46 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

if choice == 1:
print(num1,"+",num2,"=", add(num1,num2))

elif choice == 2:
print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == 3:
print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == 4:
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

Output No : 24

RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python 36-32/sample


programs/func.py
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):1
Enter first number: 12
Enter second number: 34
12 + 34 = 46
>>>
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/sample programs/func.py
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):2
Enter first number: 12
Enter second number: 3
12 - 3 = 9
>>>
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/sample programs/func.py
Select operation.

Page No : 47 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):3
Enter first number: 12
Enter second number: 3
12 * 3 = 36
>>>
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/sample programs/func.py
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):4
Enter first number: 12
Enter second number: 7
12 / 7 = 1.7142857142857142

SEARCHING, SORTING IN PYTHON


Write a program to implement the binary search algorithm and Bubble sort in Python .

Step by step example :

Page No : 48 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

def binary_search(item_list,item):
first = 0
last = len(item_list)-1

Page No : 49 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found

def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp

LL=[]
N = int(input("Enter the Number of elements in List :"))
for i in range(0,N):
item = int(input("Enter Elements for List :"))
LL.append(item)
item = int(input("Enter the Item to Search "))
print("\n UNSORTED ELEMENTS ARE ")
print(LL)

bubbleSort(LL)
print("\n BUBBLE SORTED ELEMENTS ARE ")
print(LL)

res = binary_search(LL, item)


if res == True:
print("Item is Present")
else:
print("Item is not Present")

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/binarysearch.py
Enter the Number of elements in List :10

Page No : 50 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Enter Elements for List :34


Enter Elements for List :56
Enter Elements for List :1
Enter Elements for List :89
Enter Elements for List :100
Enter Elements for List :11
Enter Elements for List :333
Enter Elements for List :41
Enter Elements for List :81
Enter Elements for List :43
Enter the Item to Search 100

UNSORTED ELEMENTS ARE


[34, 56, 1, 89, 100, 11, 333, 41, 81, 43]

BUBBLE SORTED ELEMENTS ARE


[1, 11, 34, 41, 43, 56, 81, 89, 100, 333]
Item is Present

HASH TABLES IN PYTHON


Write a program in python to perform creation ,search ,insert and delete
operation in Hash Tables.

# hash table creation

hash_table = [[] for i in range(10)]


print (hash_table)

#insert data into hash table


def insert(hash_table, key, value):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket[i] = ((key, value))
else:
bucket.append((key, value))

Page No : 51 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

insert(hash_table, 10, 'Nepal')


insert(hash_table, 25, 'USA')
insert(hash_table, 20, 'India')
insert(hash_table, 23, 'Srilanka')
print (hash_table)

def search(hash_table, key):


hash_key = hash(key) % len(hash_table)
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
return v

print (search(hash_table, 10)) # Output: Nepal


print (search(hash_table, 20)) # Output: India
print (search(hash_table, 30)) # Output: None

def delete(hash_table, key):


hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
del bucket[i]
print ('Key {} deleted'.format(key))
else:
print ('Key {} not found'.format(key))

delete(hash_table, 10)
print (hash_table)

[[], [], [], [], [], [], [], [], [], []]
[[(10, 'Nepal'), (20, 'India')], [], [], [(23, 'Srilanka')], [], [(25, 'USA')], [], [], [], []]
Nepal
India

Page No : 52 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

None
Key 10 deleted
[[(20, 'India')], [], [], [(23, 'Srilanka')], [], [(25, 'USA')], [], [], [], []]

MODULES

Modular programming refers to the process of breaking a large, unwieldy


programming task into separate, smaller, more manageable subtasks or modules.
Individual modules can then be cobbled together like building blocks to create a
larger application.

There are several advantages to modularizing code in a large application:


 Simplicity: Rather than focusing on the entire problem at hand, a module
typically focuses on one relatively small portion of the problem.
 Maintainability: Modules are typically designed so that they enforce logical
boundaries between different problem domains. If modules are written in a
way that minimizes interdependency, there is decreased likelihood t hat
modifications to a single module will have an impact on other parts of the
program
 Reusability: Functionality defined in a single module can be easily reused
(through an appropriately defined interface) by other parts of the application.
This eliminates the need to recreate duplicate code.
 Scoping: Modules typically define a separate namespace, which helps avoid
collisions between identifiers in different areas of a program.
 Functions, modules and packages are all constructs in Python that promote
code modularization

Creating a Module

To create a module just save the code in a file called mymodule.py

Example
Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module

The module can be used by using import statement. Create another file and save the
following code and execute it.
import mymodule
mymodule.greeting("John")

Page No : 53 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Note: When using a function from a module, use the


syntax: module_name.function_name

Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Import the module named mymodule, and access the person1 dictionary:
import mymodule

a = mymodule.person1["age"]
print(a)

36

Renaming a Module
An alias can be created when an module is imported by using the as keyword:
import mymodule as mx
a = mx.person1["age"]
print(a)

Built-in Modules
There are several built-in modules in Python, which can beimported as per theneed of
the user

Example
Import and use the platform module:

import platform
x = platform.system()
print(x)

windows

Using the dir() Function

Page No : 54 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:

import string
x = dir(string)
print(x)

RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -32/sample


programs/import.py
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__',
'__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase',
'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

Import From Module


Only part of module can be imported using the from keyword.

mymodule.py

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

person2 = "RAJA"

from mymodule import person1, person2

print (person1["age"])
print(person2)

Decorators are “wrappers”, which allow us to execute code before and after the
function they decorate without modifying the function itself.
The given code can be wrapped in a chain of decorators as follows.
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):

Page No : 55 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello()
OUTPUT
C:/Users/TutorialsPoint1/~.py
<b><i>hello world</i></b>

CLASSES AND OBJECTS

Python is an object-oriented programming language. Object-oriented programming


(OOP) focuses on creating reusable patterns of code, in contrast to procedural
programming, which focuses on explicit sequenced instructions.

Overview of OOP Terminology

 Class − A user-defined prototype for an object that defines a set of attributes


that characterize any object of the class. The attributes are data members
(class variables and instance variables) and methods, accessed via dot notation.
 Class variable − A variable that is shared by all instances of a class. Class
variables are defined within a class but outside any of the class's met hods.
Class variables are not used as frequently as instance variables are.
 Data member − A class variable or instance variable that holds data
associated with a class and its objects.
 Function overloading − The assignment of more than one behavior to a
particular function. The operation performed varies by the types of objects or
arguments involved.
 Instance variable − A variable that is defined inside a method and belongs
only to the current instance of a class.
 Inheritance − The transfer of the characteristics of a class to other classes
that are derived from it.
 Instance − An individual object of a certain class. An object obj that belongs
to a class Circle, for example, is an instance of the class Circle.
 Instantiation − The creation of an instance of a class.
 Method − A special kind of function that is defined in a class definition.
 Object − A unique instance of a data structure that's defined by its class. An
object comprises both data members (class variables and instance variables)
and methods.

Page No : 56 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

 Operator overloading − The assignment of more than one function to a


particular operator.

Creating Classes

The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows −

class ClassName:
'Optional class documentation string'
class_suite

 The class has a documentation string, which can be accessed via


ClassName.__doc__.
 The class_suite consists of all the component statements defining class
members, data attributes and functions.

class Employee:
'Common base class for all employees'
empCount = 0

The Constructor Method


The constructor method is used to initialize data. It is invoked as soon as an object of
a class is instantiated.
It is also known as the __init__ method, it will be the first definition of a class and
the syntax is:

Self Parameter

The self parameter is a reference to the class itself, and is used to access variables
that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be
the first parameter of any function in the class

class Rectangle():
def __init__(self1, l, w):
self1.len = l
self1.wid = w

def rectangle_area(self1):
return self1.len*self1.wid

newRectangle = Rectangle(12, 10)

Page No : 57 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

print(newRectangle.rectangle_area())

Modify Object Properties


Properties can be modified on objects like this:

class Rectangle():
def __init__(self1, l, w):
self1.len = l
self1.wid = w

def rectangle_area(self1):
return self1.len*self1.wid

newRectangle = Rectangle(12, 10)


newRectangle.len = 100
print(newRectangle.rectangle_area())

1000

Delete Object Properties


The properties on objects can be deleted by using the del keyword

class Rectangle():
def __init__(self1, l, w):
self1.len = l
self1.wid = w

def rectangle_area(self1):
return self1.len*self1.wid

newRectangle = Rectangle(12, 10)

del newRectangle.len

print(newRectangle.rectangle_area())

File "C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/rectclass.py", line 7, in rectangle_area
return self1.len*self1.wid
AttributeError: 'Rectangle' object has no attribute 'len'

Page No : 58 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Write a Python class named Rectangle constructed by a length and width and a
method which will compute the area of a rectangle.

class Rectangle():
def __init__(self, l, w):
self.len = l
self.wid = w

def rectangle_area(self):
return self.len*self.wid

newRectangle = Rectangle(12, 10)


res = newRectangle.rectangle_area()
print(res)

120

Delete Objects
The created objects itself can be deleted by using the del keyword:

class Rectangle():
def __init__(self1, l, w):
self1.len = l
self1.wid = w

def rectangle_area(self1):
return self1.len*self1.wid

newRectangle = Rectangle(12, 10)


del newRectangle
print(newRectangle.rectangle_area())

Traceback (most recent call last):


File "C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/rectclass.py", line 13, in <module>
print(newRectangle.rectangle_area())
NameError: name 'newRectangle' is not defined

def __init__(self, name, salary):


self.name = name
self.salary = salary
print(“ This is a Constructor “)
Employee.empCount += 1

Page No : 59 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

class Employee:
'Common base class for all employees'
empCount = 0
'''name = "nirmala"
salary = 10000'''

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount = Employee.empCount +
1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)

def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)

"This would create first object of Employee class"


emp1 = Employee("Raja",10000)
emp1.displayEmployee()
print ("Total Employee %d" % Employee.empCount)

Name : Raja , Salary: 10000


Total Employee 1

Create a Time class and initialize it with hours and minutes.


1. Make a method addTime which should take two time object and add them. E.g.- (2
hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min)
2. Make a method displayTime which should print the time.
3. Make a method DisplayMinute which should display the total minutes in the Time.
E.g.- (1 hr 2 min) should display 62 minute.

class Time():

def __init__(self, hours, mins):


self.hours = hours
self.mins = mins

def addTime(t1, t2):


t3 = Time(0,0)
t3.mins = t1.mins+t2.mins
t3.hours = t3.mins / 60
t3.mins = t3.mins%60

Page No : 60 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

t3.hours = int(t1.hours + t2.hours + t3.hours)


return t3

def displayTime(self):
print ("Time is",self.hours,"hours and",self.mins,"minutes.")

def displayMinute(self):
print ("Total Minutes ",(self.hours*60)+self.mins)

a = Time(2,32)
b = Time(1,30)
c = Time.addTime(a,b)
c.displayTime()
c.displayMinute()

Time is 4 hours and 2 minutes.


Total Minutes 242

Develop the concept of Stack Data structure with a Sample program


class Stack:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def push(self, data):


self.items.append(data)

def pop(self):
return self.items.pop()

def display(self):
for itm in self.items:
print(itm)

s = Stack()
while True:
print('push <value>')
print('pop')
print('quit')
print('display')

Page No : 61 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

do = input('What would you like to do? ').split()

operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation =='display':
s.display()
elif operation == 'pop':
if s.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'quit':
break

push <value>
pop
quit
display
What would you like to do? push 12
push <value>
pop
quit
display
What would you like to do? push 10
push <value>
pop
quit
display
What would you like to do? display
12
10
push <value>
pop
quit
display
What would you like to do? push 200
push <value>
pop
quit
display
What would you like to do? display
12

Page No : 62 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

10
200
push <value>
pop
quit
display
What would you like to do? pop
Popped value: 200
push <value>
pop
quit
display
What would you like to do? display
12
10
push <value>
pop
quit
display
What would you like to do? Quit

Develop the concept of Queue Data structure with a Sample program

class Queue:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def insert(self, data):


self.items.append(data)

def delete(self):
return self.items.pop(0)

def display(self):
print("\n Items in Queue are ....")
for itm in self.items:
print(itm)

s = Queue()
while True:

Page No : 63 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

print('1 - Insert')
print('2 - Delete')
print('3 - Display')
print('4 - Quit')
do = int(input('What would you like to do? [1/2/3/4] '))
if do == 1:
ele = int(input("\n Enter the Element to Insert : "))
s.insert(ele)
elif do ==3:
s.display()
elif do == 2:
if s.is_empty():
print('Queue is empty.')
else:
print('Deleted Value from Queue is : ', s.delete())
elif do == 4:
break
1 - Insert
2 - Delete
3 - Display
4 - Quit
What would you like to do? [1/2/3/4] 1

Enter the Element to Insert : 10


1 - Insert
2 - Delete
3 - Display
4 - Quit
What would you like to do? [1/2/3/4] 1

Enter the Element to Insert : 20


1 - Insert
2 - Delete
3 - Display
4 - Quit
What would you like to do? [1/2/3/4] 1

Enter the Element to Insert : 30


1 - Insert
2 - Delete
3 - Display
4 - Quit
What would you like to do? [1/2/3/4] 3

Page No : 64 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Items in Queue are ....


10
20
30
1 - Insert
2 - Delete
3 - Display
4 - Quit
What would you like to do? [1/2/3/4] 2
Deleted Value from Queue is : 10
1 - Insert
2 - Delete
3 - Display
4 - Quit
What would you like to do? [1/2/3/4] 3

Items in Queue are ....


20
30
1 - Insert
2 - Delete
3 - Display
4 - Quit
What would you like to do? [1/2/3/4] 4

REGULAR EXPRESSIONS

A regular expression is a special sequence of characters that helps to match or find


other strings or sets of strings, using a specialized syntax held in a pattern.
The module re provides full support for Perl-like regular expressions in Python. The
re module raises the exception re.error if an error occurs while compiling or using a
regular expression.

There are various characters, which would have special meaning when they are used
in regular expression. To avoid any confusion while dealing with regular
expressions, we would use Raw Strings as r'expression'.

The match Function


This function attempts to match RE pattern to string with optional flags.
Here is the syntax for this function −
re.match(pattern, string, flags=0)
Here is the description of the parameters −

Page No : 65 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Sr.No. Parameter & Description

1 pattern
This is the regular expression to be matched.

2 string
This is the string, which would be searched to match the pattern at t he
beginning of string.

3 flags
You can specify different flags using bitwise OR (|). These are
modifiers, which are listed in the table below.

The most common uses of regular expressions are:


 Search a string (search and match)
 Finding a string (findall)
 Break string into a sub strings (split)
 Replace part of a string (sub)

Various methods of Regular Expressions

The ‘re’ package provides multiple methods to perform queries on an input


string. Here are the most commonly used methods:

1. re.match()
2. re.search()
3. re.findall()
4. re.split()
5. re.sub()
6. re.compile()

re.match() <_sre.SRE_Match
import re object; span=(0, 2),
it searches for first occurrence of result = re.match(r'AV', 'AV match='AV'>
RE pattern within string with Analytics Vidhya AV')
optional flags. print(result)
If the search is successful,
search() returns a match object or
None otherwise.
To print the matching string import re <_sre.SRE_Match
group method is used. (It helps result = re.match(r'AV', 'AV object; span=(0, 2),
to return the matching string). Analytics Vidhya AV') match='AV'>
print(result) AV

Page No : 66 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

print(result.group(0))
If the pattern is not matching it import re None
results a None result = re.match(r'Analytics',
'AV Analytics Vidhya AV')
print(result)

There are methods like start() import re <_sre.SRE_Match


and end() to know the start and result = re.match(r'AV', 'AV object; span=(0, 2),
end position of matching pattern Analytics Vidhya AV') match='AV'>
in the string. print(result) 0
print(result.start()) 2
print(result.end())
re.search(pattern, string): import re <_sre.SRE_Match
It is similar to match() but it result = re.search(r'Analytics', object; span=(3, 12),
doesn’t restrict us to find 'AV Analytics match='Analytics'>
matches at the beginning of the AnalyticsVidhya AV') 3
string only. Unlike previous print(result) 12
method, here searching for print(result.start()) >>>
pattern ‘Analytics’ will return a print(result.end())
match.

it only returns the first


occurrence of the search pattern.

re.findall (pattern, string): import re ['AV', 'AV']


It helps to get a list of all result = re.findall(r'AV', 'AV
matching patterns. It has no Analytics AnalyticsVidhya
constraints of searching from AV')
start or end. If we will use print(result)
method findall to search ‘AV’ in
given string it will return both
occurrence of AV
re.split(pattern, string, import re ['Anal', 'tics']
[maxsplit=0]): result=re.split(r'y','Analytics')
This methods helps to print(result)
split string by the occurrences ['Analyt', 'csVidhya']
of given pattern. import re
result=re.split(r'i','Analytics
Vidhya',maxsplit=1)
print(result) ['Analyt', 'cs V', 'dhya']

import re
result=re.split(r'i','Analytics

Page No : 67 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON

Vidhya',maxsplit=2)
print(result)

Page No : 68 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON
Files – Input and Output – Errors and Exceptions – Functions – Modules – Classes and Objects – regular Expressions

Commonly Used Operators in Regular Expressions

['A', 'V', ' ', 'i', 's', ' ',


Extract each
Matches with 'l', 'a', 'r', 'g', 'e', 's',
character import re
any single 't', ' ', 'A', 'n', 'a', 'l',
Space is also result=re.findall(r'.','AV is largest Analytics
. character 'y', 't', 'i', 'c', 's', ' ', 'c',
treated as character community of India')
except 'o', 'm', 'm', 'u', 'n', 'i',
print (result)
newline ‘\n’. 't', 'y', ' ', 'o', 'f', ' ', 'I',
'n', 'd', 'i', 'a']
['A', 'V', 'i', 's', 'l', 'a',
'r', 'g', 'e', 's', 't', 'A',
Matches with Extract each
result=re.findall(r'\w','AV is largest Analytics 'n', 'a', 'l', 'y', 't', 'i',
a alphanumeric
\w community of India') 'c', 's', 'c', 'o', 'm', 'm',
alphanumeric character.
print (result) 'u', 'n', 'i', 't', 'y', 'o',
character Space is omitted
'f', 'I', 'n', 'd', 'i', 'a']

(upper case
Extract each non
W) matches result=re.findall(r'\W','AV is @ largest [' ', ' ', '@', ' ', ' ', ' ', '
alphanumeric
\W non Analytics community of $$ India') ', ' ', '$', '$', ' ']
character.
alphanumeric print (result)
character.
['AV', '', 'is', '',
0 or more
Extract each word result=re.findall(r'\w*','AV is largest Analytics 'largest', '',
occurrences
* Space is also community of India') 'Analytics', '',
of the pattern
included print (result) 'community', '', 'of', '',
to its left
'India', '']
1 or more import re ['AV', 'is', 'largest',
Extract each word
occurrences result=re.findall(r'\w+','AV is largest Analytics 'Analytics',
+ Space is not
of the pattern community of India') 'community', 'of',
included
to its left print (result) 'India']

Page No : 69 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON
Files – Input and Output – Errors and Exceptions – Functions – Modules – Classes and Objects – regular Expressions

Matches the Extract a single


result=re.findall(r'^\w+','AV is largest
^ beginning of word from the [AV]
Analytics community of India')
the line beginning
Matches the Extract single word
result=re.findall(r'\w+$','AV is largest
$ end of the from the End of the [India]
Analytics community of India')
Line Line
Return the first two ['AV', 'is', 'la', 'rg',
character of each result=re.findall(r'\w\w','AV is largest 'es', 'An', 'al', 'yt', 'ic',
word Analytics community of India') 'co', 'mm', 'un', 'it',
'of', 'In', 'di']
Extract
boundary
consecutive two
between
characters those
word and
available at start of result=re.findall(r'\b\w\w','AV is largest ['AV', 'is', 'la', 'An',
\b non-word
word Analytics community of India') 'co', 'of', 'In']
and /B is
boundary (using
opposite of
“\b“)
/b
Extract
consecutive two
characters those
available at end of result=re.findall(r'\w\w\b','AV is largest ['AV', 'is', 'st', 'cs',
word Analytics community of India') 'ty', 'of', 'ia']
boundary (using
“\b“)

result=re.findall(r'@\w+','[email protected],
Extract ['@gmail', '@test',
[email protected], [email protected],
all characters after '@analyticsvidhya',
[email protected]')
“@” '@rest']
print(result)

Page No : 70 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON
Files – Input and Output – Errors and Exceptions – Functions – Modules – Classes and Objects – regular Expressions

['@gmail.com',
result=re.findall(r'@\w+.\w+','[email protected],
'@test.in',
[email protected], [email protected],
'@analyticsvidhya.com',
[email protected]')
'@rest.biz']
print (result)

Return the domain


result=re.findall(r'@\w+.(\w+)','[email protected],
type of given ['com', 'in', 'com', 'biz']
[email protected], [email protected],
email-ids
[email protected]')
import re
result=re.findall(r'\d{2}-\d{2}-\d{4}','Amit 34-
['12-05-2007', '12-03-
Return date from 3456 coimbatore 12-05-2007 12-03-2008')
2008']
\d given string print (result)
['34-3456', '05-2007',
Matches with result=re.findall(r'\d{2}-\d{4}','Amit 34-3456
'03-2008']
digits [0-9] coimbatore 12-05-2007 12-03-2008')
and . print(result)
(upper case import re
D) matches result=re.findall(r'\D{2}-\D{2}-\D{4}','Amit-
/D ['it-$$-@@@@']
with non- $$-@@@@ 12-12-2017')
digits print (result)
['AV', 'is', 'argest',
import re
Matches any Return words starts 'Analytics',
result=re.findall(r'[aeiouAEIOU]\w+','AV is
[..] single with alphabets 'ommunity', 'of',
largest Analytics community of India')
character in a (using []) 'India']
print (result)
square bracket Use word boundary
import re
['AV', 'is', 'Analytics',
result=re.findall(r'\b[aeiouAEIOU]\w+','AV is
'of', 'India']
largest Analytics community of India')

Page No : 71 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – II – ADVANCED PYTHON
Files – Input and Output – Errors and Exceptions – Functions – Modules – Classes and Objects – regular Expressions

print (result)
[^..] matches
import re [' is', ' largest', '
any single
result=re.findall(r'\b[^aeiouAEIOU]\w+','AV is Analytics', '
[^..] character not
largest Analytics community of India') community', ' of', '
in square
print (result) India']
bracket
import re
result=re.findall(r'\b[^aeiouAEIOU ]\w+','AV is ['largest',
largest Analytics community of India') 'community']
print (result)

Page No : 72 Prepared by : M.Nirmala / AP / MCA / HICET

You might also like