You are on page 1of 49

Lab Work

Sr. Hours
Practical Aim
No. Required

Basic of python:

 WAP to calculate area of circle, triangle and rectangle.


1.  WAP to do addition of two numbers take input from user. 4
 WAP to show use of eval function.
 WAP to convert days into months and days.
 WAP to check whether the number is prime or not.
If…else and elif:

 WAP to select & print the largest of the three nos. using
2. Nested If Else statement 4
 WAP to find sum of all integers greater than 100 & less
than 200 and are divisible by 5.
 WAP to print gradable mark sheet of student using elif.
Loops:

 WAP to do print Fibonacci series of N numbers use concept


of command line arguments,
 WAP to show use of continue, pass and break.
 Program to print Patterns.
3. 2

*
***
*****
*******

Tuple, List and Dictionaries:

WAP to try do following task in Tuple:

 Create two list of 5 different tuples, Compare two tuple,


Delete tuple from given location, Delete entire tuple, WAP
to do addition of two matrix using List
WAP to try do following task in List:

 Create two list of 10 different type values, Update item at


5 location, display item from 1 to 3, Insert item at 1st
4. location, display up to 3 , display 5 to end, Display item of 4
last location, Delete item from given location, Compare two
list, Add two list, Delete entire list
WAP to try do following task in Dictionaries:

 Create two dictionary of 6 store items based on categories,


Update values at 4 location, display item from 1 to 3, Insert
item at 1st location, display upto 3 , display 4 to end,
Delete item from given location, Print all keys and values
of dictionary separately, Compare two dictionaries, Add
two dictionaries, Delete item from dictionary, Delete entire
dictionary
Practical 1 – Basic of python

(1.1) Aim: WAP to calculate area of circle, triangle and rectangle.

print("""1.Circle
2.Triangle
3.Rectangle""")
x=eval(input("Enter your choice:"))
if x==1:
r=float(input("Enter the value of radius:"))
a=float(3.14*r*r)
print("Area:",a)
elif x==2:
b=float(input("Enter the value of base:"))
h=float(input("Enter the value of height:"))
a=0.5*b*h
print("Area:",a)
elif x==3:
l=float(input("Enter the value of length:"))
b=float(input("Enter the value of width:"))
a=l*b
print("Area:",a)
else:
print("You entered wrong value...")
(1.2) Aim: WAP to do addition of two numbers take input from user.

i=int(input("Enter the value of first number:"))


j=int(input("Enter the value of second number:"))
add=i+j
print("SUM:",add)
(1.3) Aim: WAP to show use of eval function.

i=eval(input("Enter value:"))
print(type(i))
print("you entered: ",i)
(1.4) Aim: WAP to convert days into months and days.

n=int(input("Enter the number of days:"))


d=n%30
m=(n-d)/30
print("months=%r,days:%r"%(m,d))
(1.5) Aim: WAP to check whether the number is prime or not.

n=int(input("Enter the number:"))


i=2
while i<=n:
if n%i==0:
a=0
print("Entered number is not a PRIME number")
break
else:
a=1
i=i+1
if a==1:
print("Entered number is a PRIME number")
Practical 2 – If…else and elif

(2.1) Aim: WAP to select & print the largest of the three nos. using Nested If Else
statement.

print("Enter three numbers:")


a=eval(input())
b=eval(input())
c=eval(input())
if (a>b) and (a>c):
max=a
elif (b>a) and (b>c):
max=b
else:
max=c
print("Largest number is:",max)
(2.2) Aim: WAP to find sum of all integers greater than 100 & less than 200 and
are divisible by 5.
sum=0

for i in range(101,200):
if i%5==0:
sum+=i

print(sum)
(2.3) Aim: WAP to print gradable mark sheet of student using elif.

p=eval(input("Enter your physics marks:"))


c=eval(input("Enter your chemistry marks:"))
m=eval(input("Enter your Maths marks:"))

perc=(p+c+m)/3
print("percentage is : ",perc)

if perc<40:
grade="FAIL"
elif (perc>=40) and (perc<60):
grade="SECOND CLASS"
elif (perc>=60) and (perc<80):
grade="FIRST CLAAS"
else:
grade="DISTINCTION"

print("Your grade is:",grade)


Practical 3 – Loops

(3.1) Aim: WAP to do print Fibonacci series of N numbers use concept of


command line arguments.

x=int(input("Enter the number N: "))


count=0
sum=0
a=0
b=1
print(a)
print(b)
while(count<x):

sum=a+b
print(sum)
a=b
b=sum
count+=1
(3.2) Aim: WAP to show use of continue, pass and break.

print("If you enter negative value than you comes at end of programe and get
summation of all positive number")
sum=0

while True:
n=eval(input("Enter number:"))
if n>0:
sum=sum+n
elif n==0:
continue
else:
break

print("Addition of all positive number is:",sum)


(3.3) Aim: Program to print Patterns.

row= int(input("Enter no of rows:"))


count=1

for i in range(0,row):
for j in range(1,row-i):
print(" ",end=" ")

for k in range(0,count):
print("*", end=" ")

count+=2
print("\n")
Practical 4 – Tupples, list and dictionaries

(4.1) Aim: WAP to try do following task in Tuple


Create two list of 5 different tuples, Compare two tuple, Delete tuple from
given location, Delete entire tuple, WAP to do addition of two matrix using
List

l1 = ['Raju','43','John','68','Jason','32','Akash','Happy','Bunny','Tweety']
l2 = ['Charlie','34','Jhonny','112','Rick','Rachel','Mike','Kenny','Joe','Donald']
print(l1)
print(l2)

l1[4]= 'Rocky'
l2[4]= 'Vin'
print("Updated l1:",l1)
print("Updated l2:",l2)

print("1 to 3:",l1[0:3])
print("1 to 3:",l2[0:3])

l1.insert(0,'TheBigBang')
print("New l1:",l1)

print("Upto 3:",l1[0:3])

print("5 to End:",l2[4:9])

print("Last value:",l2[9])

del l1[0]
print("After Deleting New l1:",l1)

l1.sort()
l2.sort()

if l1 == l2:
print ("The lists are identical")
else :
print ("The lists are not identical")
l3 = l1 + l2
print("Joined List:",l3)

l3.clear()
print("l3 after deleting:",l3)
(4.2) WAP to try do following task in List :

Create two list of 10 different type values, Update item at 5 location, display item
from 1 to 3, Insert item at 1st location, display upto 3 , display 5 to end, Display
item of last location, Delete item from given location, Compare two list, Add two
list, Delete entire list

list1 = ["one","two","three","four","five","six","seven","eight","nine","ten"]

list2 = ["1","2","3","4","5","6","7","8","9","10"]

print("The list defined are :")

print(list1)

print(list2)

print()

list1[4] = "sixty"

print("The modified list is")

print(list1)

print()

print(list1[1:4])

print()

list2.insert(0,"0")

print(list2)

print(list2[:4]) #display upto 3

print(list2[5:]) #5th to last element

print(list2[-1]) #last element display


del list2[-1]

print(list2)

print()

print("The result of commaring two list is:")

print(list1<list2)

print()

list3 = list1+list2

print("The adddition of two list is \n",list3)

print("Deleting list2 \n")

del list2

try:

print(list2)

except:

print("List2 is deleted so it dont exists")


(4.3) WAP to try do following task in dictionaries :

Create two dictionary of 6 store items based on categories, Update values at 4


location, display item from 1 to 3, Insert item at 1st location, display upto 3 ,
display 4 to end, Delete item from given location, Print all keys and values of
dictionary separately, Compare two dictionaries, Add two dictionaries, Delete
item from dictionary, Delete entire dictionary

#Creating dictionaries

dict1 = {"name" : "Mustang GT", "model" : 2019 ,"Built" : "Custom",


"Colour":"black", "price":350000,"Brand":"Nissan"}

dict2 = {"name" : "Fortuner", "model" : 2017 ,"Built" : "Custom", "Colour":"beige",


"price":550000,"Brand":"Ford"}

print(dict1)

print(dict2)

print()

#updating value

dict1["Colour"]= "Pink"

print("Updated dictionary is :")

print(dict1)

print()

#Displaying particular values


count = 0

print("Displaying first three items:")

for x,y in dict1.items():

count+=1

if count < 4:

print(x,y,sep=":")

else :

break

print()

#inserting item at location one

print("Inserted new item: ")

dict2["Resale value"] = 100000

print(dict2)

print()

#Displaying from 4 to end

count = 0
print("Displaying items from four and onwards :")

for x,y in dict1.items():

count+=1

if count < 4:

continue

else :

print(x,y,sep=":")

print()

#deleting item from given location

print(dict2)

del dict2["Colour"]

print("Updated dictionary")

print(dict2)

print()

#Printing keys and values separately

print("Printing keys: ")

for x in dict1:

print(x)
print()

print("Printing Values: ")

for y in dict1:

print(dict1[y])

print()

#Comparing two dictionaries

for x_values, y_values in zip(dict1.items(), dict2.items()):

if x_values == y_values:

print ('Ok', x_values, y_values)

else:

print ('Not', x_values, y_values)


#Deleting entire dictionary

print()

del dict2

try:

print(dict2)

except:

print("dict2 is deleted so it don't exists//")

Output
Practical 5 – String

(5.1) WAP to count total words in text and length of text.


my_string = “India has 28 states"
print ("The original string is : " + my_string)
res = len(my_string.split())
print ("The number of words in string are : " + str(res))
a=len(my_string)
print("Lenght of text = " , a)
(5.2)WAP to join two strings.

f_name="Aman "
l_name="Dobariya"
print(f_name)
print(l_name)
print(f_name + l_name )
(5.3) WAP to Find given string is palindrome or not.

string=input(("Enter a string:"))

if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")
Practical 6: Functions
(6.1) Aim: WAP to show use of default argument to calculate area of circle in
function.

def area(r=20):
return (22/7)*(r**2)

a=area()
print("Area:",a)
(6.2) Aim: WAP to illustrate the concept of call by value and call by reference.

def dummy(a):
print(a)

print(dummy(5))
(6.3) Aim: WAP to reverse the digit using function return value from function,
create module for reverse number.
def reverse_number(a):
b=str(a)
b=b[::-1]
c=int(b)
return c

n=int(input(("Enter the integer number:")))


print("reverse of that number is:",reverse_number(n))
(6.4) WAP to find out factorial of given number using recursion import module of
factorial.

from logicFact import fact as f

n = eval(input("enter no whose factorial need to be found: "))

print("The factorial of %d is '%d'"%(n,f(n)))

def fact(n):

if n==0:

return 1

else:

return n*fact(n-1)

Output
(6.5)WAP to arrange given number in ascending orders import module of ascending
order.

from logicAscend import ascend as a

def ascending():

arr = []

l = eval(input("How many elements you want in your list? "))

for i in range(0,l):

n = eval(input("Enter value :"))

arr.insert(i,n)

print(arr)

print("Sorted array in aseccnding order is ",a(arr))

ascending()

def ascend(n):

temp = 0

for i in range(0,len(n)):

for j in range(i+1,len(n)):

if n[i]>n[j]:

"""temp = n[i]

n[i]=n[j]

n[j]=temp"""

n[i],n[j]=n[j],n[i]

return n
Practical 7 – Object Oriented Programming

(7.1) WAP to demonstrate declaration and initialization of object of a class.

class bio:

def __init__(self, name):


self.name = name

def msg(self):
print('I am ', self.name)

p = bio('Aman')
p.msg()
(7.2)WAP to print average of 10 numbers using class and object.

class num():
def __init__(self):
self.l=[]

def ins(self,i):
self.l.append(i)

def avg(self):
s=sum(self.l)
l=len(self.l)
return s/l
n=num()
print("Enter 10 numbers")
for i in range(10):
n.ins(int(input()))
print("Average of that 10 numbers is ", n.avg())
(7.3) WAP multiply the positive numbers using single level inheritance.

Source code:
class num():

def __init__(self):
pass

class add(num):

def __init__(self,a,b):
num.a=a
num.b=b

def myAdd(self):
return num.a+num.b

n=num()
t1=int(input("Enter 1st number : "))
t2=int(input("Enter 2nd number : "))
a=add(t1,t2)
t=a.myAdd()
print("Addition is : ",t)

Practical 8 – Exception
(8.1)WAP to perform exception handling for Divide by zero Exception.

class DivByZero:

def __init__(self,a,b):

self.a = a
self.b = b

def check(self):

c = self.a/self.b
print (c)
try:

a = int(input("Enter Value of A : "))


b = int(input("Enter valur of B : "))

x = DivByZero(a,b)
x.check()

except:
print("Error : Cannot divide with zero")

(8.2)WAP to perform exception handling operation


class Exp:

def __init__(self,a):

self.a = a

def check(self):

try:

print("Divided by : ",self.a)
x = 1/int(self.a)

except Exception as e :

print("Error : ",str(e))

else :

print(1,"Divided by ",self.a, "is : ",x)

d1 = Exp('zero')
d1.check()
d2 = Exp(0)
d2.check()
d3 = Exp(3)
d3.check()
(8.3) WAP to create user defined Exception

class Error(Exception):
pass

class SmallError(Error):
pass

class BigError(Error):
pass

class BigSmall:

def __init__(self,a):
self.a = a

def check(self):

try :

if self.a < 50000:


raise SmallError

elif self.a > 50000:


raise BigError

except SmallError :
print("Error : Entered is less than 50000.\n")

except BigError:
print("Error: Entered is Greater than 50000.\n")

else:
print("Entered is exact 50000.")

money = 50000
a = int(input('Enter a Number : '))
x = BigSmall(a)
x.check()
a = int(input('Enter a Number : '))
y = BigSmall(a)
y.check()
a = int(input("Enter a Number : "))
z = BigSmall(a)
z.check()

Practical 9 – File
(9.1)WAP to create a file, store given text, calculate total number of words in text,
and display it on shell.

myfile = open("abc.txt",'r')

txt=myfile.read()

print("-------------------------------------------")

print("File have below content")

print("-------------------------------------------")

print(txt)

print("-------------------------------------------")

myfile.seek(0)

words=0

for line in myfile:

words=words+len(line.split())

print("Total number of words in file is",words)

myfile.close()

(9.2) WAP to store content of two file into one file and count total numbers of
character in file and display it.
myfile = open("abc.txt",'r')

txt=myfile.read()

print("-------------------------------------------")

print("File 1 have below content")

print(txt)

print("-------------------------------------------")

myfile.seek(0)

myfile1 = open("def.txt",'r')

txt1=myfile1.read()

print("-------------------------------------------")

print("File 2 have below content")

print(txt1)

print("-------------------------------------------")

myfile1.seek(0)

desfile=open("Merge.txt",'w')

desfile.write(txt+"\n")

desfile.write(txt1+"\n")

desfile.close()

desfile=open("Merge.txt",'r')

OUTPUT=desfile.read()

print("-------------------------------------------")

print("OUTPUT have below content")

print("-------------------------------------------")
print(OUTPUT)

print("-------------------------------------------")

print("Total Number of Characters in Merge.txt is ",len(OUTPUT))

myfile.close()

myfile1.close()

desfile.close()

Practical 10
(10.1)WAP to find out email address of a file and count total number of email
address using regular expression, also find out name starts with S and with A,
find out name word starts with PA. Find out Mobile number starts with 99 and
count

import re
f=open("test_file.txt","r")
str1=f.read()
print(str1)
email = re.findall('\w+@\w+', str1)
start1 = re.findall('S[\w]+', str1)
start2 = re.findall('A[\w]+', str1)
start3 = re.findall('PA[\w]+', str1)
mob = re.findall('99\d{8}', str1)

print("Count of Email : ",len(email))


print("Count of Start(A/S) : ",len(start1)+len(start2)+len(start3))
print("Count of Mobile No. : ",len(mob))
print(start1)
print(start2)
print(start3)

You might also like