PS Python
PS Python
T. Y. B. B. A. (C.A.) Semester V
Practical Slip
Name: Mahesh Kumar
Roll No. :84
Seat No. : ______
Division: B
Subject: Python
1
CERTIFICATE
This is to certify that
Mr. MAHESH KUMAR
Seat Number: of T.Y.B.B.A. (C.A) Sem-V has Successfully
Completed Laboratory
Course (Python) in the year.
He/she has scored mark out of 10(For Lab Book).
2
Practical Slip 1
Q 1. A) Write a Python program to accept n numbers in list and
remove duplicates from a list.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
[Link](element)
b = set()
unique = []
for x in a:
if x not in b:
[Link](x)
[Link](x)
print("Non-duplicate items:")
print(unique)
OUTPUT:-
Enter the number of elements in list:5
Enter element1:12
Enter element2:3
Enter element3:4
Enter element4:5
Enter element5:3
Non-duplicate items:
[12, 3, 4, 5]
3
B) Write Python GUI program to take accept your birthdate and
output your age when a button is pressed.
today = [Link]()
day_check = (([Link], [Link]) < ([Link], [Link]))
if __name__ == "__main__":
print("Simple Age Calculator")
birthYear = int(input("Enter the birth year: "))
birthMonth = int(input("Enter the birth month: "))
birthDay = int(input("Enter the birth day: "))
OUTPUT:-
Simple Age Calculator
Enter the birth year: 2003
Enter the birth month: 12
Enter the birth day: 15
Age: 20 Years 3 Months and 7 days
4
Practical Slip 2
A) Write a Python function that accepts a string and calculate the
number of upper case letters and lower case letters. Sample String:
'The quick Brown Fox' Expected Output: No. of Upper case
characters: 3 No. of Lower case characters: 13
def string_test(s):
d = {"UPPER_CASE": 0, "LOWER_CASE": 0}
for c in s:
if [Link]():
d["UPPER_CASE"] += 1
elif [Link]():
d["LOWER_CASE"] += 1
else:
pass
print("Original String: ", s)
print("No. of Upper case characters: ", d["UPPER_CASE"])
print("No. of Lower case Characters: ", d["LOWER_CASE"])
string_test('The quick Brown Fox')
5
clock_label.config(text=current_time)
[Link](1000, update_time) # Update every 1000 milliseconds
(1 second)
root = [Link]()
[Link]("Digital Clock")
clock_label = [Link](root, text="", font=("Helvetica", 48))
clock_label.pack(padx=20, pady=20)
update_time()
[Link]()
OUPUT:-
6
Practical Slip 3
A). Write a Python program to check if a given key already exists in
a dictionary. If key exists replace with another key/value pair.
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)
OUPUT:-
Key is present in the dictionary
Key is not present in the dictionary
7
B) Write a python script to define a class student having members
roll no, name, age, gender. Create a subclass called Test with
member marks of 3 subjects. Create three objects of the Test class
and display all the details of the student with total marks.
class Student():
def __init__(self,roll_no,name,age,gender):
self.roll_no=roll_no
[Link]=name
[Link]=age
[Link]=gender
class Test(Student):
def__init__(self,roll_no,name,age,gender,sub1mark,sub2mark,sub
3mark,):
super().__init__(roll_no,name,age,gender)
self.mark1=sub1mark
self.mark2=sub2mark
self.mark3=sub3mark
def get_marks(self):
[Link]=self.mark1+self.mark2+self.mark3
print([Link] , "\b's marks:", [Link])
print("sub1 marks :",self.mark1)
print("sub2 marks :",self.mark2)
print("sub3 marks :",self.mark3)
8
p1=Test(1,"Mahesh",20,'male',98,99,96)
p2=Test(2,'Manisha',19,'female',78,81,74)
p1.get_marks()
p2.get_marks()
OUTPUT
Mahesh's marks: 293
sub1 marks : 98
sub2 marks : 99
sub3 marks : 96
Manisha's marks: 233
sub1 marks : 78
sub2 marks : 81
sub3 marks : 74
9
Practical Slip 4
A) Write Python GUI program to create background with changing
colors from tkinter import Button, Entry, Label, Tk
def changecolor():
newvalue = [Link]()
[Link](background = newvalue)
gui=Tk()
[Link]("color change.")
[Link](background = "gray")
[Link]("400x300")
color = Label(gui, text = "color", bg = "gray")
value = Entry(gui)
apply = Button(gui, text = "Apply", fg = "Black", bg = "gray",
command = changecolor)
[Link](row=0,column=0)
[Link](row=0,column=1)
[Link](row=0,column=2)
[Link]()
OUPUT:-
10
B) Define a class Employee having members id, name, department,
salary. Create a subclass called manager with member bonus.
Define methods accept and display in both the classes. Create n
objects of the manager class and display the details of the manager
having the maximum total salary (salary+bonus).
class Employee:
def __init__(self, id, name, department, salary):
[Link]=id
[Link]=name
[Link]=department
[Link]=salary
class manager(Employee):
def __init__(self, id, name, department, salary ,bonus):
super(manager, self).__init__(id, name, department, salary)
[Link]=bonus
def totalsalary(self):
print([Link],'got total salary :',[Link]+[Link])
n=manager('A023','MAHESH','GENERAL
MANAGEMENT',200000,8000)
m=manager('A025','MANISHA','MARKETIG',25000,6400)
[Link]()
[Link]()
OUPUT:-
MAHESH got total salary : 208000
MANISHA got total salary : 31400
11
Practical Slip 5
A) Write a Python script using class, which has two methods
get_String and print_String. get_String accept a string from the user
and print_String print the string in upper case. [15 M]
class Str1():
def __init__(self,demo=0):
[Link]=demo
def set_String(self,demo):
[Link]=demo
def print_streing(self):
str=[Link]
print([Link]())
A=Str1()
rowinput=input('enter a string :')
A.set_String(rowinput)
A.print_streing()
OUPUT:-
enter a string :hii mahesh
HII MAHESH
12
B) Write a python script to generate Fibonacci terms using
generator function.
def generator(r):
a=0;b=1
for i in range (1,r):
print(b)
a,b=b,a+b
13
Practical Slip 6
A) Write python script using package to calculate area and volume
of cube and sphere.
import math
class cube():
def __init__(self,edge):
[Link]=edge
def cube_area(self):
cubearea=6*[Link]*[Link]
print("Area of cube :",cubearea)
def cube_volume(self):
cubevolume=[Link]*[Link]*[Link]
print("Volume of cube :",cubevolume)
class sphere():
def __init__(self,radius):
[Link]=radius
def sphere_area(self):
spherearea=4*[Link]*[Link]*[Link]
print("Area of sphere :",spherearea)
14
def sphere_volume(self):
spherevolume=float(4/3*[Link]*[Link]**3)
print("volume of sphere :",spherevolume)
e1=cube(5)
e1.cube_area()
e1.cube_volume()
r1=sphere(5)
r1.sphere_area()
r1.sphere_volume()
OUPUT:-
Area of cube : 150
Volume of cube : 125
Area of sphere : 314.1592653589793
volume of sphere : 523.5987755982989
15
B) Write a Python GUI program to create a label and change the
label font style (font name, bold, size). Specify separate check
button for each style.
import tkinter as tk
parent = [Link]()
[Link]("-Welcome to Python tkinter Basic exercises-")
my_label = [Link](parent, text="Hello", font=("Arial Bold", 70))
my_label.grid(column=0, row=0)
[Link]()
OUPUT:-
16
Practical Slip 7
A) Write Python class to perform addition of two complex numbers
using binary + operator overloading.
class Complex ():
def initComplex(self):
[Link] = int(input("Enter the Real Part: "))
[Link] = int(input("Enter the Imaginary Part: "))
def display(self):
print([Link],"+",[Link],"i", sep="")
c1 = Complex()
c2 = Complex()
c3 = Complex()
17
print("Enter second complex number")
[Link]()
print("Second Complex Number: ", end="")
[Link]()
18
B) Write python GUI program to generate a random password with
upper and lower case letters.
import string,random
from tkinter import *
def password():
clearAll()
String = [Link](string.ascii_letters, 6) +
[Link]([Link], 4)
[Link]().shuffle(String)
password=''.join(String)
[Link](10, str(password))
def clearAll() :
[Link](0, END)
if __name__ == "__main__" :
gui = Tk()
[Link](background = "light pink")
[Link]("random password")
[Link]("325x150")
19
passField = Entry(gui);[Link]()
[Link]()
OUPUT:-
20
Practical Slip 8
A) Write a python script to find the repeated items of a tuple
import collections
tuplex = 2,4,5,6,2,3,4,4,7,5,6,7,1
dictx=[Link](int)
for x in tuplex:
dictx[x]+=1
for x in sorted(dictx,key=[Link]):
if dictx[x]>1:
print('%d repeted %d times'%(x,dictx[x]))
2 repeted 2 times
5 repeted 2 times
6 repeted 2 times
7 repeted 2 times
4 repeted 3 times
21
B) Write a Python class which has two methods get_String and
print_String. get_String accept a string from the user and
print_String print the string in upper case. Further modify the
program to reverse a string word by word and print it in lower case.
class Str1():
def __init__(self,demo=0):
[Link]=demo
def set_String(self,demo):
demo=[Link]()
[Link]=demo
def print_streing(self):
return [Link]
A=Str1()
str1=input('enter a string to display :')
A.set_String(str1)
print('Upper string :',A.print_streing())
OUPUT:-
enter a string to display :hii i am mahesh kumar
Upper string : HII I AM MAHESH KUMAR
22
Practical Slip 9
A) Write a Python script using class to reverse a string word by
word def reverse_words(s):
return ' '.join(reversed([Link]()))
def perfect():
number=int([Link]())
count = 0
for i in range(1, number):
if number % i == 0:
count = count + i
if count == number:
[Link]()
print(number, 'The number is a Perfect number!')
else:
23
[Link]()
print(number, 'The number is not a Perfect number!')
def armstrong():
number=int([Link]())
count = 0
temp = number
while temp > 0:
digit = temp % 10
count += digit ** 3
temp //= 10
if number == count:
[Link]()
print(number, 'is an Armstrong number')
else:
[Link]()
print(number, 'is not an Armstrong number')
def prime():
number=int([Link]())
if number > 1:
for i in range(2,number):
if (number % i) == 0:
[Link]()
24
print(number,"is not a prime number")
print(i,"times",number//i,"is",number)
break
else:
[Link]()
print(number,"is a prime number")
else:
[Link]()
print(number,"is not a prime number")
root=Tk()
[Link]('Prime, Perfect or Armstrong number')
[Link]('300x200')
numberFeald=Entry(root)
[Link]()
Button1=Button(root,text='Button',command=lambda:[armstrong(),
prime(),perfect()])
[Link]()
prime2=IntVar()
perfect2=IntVar()
armstrong2=IntVar()
25
armstrong1=Radiobutton(root,text='armstrong',variable=armstrong2
,value=1)
prime1=Radiobutton(root,text='prime',variable=prime2,value=1)
perfect1=Radiobutton(root,text='perfect',variable=perfect2,value=1)
[Link]()
[Link]()
[Link]()
[Link]()
OUPUT:-
26
Practical Slip 10
A) Write Python GUI program to display an alert message when a
button is pressed.
from tkinter import *
from tkinter import messagebox
def clicked():
[Link]('Button','Button is pressed.')
root=Tk()
[Link]('300x200')
word= Label(root,text='messagebox from button')
Button1=Button(root,text='BUTTON',command=clicked)
[Link]()
[Link]()
[Link]()
OUPUT:-
27
B) Write a Python class to find validity of a string of parentheses, '(',
')', '{', '}', '[' ']’. These brackets must be close in the correct order.
for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are
invalid.
class py_solution:
def is_valid_parenthese(self, str1):
stack, pchar = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in str1:
if parenthese in pchar:
[Link](parenthese)
elif len(stack) == 0 or pchar[[Link]()] != parenthese:
return False
return len(stack) == 0
print(py_solution().is_valid_parenthese("(){}[]"))
print(py_solution().is_valid_parenthese("()[{)}"))
print(py_solution().is_valid_parenthese("()"))
OUPUT:-
True
False
True
28
Practical Slip 11
A) Write a Python program to compute element-wise sum of given
tuples. Original lists: (1, 2, 3, 4) (3, 5, 2, 1) (2, 2, 3, 1) Element-wise
sum of the said tuples: (6, 9, 8, 6) [15 M]
x = (1,2,3,4);y = (3,5,2,1);z = (2,2,3,1)
print("Original lists:")
print(x)
print(y)
print(z)
OUPUT:-
29
B)Write Python GUI program to add menu bar with name of colors
as options to change the background color as per selection from
menu option.
from tkinter import Menu, Tk, mainloon
def redcolor():
[Link](background = 'red')
def greencolor():
[Link](background = 'green')
def yellowcolor():
[Link](background = 'yellow')
def violetcolor():
[Link](background = 'violet')
def bluecolor():
[Link](background = 'blue')
def cyancolor():
[Link](background = 'cyan')
root = Tk()
[Link]('COLOR MENU')
menubar = Menu(root)
30
color.add_command(label ='Red', command =
redcolor,activebackground='red',
activeforeground='cyan')
color.add_command(label ='Green',command =
greencolor,activebackground='green',
activeforeground='blue')
color.add_command(label ='Blue',command =
bluecolor,activebackground='blue',
activeforeground='yellow')
color.add_command(label ='Yellow',command =
yellowcolor,activebackground='yellow',
activeforeground='blue')
color.add_command(label ='Cyan',command =
cyancolor,activebackground='cyan',
activeforeground='red')
color.add_command(label ='Violet',command =
violetcolor,activebackground='violet',
activeforeground='green')
color.add_separator()
color.add_command(label ='Exit',command = [Link])
31
[Link](menu = menubar)
mainloop()
OUPUT:-
32
Practical Slip 12
A) Write a Python GUI program to create a label and change the
label font style (font name, bold, size) using tkinter module. [15 M]
from tkinter import Label, Tk
top=Tk()
[Link]="font style"
label=Label(top,text="this is text with style",font=("Helvetica",25))
[Link]()
[Link]()
OUPUT:-
33
Practical Slip 13
A) Write a Python program to input a positive integer. Display
correct message for correct and incorrect input. (Use Exception
Handling)
try:
num=int(input('Enter a number :'))
except ValueError:
print("\nThis is not a number!")
else:
print('\nnumber is : ',num)
OPT
Enter a number :2
number is : 2
B) Write a program to implement the concept of queue using list.
q=[]
[Link](10)
print("Initial Queue is:",q)
[Link](100)
print("Initial Queue is:",q)
[Link](1000)
print("Initial Queue is:",q)
[Link](10000)
34
print("Initial Queue is:",q)
35
Practical Slip 14
A) Write a Python GUI program to accept dimensions of a cylinder
and display the surface area and volume of cylinder. from tkinter
import *
from math import pi
from tkinter import messagebox
def clearAll() :
[Link](0, END)
[Link](0, END)
[Link](0, END)
[Link](0,END)
def checkError() :
if ([Link]() == "" or [Link]() == "") :
[Link]("Input Error")
clearAll()
return -1
def result() :
value = checkError()
if value == -1 :
return
else :
36
Radius = int([Link]())
Height = int([Link]())
volume=round(pi*Height*Radius**2,2)
area=round((2*pi*Radius*Height)+(2*pi*Radius**2),2)
[Link](10, str(volume))
[Link](10, str(area))
if __name__ == "__main__" :
gui = Tk()
[Link](background = "light green")
[Link]("cylinder surface area and volume of cylinder")
[Link]("300x175")
radius = Label(gui, text = " give radius", bg = "#00ffff")
height = Label(gui, text = "give height", bg = "#00ffff")
area = Label(gui, text = "Area", bg = "#00ffff")
volume = Label(gui, text = "Volume", bg = "#00ffff")
37
volumeField = Entry(gui)
areaField =Entry(gui)
[Link](row = 0, column = 0)
[Link](row = 0, column = 2)
[Link](row = 2, column = 0)
[Link](row = 2, column = 2)
[Link](row = 4, column = 1)
[Link](row = 5, column = 1)
[Link](row = 1, column = 0)
[Link](row = 1, column = 2)
[Link](row=3,column=0)
[Link](row = 3, column = 2)
[Link](row = 6, column = 1)
[Link]()
OUPUT:-
38
B) Write a Python program to display plain text and cipher text
using a Caesar encryption.
OUPUT:-
Enter a string : MAHESH KUMAR
ENtER number to shift pattern encript : 2
Plain txt : MAHESH KUMAR
Shift pattern : 2
Cipher: PDKHVKqWDQYL
39
Practical Slip 15
A) Write a Python class named Student with two attributes
student_name, marks. Modify the attribute values of the said class
and print the original and modified values of the said attributes.
class Student:
def __init__(self, Student_name, marks):
self.Student_name=Student_name
[Link]=marks
def get_marks(self):
print("\nOriginal name and values")
print(self.Student_name,'marks : ',[Link])
def modify_marks(self):
self.Student_name1=input('Enter modifyed name : ')
self.marks1=int(input('Enter modifyed marks : '))
print(self.Student_name1,'modifyed marks',[Link])
def modifyed_marks(self):
print("\nmodified name and values")
print(self.Student_name1,'marks : ',self.marks1)
x=Student('AMAR',81)
x.get_marks()
x.modify_marks()
x.get_marks()
x.modifyed_marks()
40
OUPUT:-
Original name and values
AMAR marks : 81
Enter modifyed name : MAHESH
Enter modifyed marks : 99
MAHESH modifyed marks 81
41
B) Write a python program to accept string and remove the
characters which have odd index values of given string using user
defined function.
def removeodd(string):
str2=''
for x in range(len(string)):
if x%2==0:
str2=str2+string[x]
return str2
str1=input('enter a string : ')
print('String after removing char : ',removeodd(str1))
OUPUT:-
enter a string : MAHESH
String after removing char : MHS
42
Practical Slip 16
A) Write a python script to create a class Rectangle with data
member’s length, width and methods area, perimeter which can
compute the area and perimeter of rectangle.
class Ractangle():
def __init__(self,l,w):
self.l=l
self.w=w
def rectangle_area(self):
return self.l*self.w
def rectangle_Perimeter(self):
return (self.l*2)+(self.w*2)
OUPUT:-
enter Length of Rectangle :5
enter Width of Rectangle :6
30
22
43
B) Write Python GUI program to add items in listbox widget and to
print and delete the selected items from listbox on button click.
Provide three separate buttons to add, print and delete.
import tkinter as tk
def add_item():
item = [Link]()
if item:
[Link]([Link], item)
[Link](0, [Link])
def print_item():
selected_index = [Link]()
if selected_index:
selected_item = [Link](selected_index[0])
print("selected item:", selected_item)
def delete_item():
selected_index= [Link]()
if selected_index:
[Link](selected_index[0])
root = [Link]()
[Link]("Listbox Example")
44
entry = [Link](root)
[Link]()
listbox = [Link](root)
[Link]()
[Link]()
OPT
45
Practical Slip 17
A) Write Python GUI program that takes input string and change
letter to upper case when a button is pressed.
from tkinter import *
from tkinter import messagebox
def clearAll() :
[Link](0, END)
[Link](0, END)
def checkError() :
if ([Link]() == "" ) :
[Link]("Input Error")
clearAll()
return -1
def upper() :
value = checkError()
if value == -1 :
return
else :
String0 = ([Link]())
newstr=[Link]()
[Link](20, str(newstr))
if __name__ == "__main__" :
gui = Tk()
[Link](background = "light green")
46
[Link]("upper case")
[Link]("250x200")
Stringin = Label(gui, text = " given String", bg = "#00ffff")
str1 = Label(gui, text = "String", bg = "light green")
str1Field = Entry(gui)
result = Button(gui, text = "Result", fg = "Black",
bg = "gray", command = upper)
alters = Label(gui, text = "upper case string", bg = "light green")
altersField = Entry(gui)
clearAllEntry = Button(gui, text = "Clear All", fg = "Black",
bg = "Red", command = clearAll)
[Link](row = 0, column = 1)
[Link](row = 1, column = 0)
[Link](row = 1, column = 1)
[Link](row = 2, column = 0)
[Link](row = 2, column = 1)
[Link](row = 3, column = 0)
[Link](row = 3, column = 1)
[Link]()
OUPUT:-
47
B) Define a class Date (Day, Month, Year) with functions to accept
and display it. Accept date from user. Throw user defined exception
“invalid Date Exception” if the date is invalid.
class date:
def acceptdate(self):
[Link]=int(input("Enter Day: "))
[Link]=int(input("Enter Month: "))
[Link]=int(input("Enter Year: "))
def printdate(self):
try:
if([Link]>31):
raise Exception("Day value is greater than 31")
if([Link]>12):
raise Exception("Month value is greater than 12") if([Link]<0):
raise Exception("Year value should not be negative")
print("Date: ",[Link],"-",[Link],"-",[Link])
except Exception as e:
print(e)
objdate=date()
[Link]()
[Link]()
OUPUT:-
Enter Day: 12
Enter Month: 03
Enter Year: 2023 Date: 12 - 3 – 2023
48
Practical Slip 18
A) Create a list a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a
python program that prints out all the elements of the list that are
less than 5
list1 =[]
list3=[]
list2=[]
n=int(input('Enter number of elements : '))
for i in range(n):
value=int(input())
[Link](value)
print(list1)
n=int(input('Enter a number to sort list : '))
for i in list1:
if n > i:
[Link](i)
else:
[Link](i)
print('less then {} value list : '.format(n),list2)
print('greater then {} value list :'.format(n),list3)
OUPUT:-
Enter number of elements : 2
3
4
[3, 4]
49
B) Write a python script to define the class person having members
name, address. Create a subclass called Employee with members
staffed salary. Create 'n' objects of the Employee class and display
all the details of the employee.
class person:
def __init__(self,name,address):
[Link]=name
[Link]=address
def display(self):
print('name : {}\taddress : {}\tsalary : {}'.format([Link],
[Link],[Link]()))
class employee(person):
def __init__(self, name, address,salary):
super().__init__(name, address)
[Link]=salary
def getsalary(self):
return [Link]
name1=input('enter name : ')
address=input('enter address : ')
salary=int(input('enter salary : '))
a=employee(name1,address,salary)
[Link]()
OUPUT:-
enter name : mahesh
enter address : abc
enter salary : 98000
name : mahesh address : abc salary : 98000
50
Practical Slip 19
A) Write a Python GUI program to accept a number form user and
display its multiplication table on button click.
from tkinter import *
def clearAll() :
[Link](0, END);[Link](0,END)
def multiplication():
num = int([Link]())
[Link](0, '{} X 1 = {}'.format(num,1*num))
[Link](1, '{} X 2 = {}'.format(num,2*num))
[Link](2, '{} X 3 = {}'.format(num,3*num))
[Link](3, '{} X 4 = {}'.format(num,4*num))
[Link](4, '{} X 5 = {}'.format(num,5*num))
[Link](5, '{} X 6 = {}'.format(num,6*num))
[Link](6, '{} X 7 = {}'.format(num,7*num))
[Link](7, '{} X 8 = {}'.format(num,8*num))
[Link](8, '{} X 9 = {}'.format(num,9*num))
[Link](9,'{} X 10 = {}'.format(num,10*num))
if __name__=="__main__" :
gui = Tk()
[Link](background = "light green")
[Link]("multiplication table")
[Link]("400x300")
51
label=Label(gui,text='multiplication table \
on button click').pack(side=TOP,fill=BOTH)
number = Label(gui, text = "Give number", bg =
"#00ffff").pack(fill=BOTH)
numberField = Entry(gui)
[Link]()
resultbutton = Button(gui, text = "Result button",
fg = "Black", bg = "gray",command=multiplication).pack()
Lb1 =
Listbox(gui,fg='yellow',width=30,bg='gray',bd=1,activestyle='dotbox')
clearAllEntry = Button(gui, text = "Clear All",
fg = "Black", bg = "gray", command =
clearAll).pack(side=BOTTOM)
[Link]()
[Link]()
OUPUT:-
52
B) Define a class named Shape and its subclass(Square/ Circle). The
subclass has an init function which takes an argument
(Lenght/redious). Both classes should have methods to calculate
area and volume of a given shape.
class Shape:
pass
class Square(Shape):
def __init__(self,l2):
self.l=l2
def SArea(self):
a=self.l * self.l
print("Area of Square:", a)
def SPerimeter(self):
p=4 * self.l
print("Perimeter of Square:",p)
class Circle(Shape):
def __init__(self,r2):
self.r=r2
def CArea(self):
a=3.14 * self.r * self.r
print("Area of Circle:", a)
def SCircumference(self):
c=2 * 3.14 * self.r
print("Circumference of Circle:",c)
#main body
53
l1=int(input("Enter Length of Square: "))
obj=Square(l1)
[Link]()
[Link]()
r1=int(input("Enter Radius of Circle: "))
obj=Circle(r1)
[Link]()
[Link]()
OUPUT:-
Enter Length of Square: 3
Area of Square: 9
Perimeter of Square: 12
Enter Radius of Circle: 4
Area of Circle: 50.24
Circumference of Circle: 25.12
54
Practical Slip 20
A) Write a python program to create a class Circle and Compute the
Area and the circumferences of the circle.(use parameterized
constructor)
from math import pi
class Circle():
def __init__(self,Radius):
[Link]=Radius
def area(self):
a=pi*[Link]*[Link]
return round(a,2)
def circumference(self):
c=2*[Link]*pi
return round(c,2)
OUPUT:-
enter radius of circle : 4
Area of circle is : 50.27
Circumference of circle is : 25.13
55
B) Write a Python script to generate and print a dictionary which
contains a number (between 1 and n) in the form(x,x*x). Sample
Dictionary (n=5) Expected Output: {1:1, 2:4, 3:9, 4:16, 5:25}
def create_dict(n):
mydict=dict()
for i in range(1,n+1):
mydict[i]=i*i
return mydict
n=int(input("Enter size of dictionary: "))
dictionary=create_dict(n)
print(dictionary)
OUPUT:-
Enter size of dictionary: 5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
56
Practical Slip 21
A) Define a class named Rectangle which can be constructed by a
length and width. The Rectangle class has a method which can
compute the area and Perimeter.
class Ractangle():
def __init__(self,l,w):
self.l=l
self.w=w
def rectangle_area(self):
return self.l*self.w
def rectangle_Perimeter(self):
return (self.l*2)+(self.w*2)
OUPUT:-
enter Length of Rectangle :3
enter Width of Rectangle :4
12
14
57
B) Write a Python program to convert a tuple of string values to a
tuple of integer values. Original tuple values: (('333', '33'), ('1416',
'55')) New tuple values: ((333, 33), (1416, 55))
mytuple=(('333','33'),('1416','55'))
mylist=list()
[Link](list(mytuple[0]))
[Link](list(mytuple[1]))
list2=list()
for i in range(len(mylist)):
list3=list()
for j in range(len(mylist)):
[Link](int(mylist[i][j]))
[Link](tuple(list3))
print(f"Original Tuple: {mytuple}")
print(f"Modified Tuple: {list2}")
OUPUT:-
Original Tuple: (('333', '33'), ('1416', '55'))
Modified Tuple: [(333, 33), (1416, 55)]
58
Practical Slip 22
A) Write a python class to accept a string and number n from user
and display n repetition of strings by overloading * operator.
class StringRepeater:
def__init__(self, input_string):
self.input_string = input_string
def__mul__(self, n):
if isinstance(n, int):
return self.input_string* n
else: raise ValueError("The repetition factor should be an integer")
user_input_string = input("Enter a string: ")
repetition_factor = int(input("Enter the repetition factor (an integer):
"))
repeater = StringRepeater(user_input_string)
result = repeater * repetition_factor
print("Result:", result)
59
B) Write a python script to implement bubble sort using list
def bubble_sort(list1):
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1
list1 =[]
n=int(input('Enter number of elements : '))
for i in range(n):
value=int(input())
[Link](value)
print("The unsorted list is: ", list1)
print("The sorted list is: ", bubble_sort(list1))
OUPUT:-
Enter number of elements : 3
3
4
5
The unsorted list is: [3, 4, 5]
The sorted list is: [3, 4, 5]
60
Practical Slip 23
A) Write a Python GUI program to create a label and change the
label font style (font name, bold, size) using tkinter module.
import tkinter as tk
root = [Link]()
[Link]("Bold Label Example1 ")
label = [Link](root, text="Hello GFG - Message 1 ")
[Link](font=("Helvetica", 12, "bold"))
[Link](pady=20)
[Link]()
OUPUT:-
61
B) Create a class circles having members radius. Use operator
overloading to add the radius of two circle objects. Also display the
area of circle.
import math
class Circle:
def__init__(self, radius):
self__radius = radius
def setRadius(self, radius):
self __ radius = radius
def getRadius(self):
return self__radius
def area(self):
return [Link]* self__radius ** 2
def__add__(self, another_circle):
return Circle(self__radius + another_circle__radius)
c1 = Circle(4)
print([Link]())
c2 = Circle(5)
print([Link]())
c3 = c1 + c2
print([Link]())
62
Practical Slip 24
A) Write a Python Program to Check if given number is prime or
not. Also find factorial of the given no using user defined function.
def Prime(num):
flag=0
for i in range(2,num):
if num%i==0 :
flag=1
break
if flag==0:
print("Number is Prime")
else:
print("Number is Not Prime")
def Fact(num):
f=1
for i in range(1,num+1):
f=f*i
print("Factorial of Given number is:",f)
#main body
n=int(input("Enter any number to Check:"))
Prime(n)
Fact(n)
OUPUT:-
Enter any number to Check:7
Number is Prime
Factorial of Given number is: 5040
63
B) Write Python GUI program which accepts a number n to displays
each digit of number in words.
from tkinter import END, Button, Entry, Label, Tk
def printWord(N):
i=0
length = len(N)
while i < length:
printValue(N[i])
i += 1
def printValue(digit):
if digit == '0':
[Link](30,'ZERO ')
elif digit == '1':
[Link](30,'ONE ')
elif digit == '2':
[Link](30,'TWO ')
elif digit=='3':
[Link](30,'THREE ')
elif digit == '4':
[Link](30,'FOUR ')
elif digit == '5':
[Link](30,'FIVE ')
64
elif digit == '6':
[Link](30,'SIX ')
elif digit == '7':
[Link](30,'SEVEN ')
elif digit == '8':
[Link](30,'EIGHT ')
elif digit == '9':
[Link](30,'NINE ')
def clearAll() :
[Link](0, END)
[Link](0, END)
def wordconvert():
number0 = [Link]()
printWord(number0)
if __name__=="__main__" :
gui = Tk()
[Link](background = "light green")
[Link]("decimal number converter")
[Link]("300x125")
number = Label(gui, text = "Give number", bg = "#00ffff")
number1 = Label(gui, text = "number", bg = "light green")
numberField = Entry(gui)
result = Label(gui, text = "result", bg = "#00ffff")
65
resultbutton = Button(gui, text = "Result button",fg = "Black",
bg = "gray", command = wordconvert)
numberinword = Label(gui, text ="number in word",bg ="light
green")
wordField = Entry(gui)
clearAllEntry = Button(gui, text = "Clear All", fg ="Black",
bg = "gray", command = clearAll)
[Link](row = 0, column = 1)
[Link](row = 1, column = 1)
[Link](row = 2, column = 1)
[Link](row = 3, column = 1)
[Link](row = 0, column = 5)
[Link](row = 1, column = 5)
[Link](row = 2, column = 5)
[Link](row = 3, column = 5)
[Link]()
OUPUT:-
66
Practical Slip 25
A) Write a Python function that accepts a string and calculate the
number of upper case letters and lower case letters. Sample String :
'The quick Brow Fox' Expected Output : No. of Upper case
characters : 3 No. of Lower case Characters : 12
string=input('enter a string : ')
up=low=ele=0
for x in string:
if [Link]():
up+=1
elif [Link]():
low+=1
else:
ele+=1
print('No. of Upper case characters : ',up)
print('No. of Lower case characters : ',low)
print('other special symbols',ele)
OUPUT:-
enter a string : Hii I am Mahesh Kumar
No. of Upper case characters : 4
No. of Lower case characters : 13
other special symbols 4
67
B) Write a Python script to Create a Class which Performs Basic
Calculator Operations.
class Calculator:
def __init__(self,num1,num2,operation):
self.num1=num1
self.num2=num2
[Link]=operation
if [Link]=='*':
print('Multiplication of {} and {} is : '.format(num1,num2),
self.num1*self.num2)
elif [Link]=='/':
print('division of {} and {} is : '.format(num1,num2),
self.num1/self.num2)
elif [Link]=='-':
print('Subtraction of {} and {} is : '.format(num1,num2),
self.num1/self.num2)
elif [Link]=='+':
print('Addition of {} and {} is : '.format(num1,num2),
self.num1+self.num2)
68
operator1=input('ENTER A CALCULATOR OPERATOR FROM
FOLLOWING : / , * , - , +\n')
num2=int(input('Enter 2st number : '))
Calculator(num1,num2,operator1)
OUPUT:-
Enter 1st number : 34
ENTER A CALCULATOR OPERATOR FROM FOLLOWING : / , * , - , +
*
Enter 2st number : 45
Multiplication of 34 and 45 is : 1530
69
Practical Slip 26
A) Write an anonymous function to find area of square and
rectangle.
area_square=lambda x: x*x
side=int(input('Enter a side value of square : '))
print(area_square(side))
area_rectangle=lambda x,y:x*y
Length=int(input('Enter a Length value of rectangle : '))
Width=int(input('Enter a Width value of rectangle : '))
print(area_rectangle(Length,Width))
OUPUT:-
Enter a side value of square : 4
16
Enter a Length value of rectangle : 3
Enter a Width value of rectangle : 4
12
70
def clearAll() :
[Link](0, END)
[Link](0, END)
def checkError() :
if ([Link]() == "" ) :
[Link]("Input Error")
clearAll()
return -1
def occurrences() :
value = checkError()
if value == -1 :
return
else :
String0 = ([Link]())
newstr=''
for char in String0:
if [Link]():
char=[Link]()
newstr+=char
elif [Link]():
71
char=[Link]()
newstr+=char
elif char==' ':
char=[Link](' ','*')
newstr+=char
elif [Link]():
char=[Link](char,'?')
newstr+=char
else:
newstr+=char
[Link](10, str(newstr))
if __name__ == "__main__" :
gui = Tk()
[Link](background = "light green")
[Link]("alters")
[Link]("250x200")
72
bg = "gray", command = occurrences)
[Link](row = 0, column = 1)
[Link](row = 1, column = 0)
[Link](row = 1, column = 1)
[Link](row = 2, column = 0)
[Link](row = 2, column = 1)
[Link](row = 3, column = 0)
[Link](row = 3, column = 1)
[Link]()
OUPUT:-
73
Practical Slip 27
A) Write a Python program to unzip a list of tuples into individual
lists.
l = [(1,2), (3,4), (8,9)]
print(list(zip(*l)))
OUPUT:-
[(1, 3, 8), (2, 4, 9)]
def calculateAge() :
74
value = checkError()
if value == -1 :
return
else :
number0 = int([Link]())
binary=(bin(number0)[2:])
octal =oct(number0)[2:]
hexadecimal=hex(number0)[2:]
[Link](10, str(binary))
[Link](10, str(octal))
[Link](10, str(hexadecimal))
if __name__ == "__main__" :
gui = Tk()
[Link](background = "light green")
[Link]("decimal number converter")
[Link]("400x200")
number = Label(gui, text = "Give number", bg = "#00ffff")
number1 = Label(gui, text = "number", bg = "light green")
numberField = Entry(gui)
result = Label(gui, text = "result", bg = "#00ffff")
resultbutton = Button(gui, text = "Result button", fg = "Black",
bg = "gray", command = calculateAge)
75
resultoctal = Label(gui, text = "result cotal", bg = "light green")
resulthexadecimal = Label(gui,text ="resulthexadecimal",bg = "light
green")
binaryField = Entry(gui)
octalField = Entry(gui)
hexadecimalField = Entry(gui)
clearAllEntry = Button(gui, text = "Clear All", fg = "Black",
bg = "Red", command = clearAll)
[Link](row = 0, column = 1)
[Link](row = 1, column = 1)
[Link](row = 2, column = 1)
[Link](row = 3, column = 1)
[Link](row = 4, column = 1)
[Link](row = 5, column = 0)
[Link](row = 6, column = 0)
[Link](row = 5, column = 1)
[Link](row = 6, column = 1)
[Link](row = 5, column = 2)
[Link](row = 6, column = 2)
[Link](row = 7, column = 1)
[Link]()
OUPUT:-
76
Practical Slip 28
A) Write a Python GUI program to create a list of Computer Science
Courses using Tkinter module (use Listbox).
from tkinter import *
top = Tk()
[Link]('Course')
[Link]("300x250")
Lb1 =
Listbox(top,fg='yellow',width=30,bg='gray',bd=1,activestyle='dotbox')
label=Label(top,text='Computer Science Course Listing').pack()
[Link](1, "Computer Programming")
[Link](2, "Information Science")
[Link](3, "Networking")
[Link](4, "Operating Systems")
[Link](5, "Artificial Intelligence")
[Link](6, "Information Technology")
[Link](7,'Information Security')
[Link](8, "Cyber Security")
[Link]()
[Link]()
OPT:-
77
B) Write a Python program to accept two lists and merge the two
lists into list of tuple.
list1 =[]
n=int(input('Enter number of elements in first list : '))
for i in range(n):
value=int(input('enter {} value of list : '.format(i+1)))
[Link](value)
list2 =[]
n=int(input('Enter number of elements in second list : '))
for i in range(n):
value=int(input('enter {} value of list : '.format(i+1)))
[Link](value)
print('list 1 : ',list1)
78
print('list 2 : ',list2)
tuple1=tuple(list1+list2)
print(tuple1)
OUPUT:-
Enter number of elements in first list : 3
enter 1 value of list : 1
enter 2 value of list : 2
enter 3 value of list : 3
Enter number of elements in second list : 3
enter 1 value of list : 1
enter 2 value of list : 2
enter 3 value of list : 4
list 1 : [1, 2, 3]
list 2 : [1, 2, 4]
(1, 2, 3, 1, 2, 4)
79
Practical Slip 29
A) Write a Python GUI program to calculate volume of Sphere by
accepting radius as input.
from tkinter import *
from tkinter import messagebox
import math
def clearAll() :
[Link](0, END)
[Link](0, END)
def checkError() :
if ([Link]() == "") :
[Link]("Input Error")
clearAll()
return -1
def getvolume() :
value = checkError()
if value == -1 :
return
else :
radius0 = int([Link]())
volume0=round((4/3)*[Link]*radius0*radius0*radius0,2)
80
[Link](10, str(volume0))
if __name__ == "__main__" :
gui = Tk()
[Link](background = "light green")
[Link]("volume of sphere")
[Link]("425x200")
radiusField = Entry(gui)
volumeField = Entry(gui)
81
[Link](row = 0, column = 1)
[Link](row = 1, column = 0)
[Link](row = 1, column = 1)
[Link](row = 0, column = 4)
[Link](row = 1, column = 3)
[Link](row = 1, column = 4)
[Link](row = 4, column = 2)
[Link](row = 12, column = 2)
[Link]()
OUPUT:-
82
B) Write a Python script to sort (ascending and descending) a
dictionary by key and value.
dict1 = {}
n=int (input('Enter a number or pair in dict :'))
for i in range(n):
key=input('enter {0} key :'.format(i+1))
value=input('enter value of {}:'.format(key))
dict1[key]=value
sorted_result = dict(sorted([Link]()))
print("\nSorting key in alphabetically ascending order:-")
print(sorted_result)
83
OUPUT:-
Enter a number or pair in dict :2
enter 1 key :APPLE
enter value of APPLE:200
enter 2 key :MANGO
enter value of MANGO:120
84
Practical Slip 30
A) Write a Python GUI program to accept a string and a character
from user and count the occurrences of a character in a string.
from tkinter import *
from tkinter import messagebox
def clearAll() :
[Link](0, END)
[Link](0, END)
[Link](0, END)
def checkError() :
if ([Link]() == "" or [Link]() == "") :
[Link]("Input Error")
clearAll()
return -1
def occurrences() :
value = checkError()
if value == -1 :
return
else :
String0 = ([Link]())
char0 = ([Link]())
85
i=0
count=0
while(i<len(String0)):
if(String0[i]==char0):
count=count+1
i=i+1
[Link](10, str(count))
if __name__ == "__main__" :
gui = Tk()
[Link](background = "light green")
[Link]("occurrences of a character in a string")
[Link]("525x260")
86
occurrenceslabel = Label(gui, text = "occurrences \n character",
bg = "light green")
str1Field = Entry(gui)
char1Field = Entry(gui)
resultField = Entry(gui)
[Link](row = 0, column = 1)
[Link](row = 1, column = 0)
[Link](row = 1, column = 1)
[Link](row = 0, column = 4)
[Link](row = 1, column = 3)
[Link](row = 1, column = 4)
[Link](row = 4, column = 2)
[Link](row = 5, column = 2)
[Link](row = 6, column = 2)
87
[Link](row = 12, column = 2)
[Link]()
OUPUT:-
88
B) Python Program to Create a Class in which One Method Accepts
a String from the User and Another method Prints it. Define a class
named Country which has a method called print Nationality. Define
subclass named state from Country which has a mehtod called
printState. Write a method to print state, country and nationality.
class stringmethod():
def __init__(self):
[Link]=""
def get(self):
[Link]=input("Enter string: ")
def put(self):
print("String is:")
print([Link])
obj=stringmethod()
[Link]()
[Link]()
OUPUT:-
Enter string: MAHESH KUMAR
String is:
MAHESH KUMAR
*****
89
90