PYTHON Unit 2
PYTHON Unit 2
-----------------------------------------------------------------------------------------------------------------
Files – Input and Output – Errors and Exceptions – Functions – Modules –
Classes and Objects – regular Expressions
Table of Contents
Program No : 1
-----------------------------------------------------------------------------------------------------------------
print(sum)
Output No : 1
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.
-----------------------------------------------------------------------------------------------------------------
% 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
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.
-----------------------------------------------------------------------------------------------------------------
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'];
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])
-----------------------------------------------------------------------------------------------------------------
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)
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']
-----------------------------------------------------------------------------------------------------------------
['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)
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
-----------------------------------------------------------------------------------------------------------------
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
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)
-----------------------------------------------------------------------------------------------------------------
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
Program No : 7
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.
-----------------------------------------------------------------------------------------------------------------
Creating a Tuple
A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).
-----------------------------------------------------------------------------------------------------------------
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)
#reverse print
print(a[::-1])
#reverse with slicing increment
print(a[::-2])
#using slice
a = [1, 2, 3, 4, 5]
-----------------------------------------------------------------------------------------------------------------
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
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
-----------------------------------------------------------------------------------------------------------------
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") '''
print(tuplex)
-----------------------------------------------------------------------------------------------------------------
#Display the length of the TUPLE2
print(len(TUPLE2))
Output No : 8
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)
-----------------------------------------------------------------------------------------------------------------
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)
-----------------------------------------------------------------------------------------------------------------
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 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'}
-----------------------------------------------------------------------------------------------------------------
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'}
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'}
-----------------------------------------------------------------------------------------------------------------
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) >>>
-----------------------------------------------------------------------------------------------------------------
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
-----------------------------------------------------------------------------------------------------------------
{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
STRING MANIPULATION
String Creation
Strings can be created by enclosing characters inside a single quote or double quotes
Example
-----------------------------------------------------------------------------------------------------------------
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,....
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
-----------------------------------------------------------------------------------------------------------------
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
-----------------------------------------------------------------------------------------------------------------
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
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)
-----------------------------------------------------------------------------------------------------------------
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])
-----------------------------------------------------------------------------------------------------------------
print(str[3:])
Output No : 16
Nik
khi
Nikhil
Hil
a="raja"
a="ram"
print(a)
del a
print(a)
But we can combine strings and numbers by using the format() method!
-----------------------------------------------------------------------------------------------------------------
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
O/P
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
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
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
-----------------------------------------------------------------------------------------------------------------
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=" "; 4
print (len(string1)); 16
len(string) len() returns the length of a string. string2="WELCOME TO SSSIT"
print (len(string2));
-----------------------------------------------------------------------------------------------------------------
print (string2.lower());
-----------------------------------------------------------------------------------------------------------------
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.
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.
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" )
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.
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!")
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
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.
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")
10
An exception occurred
Hello
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")
ASSERTIONS
Assertions are Boolean expressions used for expressing and validating the
correctness of modules, classes, sub programs
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.
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
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
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))
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
Advantages
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.
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
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
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)
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
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
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.
Program No : 21
double = lambda x: x * 2
print(double(5))
Output No : 21
10
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
Output No : 23
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
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
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
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
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
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)
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/binarysearch.py
Enter the Number of elements in List :10
delete(hash_table, 10)
print (hash_table)
[[], [], [], [], [], [], [], [], [], []]
[[(10, 'Nepal'), (20, 'India')], [], [], [(23, 'Srilanka')], [], [(25, 'USA')], [], [], [], []]
Nepal
India
None
Key 10 deleted
[[(20, 'India')], [], [], [(23, 'Srilanka')], [], [(25, 'USA')], [], [], [], []]
MODULES
Creating a Module
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")
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
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)
mymodule.py
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
person2 = "RAJA"
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):
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>
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
class Employee:
'Common base class for all employees'
empCount = 0
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
print(newRectangle.rectangle_area())
class Rectangle():
def __init__(self1, l, w):
self1.len = l
self1.wid = w
def rectangle_area(self1):
return self1.len*self1.wid
1000
class Rectangle():
def __init__(self1, l, w):
self1.len = l
self1.wid = w
def rectangle_area(self1):
return self1.len*self1.wid
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'
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
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
class Employee:
'Common base class for all employees'
empCount = 0
'''name = "nirmala"
salary = 10000'''
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
class Time():
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()
def is_empty(self):
return self.items == []
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')
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
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
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
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:
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
REGULAR EXPRESSIONS
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'.
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.
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
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)
import re
result=re.split(r'i','Analytics
Vidhya',maxsplit=2)
print(result)
(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']
result=re.findall(r'@\w+','[email protected],
Extract ['@gmail', '@test',
[email protected], [email protected],
all characters after '@analyticsvidhya',
[email protected]')
“@” '@rest']
print(result)
['@gmail.com',
result=re.findall(r'@\w+.\w+','[email protected],
'@test.in',
[email protected], [email protected],
'@analyticsvidhya.com',
[email protected]')
'@rest.biz']
print (result)
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)