Oop With Python Lab
Oop With Python Lab
It is the simplest way to run the python programs. This interactive mode would be started
with DOS console and with IDE(Integrated Development Environment). The drawback of the
interactive mode is it doesn’t allow your program to save a file.
We can run python from Graphical User Interface(GUI) environment as well .It
provides lot of menu’s like File, Edit, Shell, Debug etc.
1
Output:
2
b) Write a program to purposefully raise Indentation Error and correct it
Source code :-
3
Exercise 2- Operations
a) Write a program to compute distance between two points taking input from the
user(Pythagorean Theorem)
Source Code:-
import math
d=math.sqrt((x2-x1)**2+(y2-y1)**2)
Output:-
b) Write a program add.py that takes 2 numbers as command line arguments and prints its
sum.
Source Code:
import sys
s=int(sys.argv[1])+int(sys.argv[2])
Output:
4
5
Exercise -3 Control Flow
a) Write a Program for checking whether the given number is an even number or not.
Source Code:-
Output:-
EVEN NUMBER
b) Using a for loop ,write a program that prints out the decimal equivalents of 1/2
,1/3,1/4,…,1/10
Source code :-
i=0
for i in range(2,11):
print ("value of 1/",i,"is:",(1.0/i))
Output:-
6
c) Write a program using a for loop that loops over a sequence.What is sequence?
Source code:-
i=0
for i in "hello python":
print(i)
Output:-
d) Write a program using a while loop that asks the user for a number, and prints a countdown
from that number to zero.
Source code:-
7
Output:-
8
Exercise 4 - Control Flow – Continued
s=2
i=0
j=0
for i in range(3,20,2):
for j in range(2,i):
if(i%j==0):
break
else:
print(i)
s=s+i
print ("sum of all prime numbers",s)
9
10
Output:- (sum upto 20000 numbers)
11
b) By considering the terms in the Fibonacci sequence whose values do not exceed four
million,find the sum of the even-valued terms.
Source Code:-
a=0
b=1
s=0
while(a<40):
print(a)
a,b=b,a+b
if(a%2==0):
s=s+a
print (“sum of even numbers in Fibonacci series :”,s)
12
13
Exercise - 5 – DS
a) Write a program to count the numbers of characters in the string and store them in
dictionary data structure
Source code:
i=0
s=input("enter the string:")
k=1
print("Is it string?",s.isalpha())
l=len(s)
print("numbers of characters in string :",l)
d={1:" "}
while(i<l):
d.__setitem__(k,s[i])
i=i+1
k=k+1
print("the item of dictionary:",d)
Output:-
14
b) Write a program to use split and join methods in the string and trace a birthday with a
dictionary data structure.
Source code:
Output:-
15
Exercise - 6 DS – Continued
Source Code:-
sub=["OOPP","English","Physics","DENM","BEEE","ITE"]
marks=[85,96,88,75,81,92]
dic=dict(zip(sub,marks))
print("\n Dictionary:",dic)
Output:-
Given List are:
Dictionary: {'OOPP': 85, 'English': 96, 'Physics': 88, 'DENM': 75, 'BEEE': 81, 'ITE': 92}
b) Write a program to count frequency of characters in a given file. Can you use character
frequency to tell whether the given file is a Python program file, C program file or a text file?
Source Code:-
filetypes=['.py','.c','.txt']
fn=input("Enter the file name:")
f=open(fn,"r") #opening a file
print("Given file is:",end='\t')
for ft in filetypes:
if(ft in fn):
if(ft==".py"):
print("Python File")
elif(ft==".c"):
print("C File")
elif(ft==".txt"):
print("Text File")
st=f.read()
print("The file content is ",st)
s=set(st) #removes the duplicate characters
i=[]
for x in s:
count=0
16
for y in st:
if(x==y):
count=count+1
i.append(count)
print("The set contents are:",s)
print("The frequency table is:",i)
print("The character frequency is:",list(zip(s,i)))
Output:-
17
Exercise - 7 Files
Source code :-
Output:-
b) Write a program to compute the number of characters, words and lines in a file.
Source code :-
f=open("first.txt","r")
st=f.read() #reading content from file object
print("The content of file :",st)
n=len(st)
print("the no. of characters in string :",n)
words=st.split()
wc=len(words)
print("the no. of words in string:",wc)
lines=st.splitlines()
lc=len(lines)
print("the no. of lines in string:",lc)
18
Output:-
19
Exercise - 8 Functions
a) Write a function ball_collide that takes two balls as parameters and computes if they are
colliding. Your function should return a Boolean representing whether or not the balls are
colliding.
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius
Source code :-
import math
def ball_collide(t1,t2):
d=math.sqrt((x2-x1)**2+(y2-y1)**2)
r=r1+r2
print("centroid distance of two balls is:",d)
print("Sum of radius of two balls is:",r)
if(d<=r):
return True
else:
return False
x1=int(input("enter the value of x1:"))
y1=int(input("enter the value of y1:"))
x2=int(input("enter the value of x2:"))
y2=int(input("enter the value of y2:"))
r1=int(input("enter the value of r1:"))
r2=int(input("enter the value of r2:"))
t1=(x1,y1,r1)
t2=(x2,y2,r2)
if ball_collide(t1,t2):
print("balls are collide")
else:
print("the balls do not collide")
Output:-
20
b) Find mean, median, mode for the given set of numbers in a list.
Source code :-
21
n=a//2
print("median is",l[n])
#calculate mode
def mode(l):
for x in l:
l1.append(l.count(x))
m=max(l1)
print("mode is",l[l1.index(m)])
#read size and elements into list
l=[]
l1=[]
i=0
m=int(input("Enter the size of the list:"))
while(i<m):
l.append(int(input("enter the element:")))
i=i+1
print("the list contains:",l)
a=len(l)
mean(l)
median(l)
mode(l)
Output:-
median is 2.5
mode is 1
22
Exercise - 9 Functions – Continued
a) Write a function nearly_equal to test whether two strings are nearly equal. Two strings a
and b are nearly equal when a can be generated by a single mutation on b.
Source code :-
def nearly_equal(s1,s2):
count=0
i=j=0
while(i<len(s1)and j<len(s2)):
if(s1[i]!=s2[j]):
count+=1
if(count>1):
return False
i+=1
j+=1
if(count<2):
return True
s1=input("enter string1:")
s2=input("enter string2:")
if(nearly_equal(s1,s2)):
print("Strings are nearly Equal")
else:
print("Strings are NOT Equal")
Output:-
enter string1:Engineering
enter string2:Engg
enter string1:Engineering
enter string2:English
23
b) Write a function dups to find all duplicates in the list.
Source code :-
def dups(list):
temp=[]
for x in list:
if(list.count(x)>1):
temp.append(x)
s=set(temp)
print("the duplicate values:",s)
#read the size of list and read the elements
list=[]
i=0
m=int((input("enter size of list:")))
while(i<m):
list.append(int(input("enter element:")))
i=i+1
print("the list contain:",list)
dups(list)
Output:-
24
b) Write a function unique to find all the unique elements of a list.
Source code :-
def unquie(list):
temp=[]
for x in list:
if(list.count(x)==1):
temp.append(x)
print("the unqiue elements are :",temp)
#read the size of list and read the elements
list=[]
i=0
m=int(input("enter size of list:"))
while(i<m):
list.append(int(input("enter element:")))
i=i+1
print("the list contain:",list)
#function call
unquie(list)
Output:-
enter element:1
enter element:5
enter element:2
enter element:3
enter element:5
25
Exercise - 10 - Functions - Problem Solving
Source Code:-
Output:
b. Write a function reverse to reverse a list. Without using the reverse function.
Source Code:-
26
print("The elements after reversing are:",temp)
#function call
rev(num)
Output:
Enter the size of list: 5
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
Enter the element:5
The lis before reversing is: [1, 2, 3, 4, 5]
The elements after reversing are: [5, 4, 3, 2, 1]
c. Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed
one line.
Source Code:-
n1=int(input("Enter n1:"))
n2=int(input("Enter n2:"))
def gcd(a,b):
if a==b:
print("The GCD is:",a)
return a
elif a>b:
return(gcd(a-b,b))
else:
return(gcd(a,b-a))
def lcm(a,b):
return((a*b)/gcd(a,b))
res=lcm(n1,n2)
print("The LCM is:",res)
Output::
Enter n1:9
Enter n2:21
The GCD is: 3
The LCM is: 63.0
27
Exercise 11 - Multi-D Lists
Source code :-
print("Matrix is:")
for i in range(rows):
for j in range(cols):
print(matrix[i][j],end='\t')
print()
Output:-
28
b) Write a program to perform addition of two square matrices
Source code :-
print("Matrix is:")
for i in range(rows):
for j in range(cols):
print(matA[i][j],end='\t')
print()
print("Matrix is:")
for i in range(rows):
for j in range(cols):
print(matB[i][j],end='\t')
print()
for x in res:
print(x)
Output:-
29
3 4
Enter [00]value:1
Enter [01]value:2
Enter [10]value:3
Enter [11]value:4
Matrix is:
1 2
3 4
[2, 4]
[6, 8]
30
Output:-
Enter row size of Matrix:2
Enter column size of Matrix:2
Enter [00]value:1
Enter [01]value:2
Enter [10]value:3
Enter [11]value:4
Matrix is:
1 2
3 4
Enter [00]value:1
Enter [01]value:2
Enter [10]value:3
Enter [11]value:4
Matrix is:
1 2
3 4
[7, 10]
[15, 22]
31
Exercise - 12 – Modules
steps:
Installing requests:
32
To see the contains about the packages type the following
33
Installing flask:
To see the contains about the flask package type the following
34
pip show flask
35
b) Write a script that imports requests and fetch content from the page. Eg. (Wiki)
Source code :-
import requests
req= requests.get("http://www.yahoo.com")
print("status code is:",req.status_code)
print("the URL is :",req.url)
print("the content type Header is:",req.headers['content-type'])
print("the non-textual content is:",req.content)
print("the text content is:",req.text)
print("the history is:",req.history)
Output:-
c) Write a simple script that serves a simple HTTP Response and a simple HTML
Page
Source code :-
def main():
return render_template("login.html")
if __name__== "__main__":
app.run(host= "127.0.0.1",port=2500) #used the application
36
Output:-
37
Exercise - 13 OOP
i) Robot
ii) ATM Machine
Source code :-
class bankaccount:
balance=0
def deposit(self,d):
bankaccount.balance+=d
def withdrawal(self,w):
if(bankaccount.balance>=0):
print("withdrawal is successful")
bankaccount.balance-=w
else:
print("insufficient balance in your account")
def balenq(self):
print ("Balance is :",bankaccount.balance)
#creating objects
atm1=bankaccount()
atm2=bankaccount()
atm3=bankaccount()
#function call
atm1.deposit(float(input("enter amount to be deposit:")))
atm1.balenq()
atm2.withdrawal(float(input("enter amount to be withdraw:")))
atm2.balenq()
atm3.withdrawal(float(input("enter amount to be withdraw:")))
atm3.balenq()
Output:-
enter amount to be deposit:10000
Balance is : 10000.0
enter amount to be withdraw:5000
withdrawal is successful
Balance is : 5000.0
enter amount to be withdraw:2500
withdrawal is successful
Balance is : 2500.0
38
Instance variable version
class bankaccount:
balance=0
def deposit(self,d):
self.balance+=d
def withdrawal(self,w):
if(self.balance>=w):
print("withdrawal is successful")
self.balance-=w
else:
print("insufficient balance in your account")
def balenq(self):
print ("Balance is :",self.balance)
#creating objects
atm1=bankaccount()
atm2=bankaccount()
atm3=bankaccount()
#function call
atm1.deposit(float(input("enter amount to be deposit:")))
atm1.balenq()
atm2.withdrawal(float(input("enter amount to be withdraw:")))
atm2.balenq()
atm3.withdrawal(float(input("enter amount to be withdraw:")))
atm3.balenq()
Output:-
39
Robot
class robot:
rbno=5
def __init__(self,name):
self.name=name
robot.rbno+=1
def disp(self):
print("the robot name is:",self.name)
print("no. of robot created:",robot.rbno)
def killrobot(self):
robot.rbno-=1
r1=robot("srinu")
r2=robot("george")
r3=robot("vinay")
r1.disp()
r2.disp()
r3.disp()
r1.killrobot()
r1.disp()
r2.killrobot()
r2.disp()
r3.killrobot()
r3.disp()
Output:-
40
Instance variable version
class robot:
rbno=0
def __init__(self,name):
self.name=name
self.rbno+=1
def disp(self):
print"the robot name is:",self.name
print"no. of robot created:",self.rbno
def killrobot(self):
self.rbno-=1
print"starting with 5 robots"
r1=robot("srinu")
r2=robot("george")
r3=robot("vinay")
r1.disp()
r2.disp()
r3.disp()
r1.killrobot()
r1.disp()
r2.killrobot()
r2.disp()
r3.killrobot()
r3.disp()
Output:-
41
42
Exercise - 14 GUI, Graphics
Source code :-
43
s=str(s1)
res=Label(root,text='Result is :'+s)
res.config(font=('calbri',30,'italic'),bg='pink',fg='green')
res.grid(row=4,column=0)
#creating the widgets
l=Label(root,text='simple calculator')
l.config(font=('calbri',30,'italic'),bg='cyan',fg='red')
l1=Label(root,text='First Number')
l2=Label(root,text='Second Number')
t1=Entry(root,width=8)
t2=Entry(root,width=8)
a=Button(root,text='+',command=printadd)
s=Button(root,text='-',command=printsub)
m=Button(root,text='*',command=printmul)
d=Button(root,text='/',command=printdiv)
md=Button(root,text='%',command=printmulodiv)
#attaching the widgets to window
l.grid(row=0,column=0)
l1.grid(row=1,column=0)
t1.grid(row=1,column=1)
l2.grid(row=2,column=0)
t2.grid(row=2,column=1)
a.grid(row=3,column=2)
s.grid(row=3,column=3)
m.grid(row=3,column=4)
d.grid(row=3,column=5)
md.grid(row=3,column=6)
Output:-
44
45
b. Write a program to implement the following figures using turtle
Source code :-
import turtle
turtle.bgcolor('white')
turtle.pensize(3)
c=['purple','blue','green','black']
for a in range(0,360,20):
if a>=0 and a<=90:
turtle.color(c[0])
turtle.circle(100)
turtle.seth(a)
if a>90 and a<=180:
turtle.color(c[1])
turtle.circle(100)
turtle.seth(a)
if a>180 and a<=270:
turtle.color(c[2])
turtle.circle(100)
turtle.seth(a)
if a>270 and a<=360:
turtle.color(c[3])
turtle.circle(100)
turtle.seth(a)
46
Output:-
Source code :-
import turtle
turtle.bgcolor('black')
turtle.color('white')
l=[90,90,90,90]
for x in range(0,360,10):
for a in l:
turtle.forward(100)
turtle.left(a)
turtle.seth(x)
47
Output:-
48