Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Slips

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Slips

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Slip 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) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)
Output:
Enter the number of elements in list:4
Enter element1:10
Enter element2:20
Enter element3:30
Enter element4:10
Non-duplicate items:
[10, 20, 30]

B) Write Python GUI program to take accept your birthdate and output your age when a button
is pressed.
from tkinter import *
from tkinter import messagebox
def clearAll():
dayField.delete(0, END)
monthField.delete(0, END)
yearField.delete(0, END)
givenDayField.delete(0, END)
givenMonthField.delete(0, END)
givenYearField.delete(0, END)
rsltDayField.delete(0, END)
rsltMonthField.delete(0, END)
rsltYearField.delete(0, END)

def calculateAge() :
birth_day = int(dayField.get())
birth_month = int(monthField.get())
birth_year = int(yearField.get())
given_day = int(givenDayField.get())
given_month = int(givenMonthField.get())
given_year = int(givenYearField.get())
month =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (birth_day > given_day):
given_month = given_month - 1
given_day = given_day + month[birth_month-1]
if (birth_month > given_month):
given_year = given_year - 1
given_month = given_month + 12
calculated_day = given_day - birth_day;
calculated_month = given_month - birth_month;
calculated_year = given_year - birth_year;
rsltDayField.insert(10, str(calculated_day))
rsltMonthField.insert(10, str(calculated_month))
rsltYearField.insert(10, str(calculated_year))

if __name__== "__main__":
gui = Tk()
gui.configure(background = "light green")
gui.title("Age Calculator")
gui.geometry("525x260")
dob = Label(gui, text = "Date Of Birth", bg = "blue")
givenDate = Label(gui, text = "Given Date", bg = "blue")
day = Label(gui, text = "Day", bg = "light green")
month = Label(gui, text = "Month", bg = "light green")
year = Label(gui, text = "Year", bg = "light green")
givenDay = Label(gui, text = "Given Day", bg = "light green")
givenMonth = Label(gui, text = "Given Month", bg = "light green")# Create a Given
Year : label
givenYear = Label(gui, text = "Given Year", bg = "light green")
rsltYear = Label(gui, text = "Years", bg = "light green")
rsltMonth = Label(gui, text = "Months", bg = "light green")
rsltDay = Label(gui, text = "Days", bg = "light green")
resultantAge = Button(gui, text = "Resultant Age", fg = "Black", bg = "Red",
command = calculateAge)
clearAllEntry = Button(gui, text = "Clear All", fg = "Black", bg = "Red", command =
clearAll)
dayField = Entry(gui)
monthField = Entry(gui)
yearField = Entry(gui)
givenDayField = Entry(gui)
givenMonthField = Entry(gui)
givenYearField = Entry(gui)
rsltYearField = Entry(gui)
rsltMonthField = Entry(gui)
rsltDayField = Entry(gui)
dob.grid(row = 0, column = 1)
day.grid(row = 1, column = 0)
dayField.grid(row = 1, column = 1)
month.grid(row = 2, column = 0)
monthField.grid(row = 2, column = 1)
year.grid(row = 3, column = 0)
yearField.grid(row = 3, column = 1)
givenDate.grid(row = 0, column = 4)
givenDay.grid(row = 1, column = 3)
givenDayField.grid(row = 1, column = 4)
givenMonth.grid(row = 2, column = 3)
givenMonthField.grid(row = 2, column = 4)
givenYear.grid(row = 3, column = 3)
givenYearField.grid(row = 3, column = 4)
resultantAge.grid(row = 4, column = 2)
rsltYear.grid(row = 5, column = 2)
rsltYearField.grid(row = 6, column = 2)
rsltMonth.grid(row = 7, column = 2)
rsltMonthField.grid(row = 8, column = 2)
rsltDay.grid(row = 9, column = 2)
rsltDayField.grid(row = 10, column = 2)
clearAllEntry.grid(row = 12, column = 2) # Start the GUI
gui.mainloop()

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 c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
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"])
str1=input("Enter the string you want: ")
string_test(str1)
Output:-
Enter the string you want: Hello I Am TYBBA(CA) Student
Original String : Hello I Am TYBBA(CA) Student
No. of Upper case characters : 11
No. of Lower case Characters : 11
B. Write Python GUI program to create a digital clock with Tkinter to display the time
import time
from tkinter import *
canvas = Tk()
canvas.title("Digital Clock")
canvas.geometry("350x200")
canvas.resizable(1,1)
label = Label(canvas, font=("Courier", 30, 'bold'), bg="red", fg="white", bd =30)
label.grid(row =0, column=1)
def digitalclock():
text_input = time.strftime("%H:%M:%S %p")
label.config(text=text_input)
label.after(200, digitalclock)
digitalclock()
canvas.mainloop()

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={'A':1,'B':2,'C':3}
key=input("Enter key to check:")
check_value = input("Enter Value: ")
if key in d.keys():
print("Key is present and value of the key is:")
print(d[key])
d.pop(key)
d[key]=check_value
else:
print("Key isn't present!")
d[key]=check_value
print("Updated dictionary : ",d)
Output:
Enter key to check:A
Enter Value: 4
Key is present and value of the key is:
1
Updated dictionary: {'B': 2, 'C': 3, 'A': '4'}
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 GetStudent(self):
self.RollNo=int(input("\nEnter Student Roll No:"))
self.Name=input("Enter Student Name:")
self.Age=int(input("Enter Student Age:"))
self.Gender=input("Enter Student Gender:")
def PutStudent(self):
print("Student Roll No:",self.RollNo)
print("Student Name:",self.Name)
print("Student Age:",self.Age)
print("Student Gender:",self.Gender)
class Test(Student):
def GetMarks(self):
self.MarkMar=int(input("Enter Marks of Marathi Subject"))
self.MarkHin=int(input("Enter Marks of Hindi Subject"))
self.MarkEng=int(input("Enter Marks of Eglish Subject"))
def PutMarks(self):
print("Marathi Marks:", self.MarkMar)
print("Hindi Marks:", self.MarkHin)
print("English Marks:", self.MarkEng)
print("Total Marks:",self.MarkMar+self.MarkHin+self.MarkEng)

n=int(input("Enter How may students"))


lst=[]
for i in range(0,n):
obj=input("Enter Object Name:")
lst.append(obj)
print(lst)
for j in range(0,n):
lst[j]=Test()
lst[j].GetStudent()
lst[j].GetMarks()
print("\nDisplay Details of Student",j+1)
lst[j].PutStudent()
lst[j].PutMarks()
Output:
Enter How may students2
Enter Object Name:A
['A']
Enter Object Name:B
['A', 'B']
Enter Student Roll No:101
Enter Student Name:Priti
Enter Student Age:10
Enter Student Gender:F
Enter Marks of Marathi Subject10
Enter Marks of Hindi Subject20
Enter Marks of Eglish Subject30
Display Details of Student 1
Student Roll No: 101
Student Name: Priti
Student Age: 10
Student Gender: F
Marathi Marks: 10
Hindi Marks: 20
English Marks: 30
Total Marks: 60
Enter Student Roll No:201
Enter Student Name:Suhas
Enter Student Age:20
Enter Student Gender:M
Enter Marks of Marathi Subject30
Enter Marks of Hindi Subject40
Enter Marks of Eglish Subject50

Display Details of Student 2


Student Roll No: 201
Student Name: Suhas
Student Age: 20
Student Gender: M
Marathi Marks: 30
Hindi Marks: 40
English Marks: 50
Total Marks: 120

Slip 4:
A: Write Python GUI program to create background with changing colors
from tkinter import Button, Entry, Label, Tk
def changecolor():
n = value.get()
gui.configure(background = n)
gui=Tk()
gui.title("color change.")
gui.configure(background = "gray")
gui.geometry("400x300")
color = Label(gui, text = "color", bg = "gray")
value = Entry(gui)
apply = Button(gui, text = "Apply", fg = "Black", bg = "gray", command=changecolor)
color.grid(row=0,column=0)
value.grid(row=0,column=1)
apply.grid(row=0,column=2)
gui.mainloop()

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 AcceptEmp(self):
self.Id=int(input("Enter emp id:"))
self.Name=input("Enter emp name:")
self.Dept=input("Enter emp Dept:")
self.Sal=int(input("Enter emp Salary:"))
def DisplayEmp(self):
print("Emp id:",self.Id)
print("Emp Name:",self.Name)
print("Emp Dept:",self.Dept)
print("Emp Salary:",self.Sal)

class Manager(Employee):

def AcceptMgr(self):
self.bonus=int(input("Enter Manager Bonus"))
def DisplayMgr(self):
self.TotalSal=0
print("Manger Bonus is:",self.bonus)
self.TotalSal=self.Sal+self.bonus
print("Total Salary: ", self.TotalSal)

n=int(input("Enter How may Managers:"))


lst=[]
for i in range(0,n):
obj=input("Enter Object Name:")
lst.append(obj)
print(lst)
for j in range(0,n):
lst[j]=Manager()
lst[j].AcceptEmp()
lst[j].AcceptMgr()
print("\nDisplay Details of Manager",j+1)
lst[j].DisplayEmp()
lst[j].DisplayMgr()
maxTotalSal= lst[0].TotalSal
maxIndex=0
for j in range(1,n):
if lst[j].TotalSal > maxTotalSal:
maxTotalSal= lst[j].TotalSal
maxIndex=j
print("\nDisplay Details of Manager Having Maximum Salary(Salary+Bonus)")
lst[maxIndex].DisplayEmp()
lst[maxIndex].DisplayMgr()

Slip5:
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.

class IOString():
def __init__(self):
self.str1 = ""

def get_String(self):
self.str1 = input()

def print_String(self):
print(self.str1.upper())

str1 = IOString()
str1.get_String()
str1.print_String()

Output:
Hello i am TYBBA(CA) Student
HELLO I AM TYBBA(CA) STUDEN

B: Write a python script to generate Fibonacci terms using generator function.


nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Output:
How many terms? 6
Fibonacci sequence:
0
1
1
2
3
5

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):
self.edge=edge

def cube_area(self):
cubearea=6*self.edge*self.edge
print("Area of cube :",cubearea)

def cube_volume(self):
cubevolume=self.edge*self.edge*self.edge
print("Volume of cube :",cubevolume)

class sphere():
def __init__(self,radius):
self.radius=radius

def sphere_area(self):
spherearea=4*math.pi*self.radius*self.radius
print("Area of sphere :",spherearea)

def sphere_volume(self):
spherevolume=float(4/3*math.pi*self.radius**3)
print("volume of sphere :",spherevolume)

e1=cube(5)
e1.cube_area()
e1.cube_volume()
r1=sphere(5)
r1.sphere_area()
r1.sphere_volume()
Output:
Area of cube : 150
Volume of cube : 125
Area of sphere : 314.1592653589793
volume of sphere : 523.5987755982989
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
import tkinter.font as tkFont
class App:
def __init__(self):
root=tk.Tk()
# create a custom font
self.customFont = tkFont.Font(family="Helvetica", size=12)
# create a couple widgets that use that font
buttonframe = tk.Frame()
label = tk.Label(root, text="Hello, world", font=self.customFont)
text = tk.Text(root, width=20, height=2, font=self.customFont)
buttonframe.pack(side="top", fill="x")
label.pack()
text.pack()
text.insert("end","press +/- buttons to change\nfont size")
bigger = tk.Button(root, text="+", command=self.OnBigger)
smaller = tk.Button(root, text="-", command=self.OnSmaller)
bigger.pack(in_=buttonframe, side="left")
smaller.pack(in_=buttonframe, side="left")
root.mainloop()
def OnBigger(self):
'''Make the font 2 points bigger'''
size = self.customFont['size']
self.customFont.configure(size=size+2)
def OnSmaller(self):
'''Make the font 2 points smaller'''
size = self.customFont['size']
self.customFont.configure(size=size-2)
app=App()

Slip 7:
A: Write Python class to perform addition of two complex numbers using binary + operator
overloading.
class Complex ():
def initComplex(self):
self.realPart = int(input("Enter the Real Part: "))
self.imgPart = int(input("Enter the Imaginary Part: "))
def display(self):
print(self.realPart,"+",self.imgPart,"i", sep="")
def sum(self, c1, c2):
self.realPart = c1.realPart + c2.realPart
self.imgPart = c1.imgPart + c2.imgPart
c1 = Complex()
c2 = Complex()
c3 = Complex()
print("Enter first complex number")
c1.initComplex()
print("First Complex Number: ", end="")
c1.display()
print("Enter second complex number")
c2.initComplex()
print("Second Complex Number: ", end="")
c2.display()
print("Sum of two complex numbers is ", end="")
c3.sum(c1,c2)
c3.display()

Output:
Enter first complex number
Enter the Real Part: 8
Enter the Imaginary Part: 4
First Complex Number: 8+4i
Enter second complex number
Enter the Real Part: 3
Enter the Imaginary Part: 2
Second Complex Number: 3+2i
Sum of two complex numbers is 11+6i

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 = random.sample(string.ascii_letters, 6)+random.sample(string.digits, 4)
random.SystemRandom().shuffle(String)
password=''.join(String)
passField.insert(10, str(password))
def clearAll() :
passField.delete(0, END)
if __name__=="__main__":
gui = Tk()
gui.configure(background = "light green")
gui.title("random password")
gui.geometry("325x150")
passin = Label(gui, text = "Password", bg = "#00ffff").pack()
passField = Entry(gui);
passField.pack()
result = Button(gui,text = "Result",fg = "Black", bg = "gray", command
=password).pack()
clearAllEntry = Button(gui,text = "Clear All",fg = "Black",bg = "Red", command =
clearAll).pack()
gui.mainloop()
Output:-

Slip 8:
A: Write a python script to find the repeated items of a tuple

t=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
t.append(element)
lst=[]
print("Repeated elements in given tuple ")
for i in range(0, len(t)):
if t.count(t[i])>1 :
if t[i] not in lst:
lst.append(t[i])
print(t[i])
Output:
Enter the number of elements in list:3
Enter element1:10
Enter element2:20
Enter element3:10
Repeated elements in given tuple
10

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 MyClass:
def Get_String(self):
self.MyStr=input("Enter any String: ")
def Print_String(self):
s=self.MyStr
print("String in Upper Case: " , s.upper())
cnt=len(s)
i=cnt-1
RevStr=""
while(i >= 0):
RevStr=RevStr + s[i]
i=i-1
print("String in Reverse & Lower case:" , RevStr.lower())

obj=MyClass()
obj.Get_String()
obj.Print_String()
Output:
Enter any String: Priti
String in Upper Case: PRITI
String in Reverse & Lower case: itirp

Slip 09:
A: Write a Python script using class to reverse a string word by word
class MyClass:
def Get_String(self):
self.MyStr=input("Enter any String: ")
def Print_String(self):
s=self.MyStr
cnt=len(s)
i=cnt-1
RevStr=""
while(i >= 0):
RevStr=RevStr + s[i]
i=i-1
print("String in Reverse:" , RevStr)

obj=MyClass()
obj.Get_String()
obj.Print_String()
Output:
Enter any String: Hello
String in Reverse: olleH

B: Write Python GUI program to accept a number n and check whether it is Prime, Perfect or
Armstrong number or not. Specify three radio buttons.
from tkinter import*
def perfect():
number=int(numberFeald.get())
count = 0
for i in range(1, number):
if number % i == 0:
count = count + i
if count == number:
perfect1.select()
print(number, 'The number is a Perfect number!')
else:
perfect1.deselect()
print(number, 'The number is not a Perfect number!')
def armstrong():
number=int(numberFeald.get())
count = 0
temp = number
while temp > 0:
digit = temp % 10
count += digit ** 3
temp //= 10
if number == count:
armstrong1.select()
print(number, 'is an Armstrong number')
else:
armstrong1.deselect()
print(number, 'is not an Armstrong number')

def prime():
number=int(numberFeald.get())
if number > 1:
for i in range(2,number):
if (number % i) == 0:
prime1.deselect()
print(number,"is not a prime number")
print(i,"times",number//i,"is",number)
break
else:
prime1.select()
print(number,"is a prime number")
else:
prime1.deselect()
print(number,"is not a prime number")

root=Tk()
root.title('Prime, Perfect or Armstrong number')
root.geometry('300x200')
numberFeald=Entry(root)
numberFeald.pack()
Button1=Button(root,text='Button',command=lambda:[armstrong(),prime(),perfect()])
Button1.pack()
prime2=IntVar()
perfect2=IntVar()
armstrong2=IntVar()
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)
armstrong1.pack()
prime1.pack()
perfect1.pack()
root.mainloop()
6 The number is a Perfect number!

Slip 10:
A: Write Python GUI program to display an alert message when a button is pressed.

import tkinter.messagebox
def onClick():
tkinter.messagebox.showinfo("Title goes here","Message goes here")
root = tkinter.Tk()
button = tkinter.Button(root,text = "Click Me", command = onClick)
button.pack()
root.mainloop()
Output:

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:
def is_valid_parenthese(self, str1):
stack, pchar = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in str1:
if parenthese in pchar:
stack.append(parenthese)
elif len(stack) == 0 or pchar[stack.pop()] != parenthese:
return False
return len(stack) == 0
print(py().is_valid_parenthese("(){}[]"))
print(py().is_valid_parenthese("[)({[)]"))
print(py().is_valid_parenthese("{{{"))
Output:
True
False
False

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)
x = (1,2,3,4)
y = (3,5,2,1)
z = (2,2,3,1)
print("list data is: ")
print(x)
print(y)
print(z)
print("After adding list eleemnt is: ")
result = tuple(map(sum, zip(x, y, z)))
print(result)
Output:
list data is:
(1, 2, 3, 4)
(3, 5, 2, 1)
(2, 2, 3, 1)
After adding list eleemnt is:
(6, 9, 8, 6)

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 *
app = Tk()
app.title("Menu Color Change")
app.geometry("300x300")
menubar = Menu(app, background='blue', fg='white')
file = Menu(menubar, tearoff=False, background='yellow')
edit = Menu(menubar, tearoff=False, background='pink')
file.add_command(label="New")
file.add_command(label="Exit", command=app.quit)
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
menubar.add_cascade(label="File", menu=file)
menubar.add_cascade(label="Edit", menu=edit)
app.config(menu=menubar)
app.mainloop()

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.
import tkinter as tk
parent = tk.Tk()
parent.title("-Welcome to Python tkinter Basic exercises-")
my_label = tk.Label(parent, text="Hello", font=("Arial Bold", 70))
my_label.grid(column=0, row=0)
parent.mainloop()

B: Write a python program to count repeated characters in a string. Sample string:


'thequickbrownfoxjumpsoverthelazydog' Expected output: o-4, e-3, u-2, h-2, r-2, t-2
import collections
str1=input("Enter the string you want: ")
d = collections.defaultdict(int)
for c in str1:
d[c] += 1
for c in sorted(d, key=d.get, reverse=True):
if d[c] > 1:
print('%s %d' % (c, d[c]))
Output:
Enter the string you want: Hello I Am TYBBA(CA) Student
4
A3
e2
l2
B2
t2

Slip 13:
A: Write a Python program to input a positive integer. Display correct message for correct and
incorrect input. (Use Exception Handling)
num = int (input("Enter Any Positive number:"))
try:
if num >= 0:
raise ValueError("Positive Number-Input Number is Correct")
else:
raise ValueError("Positive Number-Input Number is InCorrect")
except ValueError as e:
print(e)
Output:
Enter Any Positive number:10
Positive Number-Input Number is Correct

Enter Any Positive number:-20


Positive Number-Input Number is InCorrect

B: Write a program to implement the concept of queue using list.


q=[]
def Insert():
if len(q)==size:
print("Queue is Full!!!!")
else:
element=input("Enter the element:")
q.append(element)
print(element,"is added to the Queue!")
def Delete():
if len(q)==0:
print("Queue is Empty!!!")
else:
e=q.pop(0)
print("element removed!!:",e)
def display():
print(q)
size=int(input("Enter the size of Queue:"))
while True:
print("\nSelect the Operation: 1.Insert 2.Delete 3.Display 4.Quit")
choice=int(input())
if choice==1:
Insert()
elif choice==2:
Delete()
elif choice==3:
display()
elif choice==4:
break
else:
print("Invalid Option!!!")
Output:
Enter the size of Queue:2
Select the Operation: 1.Insert 2.Delete 3.Display 4.Quit
1
Enter the element:10
10 is added to the Queue!
Select the Operation: 1.Insert 2.Delete 3.Display 4.Quit
1
Enter the element:20
20 is added to the Queue!
Select the Operation: 1.Insert 2.Delete 3.Display 4.Quit
1
Queue is Full!!!!
Select the Operation: 1.Insert 2.Delete 3.Display 4.Quit
3
['10', '20']
Select the Operation: 1.Insert 2.Delete 3.Display 4.Quit
2
element removed!!: 10
Select the Operation: 1.Insert 2.Delete 3.Display 4.Quit
4

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() :
RadiusField.delete(0, END)
HeightField.delete(0, END)
volumeField.delete(0, END)
areaField.delete(0,END)

def result() :
Radius = int(RadiusField.get())
Height = int(HeightField.get())
volume=round(pi*Height*Radius**2,2)
area=round((2*pi*Radius*Height)+(2*pi*Radius**2),2)
volumeField.insert(10, str(volume))
areaField.insert(10, str(area))

if __name__== "__main__" :
gui = Tk()
gui.configure(background = "light green")
gui.title("cylinder surface area and volume of cylinder")
gui.geometry("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")
resultlabel = Label(gui, text = "RESULT", bg = "#00ffff")
resultbutton = Button(gui, text = "Result", fg = "Black",bg = "gray", command =
result)
clearAllEntry = Button(gui, text = "Clear All", fg = "Black",bg = "Red", command =
clearAll)
RadiusField = Entry(gui)
HeightField = Entry(gui)
volumeField = Entry(gui)
areaField =Entry(gui)
radius.grid(row = 0, column = 0)
height.grid(row = 0, column = 2)
area.grid(row = 2, column = 0)
volume.grid(row = 2, column = 2)
resultlabel.grid(row = 4, column = 1)
resultbutton.grid(row = 5, column = 1)
RadiusField.grid(row = 1, column = 0)
HeightField.grid(row = 1, column = 2)
areaField.grid(row=3,column=0)
volumeField.grid(row = 3, column = 2)
clearAllEntry.grid(row = 6, column = 1)
gui.mainloop()
Output:-

B: Write a Python program to display plain text and cipher text using a Caesar encryption.
def encypt_func(txt, s):
result = ""
for i in range(len(txt)):
char = txt[i]
if (char.isupper()):
result += chr((ord(char) + s - 64) % 26 + 65)
else:
result += chr((ord(char) + s - 96) % 26 + 97)
return result
txt = input('Enter a string : ')
s = int(input('ENtER number to shift pattern encript : '))
print("Plain txt : " + txt)
print("Shift pattern : " + str(s))
print("Cipher: " + encypt_func(txt, s))

Output:
Enter a string : Hello i am TYBBA(CA) Student
ENtER number to shift pattern encript : 4
Plain txt : Hello i am TYBBA(CA) Student
Shift pattern : 4
Cipher: MjqqtsnsfrsYDGGFaHFbsXyzijsy
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 Accept(self):
self.name=input("Enter Student Name:")
self.mark=int(input("Enter Student Total Marks:"))
def Modify(self):
self.oldmark=self.mark
self.mark=int(input("Enter Student New Total Marks:"))
print("Student Name:",self.name)
print("Old Total Mark:",self.oldmark)
print("New Total Mark:",self.mark)
Stud1=Student()
Stud1.Accept()
Stud1.Modify()
Output:
Enter Student Name:Geeta
Enter Student Total Marks:67
Enter Student New Total Marks:78
Student Name: Geeta
Old Total Mark: 67
New Total Mark: 78

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 odd_values_string(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print("Enter the string you want: ")
str=input()
print(odd_values_string(str))
Output:
Enter the string you want:
Hello
Hlo

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 Rect:
def __init__(self,l2,w2):
self.l=l2
self.w=w2
def RectArea(self):
self.a=self.l * self.w
print("Area of Rectangle:", self.a)
def RectPer(self):
self.p=2*(self.l + self.w)
print("Perimeter of Rectangle:", self.p)

l1=int(input("Enter Length:"))
w1=int(input("Enter Width:"))
Obj=Rect(l1,w1)
Obj.RectArea()
Obj.RectPer()
Output:
Enter Length:2
Enter Width:3
Area of Rectangle: 6
Perimeter of Rectangle: 10

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.
from tkinter import *
def remove_item():
selected_checkboxs = listbox.curselection()
for selected_checkbox in selected_checkboxs[::-1]:
listbox.delete(selected_checkbox)
root = Tk()
root.geometry("200x200")
listbox = Listbox(root, selectmode=MULTIPLE)
listbox.pack()
items = ["Apple", "Orange", "Grapes", "Banana", "Mango"]
for item in items:
listbox.insert(END, item)
Button(root, text="delete", command=remove_item).pack()
root.mainloop()
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() :
str1Field.delete(0, END)
altersField.delete(0, END)

def checkError() :
if (str1Field.get() == "" ) :
messagebox.showerror("Input Error")
clearAll()
return -1

def upper() :
String0 = (str1Field.get())
newstr=String0.upper()
altersField.insert(20, str(newstr))

if __name__== "__main__" :
gui = Tk()
gui.configure(background = "light green")
gui.title("upper case")
gui.geometry("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)
Stringin.grid(row = 0, column = 1)
str1.grid(row = 1, column = 0)
str1Field.grid(row = 1, column = 1)
alters.grid(row = 2, column = 0)
altersField.grid(row = 2, column = 1)
clearAllEntry.grid(row = 3, column = 0)
result.grid(row = 3, column = 1)
gui.mainloop()

Output:-
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 MyDate:
def accept(self):
self.d=int(input("Enter Day:"))
self.m=int(input("Enter Month:"))
self.y=int(input("Enter Year:"))
def display(self):
try:
if self.d>31:
raise ValueError("Day value is greater than 31")
if self.m>12:
raise ValueError("Month Value is Greater than 12")
print("Date is: ", self.d, "-" ,self.m , "-",self.y )
except ValueError as e:
print(e)
Obj=MyDate()
Obj.accept()
Obj.display()
Output:
Enter Day:03
Enter Month:02
Enter Year:2022
Date is: 3 - 2 – 2022

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
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
new_list = []
for item in a:
if item < 5:
new_list.append(item)
print(new_list)
Output:
[1, 1, 2, 3]
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 GetPerson(self):
self.Name=input("\n Enter tne name of Person: ")
self.Address=input("Enter Address of Person: ")
def PutPerson(self):
print("Person Name:",self.Name)
print("Student Address:",self.Address)

class Employee(Person):
def GetSalary(self):
self.Sal=int(input("Enter Salary of Employee"))
def PutSalary(self):
print("Salary of Employee:",self.Sal)

n=int(input("Enter How may Employee: "))


lst=[]
for i in range(0,n):
obj=input("Enter Object Name:")
lst.append(obj)
print(lst)
for j in range(0,n):
lst[j]=Employee()
lst[j].GetPerson()
lst[j].GetSalary()
print("\nDisplay Details of Employee",j+1)
lst[j].PutPerson()
lst[j].PutSalary()
Output:
Enter How may Employee: 1
Enter Object Name:A
['A']

Enter tne name of Person: Priti


Enter Address of Person: Pune
Enter Salary of Employee1234

Display Details of Employee 1


Person Name: Priti
Student Address: Pune
Salary of Employee: 1234

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() :
numberField.delete(0, END);
Lb1.delete(0,END)

def multiplication():
num = int(numberField.get())
Lb1.insert(0, '{} X 1 = {}'.format(num,1*num))
Lb1.insert(1, '{} X 2 = {}'.format(num,2*num))
Lb1.insert(2, '{} X 3 = {}'.format(num,3*num))
Lb1.insert(3, '{} X 4 = {}'.format(num,4*num))
Lb1.insert(4, '{} X 5 = {}'.format(num,5*num))
Lb1.insert(5, '{} X 6 = {}'.format(num,6*num))
Lb1.insert(6, '{} X 7 = {}'.format(num,7*num))
Lb1.insert(7, '{} X 8 = {}'.format(num,8*num))
Lb1.insert(8, '{} X 9 = {}'.format(num,9*num))
Lb1.insert(9,'{} X 10 = {}'.format(num,10*num))

if __name__=="__main__":
gui = Tk()
gui.configure(background = "light green")
gui.title("multiplication table")
gui.geometry("400x300")
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)
numberField.pack()
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)
Lb1.pack()
gui.mainloop()

Output:

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)

l1=int(input("Enter Length of Square: "))


obj=Square(l1)
obj.SArea()
obj.SPerimeter()

r1=int(input("Enter Radius of Circle: "))


obj=Circle(r1)
obj.CArea()
obj.SCircumference()
Output:
Enter Length of Square: 2
Area of Square: 4
Perimeter of Square: 8
Enter Radius of Circle: 3
Area of Circle: 28.259999999999998
Circumference of Circle: 18.84

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)
class Circle():
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
def perimeter(self):
return 2*self.radius*3.14

NewCircle = Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())
Output:
200.96
50.24

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}
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Output:
Input a number 5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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 Rectangle:
def __init__(self, l, w):
self.length = l
self.width = w
def rectangle_area(self):
return self.length*self.width

newRectangle = Rectangle(12, 10)


print(newRectangle.rectangle_area())
Output:
120

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))
def Convert_Fun(tuple_str):
result = tuple((int(x[0]), int(x[1])) for x in tuple_str)
return result
tuple_str = (('333', '33'), ('1416', '55'))
print("Original tuple values:")
print(tuple_str)
print("\nNew tuple values:")
print(Convert_Fun(tuple_str))
Output:
Original tuple values:
(('333', '33'), ('1416', '55'))

New tuple values:


((333, 33), (1416, 55)

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.

Output

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 the how many element you want in list : "))
for i in range(0, n):
ele = int(input())
list1.append(ele)
print(list1)
print("The unsorted list is: ", list1)
print("The sorted list is: ", bubble_sort(list1))

Output
Enter the how many element you want in list : 3
20
10
40
[20, 10, 40]
The unsorted list is: [20, 10, 40]
The sorted list is: [10, 20, 40]

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
parent = tk.Tk()
parent.title("-Welcome to Python tkinter Basic exercises-")
my_label = tk.Label(parent, text="Hello", font=("Arial Bold", 70))
my_label.grid(column=0, row=0)
parent.mainloop()

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 get_result(self):
return self.radius

def area(self):
return math.pi * self.radius ** 2

def __add__(self, another_circle):


return Circle(self.radius + another_circle.radius)

def __sub__(self, another_circle):


return Circle(self.radius - another_circle.radius)

def __mul__(self, another_circle):


return Circle(self.radius * another_circle.radius)

def __gt__(self, another_circle):


return Circle(self.radius > another_circle.radius)

def __lt__(self, another_circle):


return Circle(self.radius < another_circle.radius)

def __ge__(self, another_circle):


return Circle(self.radius >= another_circle.radius)

def __le__(self, another_circle):


return Circle(self.radius <= another_circle.radius)

def __eq__(self, another_circle):


return Circle(self.radius == another_circle.radius)

def __ne__(self, another_circle):


return Circle(self.radius != another_circle.radius)

c1 = Circle(10)
print(c1.get_result())
print(c1.area())
c2 = Circle(15)
print(c2.get_result())
print(c1.area())
c3 = c1 + c2
print(c3.get_result())
c3 = c2 - c1
print(c3.get_result())
c4 = c1 * c2
print(c4.get_result())
c5 = c1 < c2
print(c5.get_result())
c5 = c2 < c1
print(c5.get_result())

Output:
10
314.1592653589793
15
314.1592653589793
25
5
150
True
False

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)
n=int(input("Enter any number to Check:"))
Prime(n)
Fact(n)

Output:
Enter any number to Check:3
Number is Prime
Factorial of Given number is: 6

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':
wordField.insert(30,'ZERO ')
elif digit == '1':
wordField.insert(30,'ONE ')
elif digit == '2':
wordField.insert(30,'TWO ')
elif digit=='3':
wordField.insert(30,'THREE ')
elif digit == '4':
wordField.insert(30,'FOUR ')
elif digit == '5':
wordField.insert(30,'FIVE ')
elif digit == '6':
wordField.insert(30,'SIX ')
elif digit == '7':
wordField.insert(30,'SEVEN ')
elif digit == '8':
wordField.insert(30,'EIGHT ')
elif digit == '9':
wordField.insert(30,'NINE ')

def clearAll() :
numberField.delete(0, END)
wordField.delete(0, END)
def wordconvert():
number0 = numberField.get()
printWord(number0)

if __name__=="__main__" :
gui = Tk()
gui.configure(background = "light green")
gui.title("decimal number converter")
gui.geometry("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")
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)
number.grid(row = 0, column = 1)
number1.grid(row = 1, column = 1)
numberField.grid(row = 2, column = 1)
resultbutton.grid(row = 3, column = 1)
result.grid(row = 0, column = 5)
numberinword.grid(row = 1, column = 5)
wordField.grid(row = 2, column = 5)
clearAllEntry.grid(row = 3, column = 5)
gui.mainloop()

Output:

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
def lowerupper(s):
count1=0
count2=0
for i in s:
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)

str=input("Enter string:")
lowerupper(str)

Output:MM
Enter string:Hello I am TYBBA(CA) Student
The number of lowercase characters is:
12
The number of uppercase characters is:
10

B: Write a Python script to Create a Class which Performs Basic Calculator Operations
class MathOp:
def AddOp(self):
self.a=int(input("Enter first no:"))
self.b=int(input("Enter Second no:"))
self.c= self.a + self.b
print("Addition is:",self.c)
def SubOp(self):
self.a=int(input("Enter first no:"))
self.b=int(input("Enter Second no:"))
self.c= self.a - self.b
print("Sub is:",self.c)
def MulOp(self):
self.a=int(input("Enter first no:"))
self.b=int(input("Enter Second no:"))
self.c= self.a * self.b
print("Addition is:",self.c)
print("Multiplication is:",self.c)
#main body
obj=MathOp()
while True:
print("\n1. Addtion")
print("2. Substraction")
print("3. Multiplication")
print("4. Exit")
ch=int(input("Enter choice to perform any opertaion"))
if ch==1:
obj.AddOp()
elif ch==2:
obj.SubOp()
elif ch==3:
obj.MulOp()
elif ch==4:
print("\nProgram Stop")
break
else:
print("Wrong Choice")

Output:

1. Addtion
2. Substraction
3. Multiplication
4. Exit
Enter choice to perform any opertaion1
Enter first no:10
Enter Second no:20
Addition is: 30

1. Addtion
2. Substraction
3. Multiplication
4. Exit
Enter choice to perform any opertaion4

Program Stop

Slip 26:
A: Write an anonymous function to find area of square and rectangle.
def areaOfSquare(s):
return s*s
def AreaofRectangle(width, height):
return width * height
print("Enter the Side Length of Square: ")
l = float(input())
print("Enter the Length of rectangle: ")
l1=float(input())
print("Enter the height of rectangle: ")
h=float(input())
a = areaOfSquare(l)
print("\nArea of Square is= {:.2f}".format(a))
a1 = AreaofRectangle(l1,h)
print("Area of a Rectangle is: %.2f" %a1)

Output:
Enter the Side Length of Square:
2
Enter the Length of rectangle:
3
Enter the height of rectangle:
2
Area of Square is= 4.00
Area of a Rectangle is: 6.00

B: Write Python GUI program which accepts a sentence from the user and alters it when a button is
pressed. Every space should be replaced by *, case of all alphabets should be reversed, digits are
replaced by?.
from tkinter import *
from tkinter import messagebox

def clearAll() :
str1Field.delete(0, END)
altersField.delete(0, END)

def occurrences() :
String0 = (str1Field.get())
newstr=''
for char in String0:
if char.isupper():
char=char.lower()
newstr+=char
elif char.islower():
char=char.upper()
newstr+=char
elif char==' ':
char=char.replace(' ','*')
newstr+=char
elif char.isdigit():
char=char.replace(char,'?')
newstr+=char
else:
newstr+=char
altersField.insert(10, str(newstr))

if __name__== "__main__" :
gui = Tk()
gui.configure(background = "light green")
gui.title("alters")
gui.geometry("250x200")
str1 = Label(gui, text = "String", bg = "light green")
str1Field = Entry(gui)
result = Button(gui, text = "Result", fg = "Black",bg = "gray", command =
occurrences)
alters = Label(gui, text = "alters string", bg = "light green")
altersField = Entry(gui)
clearAllEntry = Button(gui, text = "Clear All", fg = "Black",bg = "Red", command =
clearAll)
str1.grid(row = 1, column = 0)
str1Field.grid(row = 1, column = 1)
alters.grid(row = 2, column = 0)
altersField.grid(row = 2, column = 1)
clearAllEntry.grid(row = 3, column = 0)
result.grid(row = 3, column = 1)
gui.mainloop()

Output:

Slip 27:
A: Write a Python program to unzip a list of tuples into individual lists.
t = list(tuple(map(int,input().split())) for r in range(int(input('enter no of rows : '))))
print(t)
print("After the coversion of list: ")
print(list(zip(*t)))
Output:
enter no of rows: 3
10 20
30 40
50 60
[(10, 20), (30, 40), (50, 60)]
After the coversion of list:
[(10, 30, 50), (20, 40, 60)]

B: Write Python GUI program to accept a decimal number and convert and display it to binary,
octal and hexadecimal number.
from tkinter import *
from tkinter import messagebox
def clearAll() :
numberField.delete(0, END)
binaryField.delete(0, END)
octalField.delete(0, END)
hexadecimalField.delete(0, END)

def calculateAge() :
number0 = int(numberField.get())
binary=(bin(number0)[2:])
octal =oct(number0)[2:]
hexadecimal=hex(number0)[2:]
binaryField.insert(10, str(binary))
octalField.insert(10, str(octal))
hexadecimalField.insert(10, str(hexadecimal))

if __name__== "__main__" :
gui = Tk()
gui.configure(background = "light green")
gui.title("decimal number converter")
gui.geometry("400x200")
number1 = Label(gui, text = "number", bg = "light green")
numberField = Entry(gui)
resultbutton = Button(gui, text = "Result button", fg = "Black",bg = "gray", command
= calculateAge)
resultbinary = Label(gui, text = "result binary", bg = "light green")
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)
number1.grid(row = 1, column = 1)
numberField.grid(row = 2, column = 1)
resultbutton.grid(row = 4, column = 1)
resultbinary.grid(row = 5, column = 0)
binaryField.grid(row = 6, column = 0)
resultoctal.grid(row = 5, column = 1)
octalField.grid(row = 6, column = 1)
resulthexadecimal.grid(row = 5, column = 2)
hexadecimalField.grid(row = 6, column = 2)
clearAllEntry.grid(row = 7, column = 1)
gui.mainloop()

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()
top.title('Course')
top.geometry("300x250")
Lb1 =Listbox(top,fg='yellow',width=30,bg='gray',bd=1,activestyle='dotbox')
label=Label(top,text='Computer Science Course Listing').pack()
Lb1.insert(1, "Computer Programming")
Lb1.insert(2, "Information Science")
Lb1.insert(3, "Networking")
Lb1.insert(4, "Operating Systems")
Lb1.insert(5, "Artificial Intelligence")
Lb1.insert(6, "Information Technology")
Lb1.insert(7,'Information Security')
Lb1.insert(8, "Cyber Security")
Lb1.pack()
top.mainloop()

Output:-

B: Write a Python program to accept two lists and merge the two lists into list of tuple.
def merge(list1, list2):
merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))]
return merged_list
list1 = []
list2 = []
n = int(input("Enter number of elements of first list : "))
for i in range(0, n):
ele = int(input())
list1.append(ele)
print(list1)
n1 = int(input("Enter number of elements of second list : "))
for i in range(0, n1):
ele1 = int(input())
list2.append(ele1)
print(list2)
print("After the merging of two list")
print(merge(list1, list2))
Output:
Enter number of elements of first list : 3
10
20
30
[10, 20, 30]
Enter number of elements of second list : 3
20
30
40
[20, 30, 40]
After the merging of two list
[(10, 20), (20, 30), (30, 40)]

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() :
radiusField.delete(0, END)
volumeField.delete(0, END)

def getvolume() :
radius0 = int(radiusField.get())
volume0=round((4/3)*math.pi*radius0*radius0*radius0,2)
volumeField.insert(10, str(volume0))

if __name__== "__main__" :
gui = Tk()
gui.configure(background = "light green")
gui.title("volume of sphere")
gui.geometry("425x200")
Radius1 = Label(gui, text = "radius", bg = "light green")
volume1 = Label(gui, text = "volume", bg = "light green")
result = Button(gui, text = "Result", fg = "Black",bg = "gray", command = getvolume)
clearAllEntry = Button(gui, text = "Clear All", fg = "Black",bg = "Red", command =
clearAll)
radiusField = Entry(gui)
volumeField = Entry(gui)
Radius1.grid(row = 1, column = 0)
radiusField.grid(row = 1, column = 1)
volume1.grid(row = 1, column = 3)
volumeField.grid(row = 1, column = 4)
result.grid(row = 4, column = 2)
clearAllEntry.grid(row = 12, column = 2)
gui.mainloop()

Output:
B: Write a Python script to sort (ascending and descending) a dictionary by key and value.
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)

Output:
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Dictionary in ascending order by value : [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}

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() :
str1Field.delete(0, END)
char1Field.delete(0, END)
resultField.delete(0, END)

def occurrences() :
String0 = (str1Field.get())
char0 = (char1Field.get())
count=0
count= String0.count(char0)
resultField.insert(10,str(count))

if __name__== "__main__":
gui = Tk()
gui.configure(background = "light green")
gui.title("occurrences of a character in a string")
gui.geometry("525x260")
str1 = Label(gui, text = "String", bg = "light green")
char1 = Label(gui, text = "character", bg = "light green")
result = Button(gui, text = "Result", fg = "Black",bg = "gray", command =
occurrences)
clearAllEntry = Button(gui, text = "Clear All", fg = "Black",
bg = "Red", command = clearAll)
str1Field = Entry(gui)
char1Field = Entry(gui)
resultField = Entry(gui)
str1.grid(row = 1, column = 0)
str1Field.grid(row = 1, column = 1)
char1.grid(row = 1, column = 3)
char1Field.grid(row = 1, column = 4)
result.grid(row = 4, column = 2)
resultField.grid(row = 6, column = 2)
clearAllEntry.grid(row = 12, column = 2)
gui.mainloop()

Output:

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 Country:
def AcceptCountry(self):
self.cname=input("Enter Country Name: ")
def DisplayCountry(self):
print("Country Name is:", self.cname)
class State(Country):
def AcceptState(self):
self.sname=input("Enter State Name: ")
def DisplayState(self):
print("State Name is:", self.sname)

Obj=State()
Obj.AcceptCountry()
Obj.AcceptState()
Obj.DisplayCountry()
Obj.DisplayState()

Output:
Enter Country Name: India
Enter State Name: Maharashtra
Country Name is: India
State Name is: Maharashtra

You might also like