Python Lab Manual Updated 2020-21
Python Lab Manual Updated 2020-21
Solution:
#####Output#####
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
HELLO WORLD!
hello world!
12
2) WAP to demonstrate Arithmatic,Comparision,Assignment,Bitwise
Operators
A) Arithmatic Operator
Solution:
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
#####Output#####
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
B) Comparison Operator
Solution:
a = 21
b = 10
c=0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"
#####Output#####
C) Assignment Operator
Solution:
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c =2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
#####Output#####
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
#####Output#####
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
3) WAP to demonstrate Percision Operators
Solution:
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
#####Output#####
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
4) WAP to demonstrate row input and input function to check given number
is prime or not
Solution:
def prime(n1,n2):
#n=int(input("enter a number:"))
for no in range(n1,n2):
for i in range(2,no):
if(no%i)==0:
break;
else:
print(no)
#####Output#####
Solution:
count=0
while(count<6):
count=count+1
print count
#####Output#####
123456
while True:
print("hello world")
#####Output#####
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
#####Output#####
20
5)D) WAP for for loop with else statement
Solution:
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")
#####Output#####
1
2
3
No Break
some_guy = 'Fred'
first_names = []
first_names.append(some_guy)
another_list_of_names = first_names
another_list_of_names.append('George')
some_guy = 'Bill'
#####Output#####
def foo(bar):
bar.append(42)
print(bar)
answer_list = []
foo(answer_list)
print(answer_list)
#####Output#####
[42]
[42]
sum=lambda arg1,arg2:arg1+arg2
print("Value of total:",sum(10,500))
output
Value of total: 510
12)WAP to calculate area of circle,triangle,rectangle
def area_circle(r):
pie=3.14
area=pie*r*r
return area
r=float(input("enter radius of circle:"))
print("Area of Circle is:",area_circle(r))
def ar_rec(l,b):
return l*b
def ar_triangle(b1,h):
return 0.5*b1*h
l=int(input("enter length:"))
b=int(input("enter breadth:"))
b1=int(input("enter base for traigle:"))
h=int(input("enter height for triangle:"))
print("Area of Rectangle is=",ar_rec(l,b))
print("Area of Triangle is=",ar_triangle(b1,h))
#####Output#####
enter radius of circle:12
Area of Circle is: 452.15999999999997
enter length:12
enter breadth:12
enter base for traigle:12
enter height for triangle:12
Area of Rectangle is= 144
Area of Triangle is= 72.0
7) WAP for String Built in functions
Solution:
str="welcome to jspm"
print(str.split())
str1="welcome to jspm mca department to get good \n job"
print(str1)
print(str1.splitlines())
str2="Nagesh"
print(str2.upper())
print(str2.isdigit())
print(str2.lower())
str3 = 'Hello Nagesh!'
print(str3)
print(str3[0])
print(str3[2:5])
print(str3[2:])
print(str3 * 2)
#####Output#####
def cap(str):
str=str.capitalize()
s=str[-1:]
str=str[:-1]+str[-1].upper()
return str
print (cap("enter string"("dipu"));
#####Output#####
DipU
9) Write a program to replace the last three characters of string with 'ing',if
having 'ing' in the string then replace by 'ly'.
Solution:
def add_string(str1):
length=len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 +='ly'
else:
str1 +='ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))
#####Output#####
ab,abc,strly
10) Write a program to perform list operations.
Solution:
odd = [2, 4, 6, 8]
odd[0] = 1
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5])
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list.index(8))
print(my_list.count(8))
my_list.sort()
print(my_list)
my_list.reverse(), 6, 4, 3, 1, 0]
print(my_list)
#####Output#####
1
2
[0, 1, 3, 4, 6, 8, 8]
['r','o','b','l','e','m']
#####Output#####
-1,1,-1
First list length : 3,Second list length : 2
Max value element : zara,Max value element : 700
min value element : 123,min value element : 200
List elements : [123, 'xyz', 'zara', 'abc']
13) Write a program for list-comprehension using for loop,if statement,nested
loop
solution:
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
#Nested loop
transposed = []
matrix = [[1, 2, 3, 4], [4, 5, 6, 8]]
for i in range(len(matrix[0])):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed)
number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)
#####Output#####
my_tuple = (1, 2, 3)
print(my_tuple)
print(my_tuple[0])
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[1:4])
del my_tuple
my_tuple
#####Output#####
(1, 2, 3)
1
't'
'e','r','m'
#####Output#####
#####Output#####
Jack
{'age': 27, 'name': 'Jack'}
{'address': 'Downtown', 'age': 27, 'name': 'Jack'}
16
The value of pi is 3.141592653589793
17) Write a program to create User defined package,subpackage mypack.
solution:
#untitledpack
#__init__.py
#add.py
def add(x,y):
sum = x + y
return sum
#sub.py
def sub(x,y):
sub = x - y
return sub
#multi.py
def multi(x,y):
multi = x * y
return multi
#div.py
def div(x,y):
div = x / y
return div
#test.py
import sys
sys.path.append('C:\\Users\\admin\\PycharmProjects')
import untitled1
print(untitled1.add(10, 20))
print(untitled1.sub(10, 20))
print(untitled1.multi(10, 20))
print(untitled1.div(10, 20))
print(untitled1.squareroot(16))
print(untitled1.fib(5))
#sub mypack
#fib.py
def fib(n):
a, b = 0, 1
print(a)
while b < n:
print(b)
a, b = b, a + b
#sqrt.py
import math
def squareroot(n):
return math.sqrt(n)
#####Output#####
30,-10,200,0.5,4.0,0,1,1,2,3
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print "Output of Read function is "
print file1.read()
#####Output#####
Hello
This is Delhi
This is Paris
This is London
19) Write a program Reading and Writing into Binary file.
Solution:
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
#read a file
def __init__(self, fileName):
self.file = open(fileName, 'rb')
21) Wrie a python code to diplay first m and last n lines from text file.
Solution:
1. Assertion
def kelvinToFahrenheit(Temperature):
assert(Temperature>=0),"colder than absolute zero"
return((Temperature-273)*1.8)+32
print(kelvinToFahrenheit(273))
print(kelvinToFahrenheit(505.73))
print(kelvinToFahrenheit(-4))
#####Output#####
32.0
450.91400000000004
Traceback (most recent call last):
File "D:\Harshada171816\exception.py", line 7, in <module>
print(kelvinToFahrenheit(-4))
File "D:\Harshada171816\exception.py", line 3, in kelvinToFahrenheit
assert(Temperature>=0),"colder than absolute zero"
AssertionError: colder than absolute zero
2. try-except:
try:
fh=open("textfile","w")
try:
fh.write("this is my test file for exception handling")
finally:
print("going to close the file")
fh.close()
except:
print("error cant find file or read data")
#####Output#####
23) Write a program to create user defined exceptino not prime if given
number is not prime else print the prime number
Solution:
class Error(Exception):
""" base class for exception """
pass
class NotPrimeNumber(Error):
"""raised when number is not prime"""
pass
n=int(input("enter a number:"))
for i in range(2,n):
try:
if n%i==0:
raise NotPrimeNumber
#else:
#print("number is prime")
#break
except NotPrimeNumber:
print("this number is not a prime number")
break
#####Output#####
enter a number:4
this number is not a prime number
24) Write a program to guess correct no that is 10 and throw user defined
exception Toosmallnumber if number is small and throw exception
Toolargenumber if entered number is large.
Solution:
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""RAised when input is too small"""
pass
class ValueTooLargeError(Error):
"""raised when input value is too large"""
pass
#our program
number=10
while True:
try:
i_num=int(input("enter a no:"))
if i_num<number:
raise ValueTooSmallError
elif i_num>number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("this value is too small,try again!!!")
print()
except ValueTooLargeError:
print("this value is too large,try again!!!")
print("congratulations! you guessed it correctly")
#####Output#####
enter a no:4
this value is too small,try again!!!
enter a no:12
this value is too large,try again!!!
enter a no:10
congratulations! you guessed it correctly
25) Write a program to demonstrate class and object to create employee class
Solution:
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
class Point:
def __init__(self,x=0,y=0):
self.x=x;
self.y=y;
def __del__(self):
class_name=self.__class__.__name__
print(class_name,"destroyed")
pt1=Point()
pt2=pt1
pt3=pt1
print(id(pt1),id(pt2),id(pt3))
del pt1
del pt2
del pt3
#####Output#####
#multiple inheritance
class person:
def __init__(self,personName,personAge):
self.name=personName
self.age=personAge
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
class student:
def __init__(self,studentId):
self.studentId=studentId
def getId(self):
return self.studentId
class Resident(person,student):
def __init__(self,name,age,id):
person.__init__(self,name,age)
student.__init__(self,id)
r=Resident('john',30,'102')
r.showName()
r.showAge()
print(r.getId())
#####Output#####
john
30
102
#multilevel inheritance
class student:
def getStudent(self):
self.name=input("name:")
self.age=input("age:")
self.gender=input("Gender:")
class test(student):
def getMarks(self):
self.stuclass=input("class:")
print("enter marks of respective subjects:")
self.literature=int(input("literature:"))
self.math=int(input("math:"))
self.biology=int(input("biology:"))
self.physics=int(input("physics:"))
class Marks(test):
def display(self):
print("name:",self.name)
print("age:",self.age)
print("gender:",self.gender)
print("class:",self.stuclass)
print("total marks:",self.literature+self.math+self.biology+self.physics)
m1=Marks()
m1.getStudent()
m1.getMarks()
m1.display()
#####Output#####
name:harshada
age:22
Gender:female
class:mca
enter marks of respective subjects:
literature:66
math:66
biology:66
physics:66
name: harshada
age: 22
gender: female
class: mca
total marks: 264
28) Write a program to demonstrate class variable, data hiding, method
overriding and operator overloading
1. Class variable
2. Data hiding
Solution
#data hiding
class justCounter:
__secretCount=0
def count(self):
self.__secretCount+=1
print(self.__secretCount)
counter=justCounter()
counter.count()
counter.count()
#print(counter.__secretCount)
print(counter.__justCounter.__secretCount)
#object.__className_attrName
#####Output#####
1
2
3. Method Overriding
Solution:
#overriding
class parent:
def myMethod(self):
print("calling parent method")
class child(parent):
def myMethod(self):
print("calling child method")
c=child()
c.myMethod()
output: calling child method
4.operator overloading
==>#operator overloading
class vector:
def __init__(self,a,b):
self.a=a
self.b=b
def __str__(self):
return "vector(%d,%d)"%(self.a,self.b)
def __add__(self,other):
return (self.a+other.a,self.b+other.b)
v1=vector(2,10)
v2=vector(5,-2)
print(v1+v2)
#####Output#####
(7, 8)
29) Write a program to validate email address and mobile number using
regular expression.
1) Validate email address
Solution:
import re
email="harsha@gmail.com seemagmail.com rasika@gmail.com
himanshu@gmail.com"
print("email matches:",len(re.findall("[\w._%+-0-9]{1,20}@[\w.-]{2,20}.[A-Za-z]
{2,3}",email)))
#####Output#####
email matches: 3
import re
#phone no validation
#\w=[a-zA-Z0-9]
#\W=[^a-zA-Z0-9]
pnum="91-9623608400"
if re.search("\w{2}-\w{10}",pnum):
print("this is valid phone number")
#####Output#####
this is valid phone number
30) Write a program to search string using given pattern and replace that
string by your first name using regular expression.
Solution:
import re
food="haf raf maf haf"
regex=re.compile("[r]af")
Food=regex.sub("Harshada",food)
print(Food)
#####Output#####
haf Harshada maf haf
31) Write a program to search name and age from given data
Solution:
#regular expressions
import re
Nameage='''Harshada is 23 , Rasika is 22,sneha is 23 , seema is 22'''
ages=re.findall(r'\d{1,4}',Nameage)
names=re.findall(r'[A-Z][a-z]*',Nameage)
ageDict={}
x=0
for eachname in names:
ageDict[eachname]=ages[x]
x+=1
print(ageDict)
#####Output#####
import re
str="sat,mat,pat,hat"
allstr=re.findall("[shm]at",str);
for i in allstr:
print(i);
somestr=re.findall("[h-m]at",str);
for i in somestr:
print(i);
somestr1=re.findall("[^h-m]at",str)
for i in somestr1:
print(i);
food="hat,rat,mat,hat";
regex=re.compile("[r]at");
food=regex.sub("food",food);
print(food);
#####Output#####
sat
mat
hat
mat
hat
sat
pat
hat,food,mat,hat
33) Write a program for addition of matrix and transpose of matrix using list
comprehention.
Solution
X = [[1,2,3],
[7 ,8,9]]
Y = [[7,5,7],
[3,2,1]]
result = [[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
#####Output#####
[8, 7, 10]
[10, 10, 10]
[[1, 3, 5, 7], [2, 4, 6, 8]]