Subject Title:Python Programming Lab Practice Branch:Dcme SUBJECT CODE:18CM-508P (A) SEM:5 Shift:2
Subject Title:Python Programming Lab Practice Branch:Dcme SUBJECT CODE:18CM-508P (A) SEM:5 Shift:2
36 Python program where a child inherits the attributes and function from 60-61
both father and mother. Add additional attributes and functions for the
child class. Call all the methods and display all the attributes of the
child class along with the inherited attributes using the child class
object. Mention the type of inheritance should be employed here.
68 Python program Create three threads and implement the each 109-110
functionality in the run method of three thread classes in a threading
module.
--> First thread calculates the square of numbers from 1 to 10.
--> Second thread calculates the square root of numbers from 11 to 20.
--> Third thread calculates the cube root of numbers from 21 to 30.
69 Python program to Create Multiple threads which perform different 111
tasks using threading module.
70 Python program to Design threads using start(), join(), isAlive(), 112-113
getName(), setName(), activeCount() and currentThread() methods
71 Python program to achieve thread synchronization in multithreaded 114-115
environment.
72 Python program to provide synchronize access to the global variable 116-117
balance representing the balance in your father bank account where
three threads namely father, mother and you trying to depositing an
amount, checking the balance and you performing the withdrawal
through an ATM respectively
Press Enter key and the Command Prompt will appear like:
Now you can execute your Python commands. Now you can type any valid python
expression at the prompt. Python reads the typed expression, evaluates it and prints the
result.
2. Script Mode: Using Script Mode, you can write your Python code in a separate file using
any editor of your Operating System.
Save the file in any folder (Ex : Desktop) with any name and an extension of (a.py).
Now open Command prompt and run this program by calling python a.py
i) Using Interactive Mode : Execute your Python code on the Python prompt and it will
display the result simultaneously.
(ii) Using Script Mode: Click on Start button -> All Programs -> Python -> IDLE (Python
GUI). Python Shell will be opened.
Got File menu click on New File (CTRL+N) and write the code and save add.py
a=input("Enter a value: ")
b=input("Enter b value: ")
c=int(a)+int(b)
print("The sum is, c)
(b) ******
*****
****
***
**
*
(c) 1
121
12321
1234321
123454321
(d) 1
12
123
1234
123
12
1
(e) $****
*$ *
* $ *
* $*
****$
(f) ***
*
***
for i in range(1,6):
print("* "*i)
print()
print("(B)")
k=3
for i in range(5,-1,-1):
for j in range(k,0,-1):
print(end=' ')
k=k+1
for j in range(0,i+1):
print("*",end=' ')
print(' ')
print("(C)")
for i in range(6):
for j in range(1,i+1):
print(j,end=' ')
if(i==j):
for x in range(i-1,0,-1):
print(x,end=' ')
print()
print("(D)")
for i in range(5):
for j in range(1,i+1):
print(j,end=' ')
print()
for i in range(4,0,-1):
for j in range(1,i):
print(j,end=' ')
print("(E)")
for i in range(1,6):
for j in range(1,6):
if i==j:
print("$",end=" ")
elifi==1 or j==1 or i==5 or j==5:
print("*",end=" ")
else:
print(" ",end=" ")
print(" ")
print("(F)")
for i in range(1,6):
for j in range(1,4):
if i==2 and j==1:
print("*",end=' ')
elifi==4 and j==3:
print("*",end=' ')
elifi==1 or i==3 or i==5:
print("*",end=" ")
else:
print(" ",end=" ")
print(" ")
print("(G)")
a=65
for i in range(5):
for j in range(i+1):
print(chr(a),end=' ')
a+=1
print()
print()
Save:- “lcmgcd.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
#2)set operations
#a)union
s1={1,2,3,4,5}
s2={9,8,7,6,5,4}
print(s1.union(s2))
print(s1|s2)
#b)intersection
print(s1.intersection(s2))
print(s1&s2)
#c)difference
print(s1.difference(s2))
print(s1-s2)
print(s2.difference(s1))
print(s2-s1)
#d)symmetric_differnce
print(s1.symmetric_difference(s2))
print(s1^s2)
#3)set functions
set1={1,2,3,4,5}
set2={9,8,7,6,5,4}
#a)issuperset
print(set1.issuperset(set2))
print(set1>=set2)
#b)issubset
print(set1.issubset(set2))
print(set1<=set2)
#c)isdisjoint
print(set1.isdisjoint(set2))
#4)set methods
#a)pop
print(set1.pop())
print(set1)
#b)remove
print(set1.remove(3))#raises error if element is not found in set
print(set1)
#c)discard
print(set1.discard(100))#raises no error even if element is not found in set
print(set1)
#d)del
del(set1)
print(set1)#error as set1 not found
Save:- “20.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
22.Aim: Write a python program to create a String and perform following operations
on it.
(i) Create string in different ways.
STUDENT NAME:B.RAJESH PIN:19001-CM-221
FACULTY: M. SURESHM.Tech 39
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
(ii) Perform slicing of string in different ways.
(iii) Process string using operator +,*, in, not in, and, and or.
(iv) Use following function to process a stringcapitalize(), title(), lower(), upper(),
swapcase(), islower(), isupper(), isdigit(), isalpha(), isalnum()
(v) Use following function to process a string count(),find(),replace(),index() (vi) Use
following function to process a string rjust(),ljust(),center(),zfill(),join() (vii) Write a
python program to display the characters that are repeated in a string also display the
times it was repeated. Example Input: i am a diploma cme student Output: i=2 a=3
m=3 d=2 e=2
(viii) Write a python program that finds the most repeated word in a given paragraph.
(ix) Write a python program that display a word, its reverse word (palindrome) if both
exists in the given paragraph.
(x) Write a python program to split the given sentence into list of words.
Program:
import collections
from collections import Counter
str1='gptcmasabtank'
str2="computer engineering"
str3='''third year fifth sem'''
print("str1:",str1)
print("str2:",str2)
print("str3:",str3)
print("---INDEXING---")
print("str1[0]:",str1[0])
print("str1[1]:",str1[1])
print("str1[-1]:",str1[-1])
print("---SLICING---")
print("str2[:]:",str2[:])
print("str2[2:5]:",str2[2:5])
print("str2[2:]:",str2[2:])
print("str2[:7]:",str2[:7])
print("str2[7:-3]:",str2[7:-3])
print("----STRING OPERATORS----")
print("concatination(+):",str1+str2)
print("repeatation of string n times(*):",str1*4)
print("in operator (a in str2):","a" in str2)
print("not in operator (g not in str1):","g" not in str1)
print("and operator (str1 and str2):",str1 and str2)
24.Aim: Define a function that finds the sum of any number of numbers.
Program:
#using iteration
print("factorial of ",num," using iterative")
fac = 1
for i in range(1, num + 1):
fac = fac * i
print(fac)
Save:- “26.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
def FibRec(n):
if n<=1:
return n
else:
return FibRec(n-1)+FibRec(n-2)
if n<=0:
print("please enter a positive integer")
else:
print("4.fibonacci series upto",n,"using recursion")
for i in range(n):
f=FibRec(i)
class derived(base):
def __init__(self,):
base.__init__(self)
a = int(input("enter a value:"))
b = int(input("enter b value:"))
print("i am in derived class")
print("addition in derived class=", (a + b))
obj=derived()
Save:- “31.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
class teacher(person):
print("")
print("")
print("Enter teacher details")
subject = input("enter the subject name=")
college = input("enter the college name=")
nstudents = int(input("enter the no. of students="))
workload = int(input("enter the no. of work done="))
semester = int(input("enter the semester="))
38.Aim: a person has 2 kids, each kid have their own attributes and the inherited.
Display the details of both the kids along with the inherited ones. Mention the type of
inheritance should be employed here.
Program:
class father():
class mother():
mheight=0
class son(father,mother):
def __init__(self,sf,sm):
self.fheight=sf
self.mheight=sm
def sh(self):
print(self.fheight)
sheight=(self.fheight+self.mheight)/2
return sheight
Save:- “38.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
class icici(bank):
def get_interest_rate(self,p,t):
print('rate of interest for the bank icici is 7%')
print('rate of interest for the amout',p,'during ',t,'years is:',((p*t*7)/100))
class axis(bank):
def get_interest_rate(self,p,t):
print('rate of interest for the bank axis is 9%')
print('rate of interest for the amout',p,'during ',t,'years is:',((p*t*9)/100))
axisobj =axis()
sbiobj=sbi()
iciciobj=icici()
p=float(input('enter principal amount:'))
t=float(input('enter time period:'))
sbiobj.get_interest_rate(p,t)
iciciobj.get_interest_rate(p,t)
axisobj.get_interest_rate(p,t)
Save:- “39.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
44. Aim: Create a package named Cars with three modules Bmw_car.py, Audi_car.py
and Nissan_car.py with three seperate classes BMW, Audi, Nissan with attributes and
#Main.py
import admission as admin
import teaching as teach
import test
48. Aim: Write a python program to use local and global variables in the same
program.
50. Aim: Write a python program where first function swaps the global variable with
the local variable and the next function return the cube root of the new global variable
value.
Program:
a = int(input("enter the global value:"))
def swapGlobal():
global a
b = int(input("enter the local value:"))
a=b
def Cube():
return a**(1/3)
swapGlobal()
print("The new global value after swapig global variable with local :",a)
print("cube root of ",a," =",Cube())
Save:- “50.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
51. Aim: Write the steps to install, create, enable and disable virtual environment in the
following platforms
A. Windows
54. Aim: Write a python program to show Graphical representation of sin and cos
waves using sin() and cos() functions of math module.
58. Aim: Write a python that calculates from your date of birth
a. Number of Years you lived
59. Aim: Write a python script that calculates number of days to your next birthday
and on which week day your next birthday will happen.
Program:
from datetime import datetime
def get_user():
def calculate(birthday):
now=datetime.now()
delta1=datetime(now.year, birthday.month, birthday.day)
delta2=datetime(now.year+1, birthday.month, birthday.day)
weekday=delta2.weekday()
print("Your birthday will be on ", end="")
if weekday == 0:
print("Monday")
elif weekday == 1:
print("Tuesday")
elif weekday == 2:
print("Wednesday")
elif weekday == 3:
print("Thursday")
elif weekday == 4:
print("Friday")
elif weekday == 5:
print("Saturday")
elif weekday == 6:
print("Sunday")
return((delta1 if delta1 > now else delta2)-now).days
bd = get_user()
c=calculate(bd)
print("Days left till your birthday:",c)
Save:- “59.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
60. Aim: Write a python program that calculates the retirement age of a person. A
person retires from the service if he attains the age of 60 years or 33 years of service
whichever is earlier. Give the following input from the keyboard
1. Date of Birth
2. Date of Joining the Service
Program:
from datetime import date
61. Aim: If a Student joins the College on X day and leaves the college on Y day.
Calculate the Numbers of years, months and days a student studies in the college.
Program:
from datetime import date
d1=date(2022,1,24)
d2=date(2019,6,1)
duration=(d1-d2)
print("from 1/6/2019 to 24/1/2022 :")
print(" total Days = ",duration.days)
years=duration.days // 365
63. Aim: Write a program with error block and finally block.
Program:
def divide(x, y):
try:
result=x // y
except ZeroDivisionError:
print("Sorry! You are dividing by zero")
except ValueError:
print("correct value should be given")
except NameError:
print("this name is not defined")
else:
print("Yeah! Your answer is :",result)
finally:
print("this is always executed ")
STUDENT NAME:B.RAJESH PIN:19001-CM-221
FACULTY: M. SURESHM.Tech 102
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
divide(3,2)
divide(3,0)
Save:- “63.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
64. Aim: Write a python program where try block is given inside another block.
Program:
try:
a=1,2,3,4,5
print(a[5])
try:
x=a[2]//0
except ZeroDivisionError:
print("division by zero is not possible")
except IndexError:
print(" IndexError")
print("Element at such index does not exist")
Save:- “64.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
obj=MyException()
bank={"ravi":5000.00,"ramu":8500.00,"raju":1990.00}
try:
obj.abc(bank)
except MyException as e:
print(e.args)
Save:- “66.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
Output:-
for i in range(5):
th=Thread(target=sleepme,args=(i,))
th.setName('first thread')
th.start()
print(th.isAlive())
th.join()
print(th.isAlive())
print("current thread count:%i" % threading.activeCount())
Save:- “70.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
class Mythread(Thread):
def __init__(self,tobj,number):
Thread.__init__(self)
self.tobj=tobj;
self.number=number
def run(self):
lock.acquire()
self.tobj.printTable(self.number)
lock.release()
lock=Lock()
tobj=Table()
t1=Mythread(tobj,100)
t2=Mythread(tobj,200)
t3=Mythread(tobj,300 )
t1.start()
t2.start()
t3.start()
Save:- “71.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
lock=Lock()
t1=Thread(target=thread_task)
t1.setName("Father")
t1.join()
t2.join()
t3.join()
print("End of the program.....")
Save:- “72.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
73. Aim:Design the following GUIs using pack geometry managers and make sure that
the size of widget changes as the size of the container widget.
A. B.
Program:
73A.py
from tkinter import *
win=Tk()
b1=Button(win,text="ALL IS WELL").pack(fill=BOTH,expand=True)
b2=Button(win,text="BACK TO BASICS").pack(fill=BOTH,expand=True)
b3=Button(win,text="CATCH ME IF U CAN").pack(fill=BOTH,expand=True)
b4=Button(win,text="LEFT").pack(side=LEFT,fill=BOTH,expand=True)
b5=Button(win,text="CENTER").pack(side=LEFT,fill=BOTH,expand=True)
b6=Button(win,text="RIGHT").pack(side=LEFT,fill=BOTH,expand=True)
win.mainloop()
73B.py
from tkinter import *
win=Tk()
topframe=Frame(win)
topframe.pack(side=TOP,expand=True,fill=BOTH)
bottomframe=Frame(win)
bottomframe.pack(side=BOTTOM,expand=True,fill=BOTH)
b1=Button(topframe,text="red",bg="red",fg="white").pack(side=LEFT,fill=BOTH,expand=
True)
b2=Button(topframe,text="blue",bg="blue",fg="white").pack(side=LEFT,fill=BOTH,expand
=True)
b3=Button(topframe,text="green",bg="green",fg="white").pack(side=LEFT,fill=BOTH,expa
nd=True)
b4=Button(bottomframe,text="black",bg="black",fg="white").pack(fill=BOTH,expand=Tru
e)
mainloop()
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
Program:
from tkinter import *
win=Tk()
l=Label(win,text="Find:").place(x=10,y=10)
l=Label(win,text="Replace:").place(x=10,y=40)
e=Entry(win,width=60).place(x=60,y=10)
e=Entry(win,width=60).place(x=60,y=40)
b=Button(win,text="Find",width=10).place(x=450,y=10)
b=Button(win,text="FindAll",width=10).place(x=450,y=40)
b=Button(win,text="Replace",width=10).place(x=450,y=70)
b=Button(win,text="ReplaceAll",width=10).place(x=450,y=100)
c=Checkbutton(win,text="Match whole word only").place(x=10,y=70)
c=Checkbutton(win,text="Match Case").place(x=10,y=100)
c=Checkbutton(win,text="Wrap around").place(x=10,y=130)
l=Label(win,text="Directions:").place(x=200,y=70)
c=Radiobutton(win,text="up").place(x=200,y=100)
c=Radiobutton(win,text="down").place(x=280,y=100)
mainloop()
Save:- “74.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
Program:
import tkinter as tk
obj=tk.Tk()
obj.title("grid layout")
a=[]
for m in range(0,36):
n=str(m+1)
a.append(n)
k=0
for i in range(0,6):
for j in range(0,6):
b1=tk.Button(obj,text=a[k])
b1.grid(row=i,column=j)
k+=1
obj.mainloop()
Save:- “74.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
Program:
76A.py
from tkinter import *
win=Tk()
b=Button(win,text="Absolute Placement").place(x=50,y=100)
b1=Button(win,text="Relative").place(x=70,y=120)
win.mainloop()
76B.py
from tkinter import *
root=Tk()
root.title("Geometry Manager place Example")
root.geometry("500x500")
btn_height=Button(root,text="50px high")
btn_height.place(height=50,x=200,y=200)
btn_width=Button(root,text="60px wide")
btn_width.place(width=60,x=300,y=300)
btn_relheight=Button(root,text="Relheight of 0.6")
btn_relwidth=Button(root,text="Relwidth of 0.2")
btn_relwidth.place(relwidth=0.2)
btn_relx=Button(root,text="Relx of 0.3")
btn_relx.place(relx=0.3)
btn_rely=Button(root,text="Rely of 0.7")
btn_rely.place(rely=0.7)
btn_x=Button(root,text="X=400px")
btn_x.place(x=400)
btn_y=Button(root,text="Y=321")
btn_y.place(y=321)
root.mainloop()
Save:- “76.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
Program:
from tkinter import *
from tkinter import messagebox
w=Tk()
def fun():
messagebox.showinfo("hello","red button clicked")
b=Button(w,text="Green").pack(side=TOP,ipady=3,ipadx=2)
b=Button(w,text="Red",command=fun,activebackground="pink",activeforeground="red").p
ack(side=LEFT,ipady=3,ipadx=2)
b=Button(w,text="Blue").pack(side=RIGHT,ipady=3,ipadx=2)
b=Button(w,text="Yellow").pack(side=BOTTOM,ipady=3,ipadx=2)
mainloop()
Save:- “77.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
Program:
from tkinter import *
top=Tk()
top.title("Canvas Example")
#top.geometry("1000x800")
c=Canvas(top,bg="yellow",height="500",width=500)
arc=c.create_arc((5,10,100,150),start=0,extent=150,fill="red")
oval=c.create_oval((220,100,400,10),fill="blue")
poly=c.create_polygon((150,200,100,200,150,70),fill="green")
line=c.create_line((300,200,200,200),fill="black")
c.pack()
top.mainloop()
Save:- “78.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
79. Aim:Write a python program that accepts two numbers from the entry widget and
display their sum, difference, multiplication, division and remainder in result entry box
when clicking on corresponding buttons.
Program:
Program:
from tkinter import *
top=Tk()
top.geometry("140x100")
frame=Frame(top)
frame.pack()
leftframe=Frame(top)
leftframe.pack(side=LEFT)
rightframe=Frame(top)
rightframe.pack(side=RIGHT)
btn1=Button(frame,text='submit',fg='red',activebackground='yellow')
btn1.pack(side=LEFT)
btn2=Button(frame,text='remove',fg='brown',activebackground='yellow')
btn2.pack(side=RIGHT)
btn3=Button(rightframe,text='add',fg='blue',activebackground='blue')
btn3.pack(side=LEFT)
btn4=Button(leftframe,text='modify',fg='pink',activebackground='pink')
btn4.pack(side=RIGHT)
top.mainloop()
Save:- “82.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Program:
from tkinter import *
top=Tk()
top.title("label frame widget example")
labelframe1=LabelFrame(top,text="positive comments")
labelframe1.pack(fill="both",expand="yes")
toplabel=Label(labelframe1,text="place to put the positive comments")
toplabel.pack()
labelframe2=LabelFrame(top,text="negative comments")
labelframe2.pack(fill="both",expand="yes")
bottomlabel=Label(labelframe2,text="place to put the negative comments")
bottomlabel.pack()
top.mainloop()
Save:- “83.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
85. Aim:Write a python program to create a window with a menu bar and sub menu
items using Menu widget.
Program:
from tkinter import Toplevel, Button, Tk, Menu
top = Tk()
#sample.txt file:
#hello good morning!! hello good morning!! hello good morning!! hello good morning!!
97B.py
import re
pattern = re.compile(r'(Cats|Dogs)')
string_a = pattern.sub("Pets", "Dogs are a man's best friend.")
string_b = pattern.sub("Animals", "Cats enjoy sleeping.")
print(string_a)
print(string_b)
97C.py
import re
str="welcome to Regular Expression Module!"
sub="\s"
l=re.split(sub,str)
print(l)
97D.py
import re
name="Hello pk bhai!"
print(re.search("Hello",name,))#search the entire string
print(re.match("pk",name))#search from the beginning or else returns None
print(re.search("HELLO",name,re.IGNORECASE))
print(re.search("HELoO",name,re.IGNORECASE))
print(re.match("Hello pk",name))
# seek(n) takes the file handle to the nthbite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Save:- “101.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Save:- “103.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
f1 = open(firstfile, 'r')
f2 = open(secondfile, 'r')
f1.close()
f2.close()
f1 = open(firstfile, 'a+')
f2 = open(secondfile, 'r')
f1.write(f2.read())
f1.seek(0)
f2.seek(0)
f1.close()
f2.close()
Save:- “104.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
After:
CRUD-create,read,update,delete
Creating Operation......
Table student created successfully...
('name', 'varchar(30)', 'YES', '', None, '')
('pin', 'varchar(20)', 'NO', 'PRI', None, '')
('age', 'int(2)', 'YES', '', None, '')
3 records inserted
Reading Operation.....
('Gopichand', '19001-cm-212', 19)
('Divya Bharathi', '19001-cm-213', 18)
('Poojitha', '19001-cm-244', 19)
Updating operation.....
1 records affected
Delete Operation......
1 records affected
Save:- “108.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
1 record inserted
Save:- “109.py”
Method II:
A. Steps to enable I2C interface in Raspbian OS PI board using GUI:
Firstly go to the Start Menu then, select Preferences and then select and open Raspberry
Pi Configuration.
Menu>Preferences>RaspberryPiConfiguration.
Now a popup Raspberry Pi Configuration Window will appear
Then go to Interfacing tab and select Enable for 12C.
Click on the OK button to save.
Now it’s time to restart the Raspberry Pi to apply changes.