PYTHON
Slip 1
A) Write a Python program to accept n numbers in list and remove duplicates from a list.
Solution :
list1=[]
n=int(input("Enter number of elements of list:"))
print("Enter elements of list: ")
for i in range(n):
num=int(input())
[Link](num)
set1=set(list1)
list1=list(set1)
print(list1)
B) Write Python GUI program to take accept your birthdate and output your age when a button is
pressed.
Solution :
from tkinter import *
from datetime import date
root = Tk()
[Link]("700x500")
[Link]("Age Calculator")
def calculateAge():
today = [Link]()
birthDate = date(int([Link]()), int([Link]()), int([Link]()))
age = [Link] - [Link] - (([Link], [Link]) < ([Link], [Link]))
Label(text=f"{[Link]()} your age is {age}").grid(row=6, column=1)
Label(text="Name").grid(row=1, column=0, padx=90)
Label(text="Year").grid(row=2, column=0)
Label(text="Month").grid(row=3, column=0)
Label(text="Day").grid(row=4, column=0)
nameValue = StringVar()
yearValue = StringVar()
monthValue = StringVar()
dayValue = StringVar()
nameEntry = Entry(root, textvariable=nameValue)
yearEntry = Entry(root, textvariable=yearValue)
monthEntry = Entry(root, textvariable=monthValue)
dayEntry = Entry(root, textvariable=dayValue)
[Link](row=1, column=1, pady=10)
[Link](row=2, column=1, pady=10)
[Link](row=3, column=1, pady=10)
[Link](row=4, column=1, pady=10)
computeButton = Button(text="Calculate Age", command=calculateAge)
[Link](row=5, column=1, pady=10)
[Link]()
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.
Solution:
dict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("The given dictionary : ",dict)
check_key = input("Enter Key to check: ")
check_value = input("Enter Value: ")
if check_key in dict:
print(check_key,"is Present.")
[Link](check_key)
dict[check_key]=check_value
print("Updated dictionary : ",dict)
else:
print(check_key, " is not Present.")
dict[check_key]=check_value
print("Updated dictionary : ",dict)
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.
Solution:
class Student:
def __init__(self):
pass
def GetStudent(self):
[Link]=input("Enter Student Name: ")
[Link]=int(input("Enter Student Roll No: "))
[Link]=int(input("Enter Student Age: "))
[Link]=input("Enter Student Gender: ")
def PutStudent(self):
print("Student Name:",[Link])
print("Student Roll No:",[Link])
print("Student Age:",[Link])
print("Student Gender:",[Link])
class Test(Student):
def __init__(self):
pass
Student.__init__(self)
def GetMarks(self):
[Link]=int(input("Enter Marks of Python Subject: "))
[Link]=int(input("Enter Marks of Java Subject: "))
[Link]=int(input("Enter Marks of Cyber Security Subject: "))
def PutMarks(self):
print("Python Marks:", [Link])
print("Java Marks:", [Link])
print("Cyber Security Marks:", [Link])
print("Total Marks:",[Link]+[Link]+[Link])
n=int(input("Enter Number of Students: "))
lst=[]
for i in range(n):
print("\nEnter Details of Student",i+1)
obj=f"Student{i}"
[Link](obj)
lst[i]=Test()
lst[i].GetStudent()
lst[i].GetMarks()
for j in range(n):
print("\nDisplay Details of Student",j+1)
lst[j].PutStudent()
lst[j].PutMarks()
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.
Solution:
class str_mod:
def get_string(self):
[Link]=input("Enter Your Name: ")
def put_string(self):
print([Link]())
obj1=str_mod()
obj1.get_string()
obj1.put_string()
B) Write a python script to generate Fibonacci terms using generator function.
Solution:
def Fibo(terms2):
f1=0
yield f1
f2=1
yield f2
for i in range(0,terms2-2):
f3=f1+f2
yield f3
f1=f2
f2=f3
#mainbody
terms1=int(input("How many terms: "))
gen=Fibo(terms1)
while True:
try:
print(next(gen))
except StopIteration:
break
Slip 6
A) Write python script using package to calculate area and volume of cube and sphere
Solution:
Pacakge Calc
pi=3.14
def area_sphere(r):
global pi
return 4*pi*r*r
def vol_sphere(r):
global pi
return 4/3*pi*(r*r*r)
def area_cube(s):
return 6*s*s
def vol_cube(s):
return s*s*s
Main code
from Calc import functions
radius=int(input("Enter radius of sphere: "))
sphere_area=functions.area_sphere(radius)
sphere_vol=functions.vol_sphere(radius)
print(f"Area of sphere: {sphere_area}\nVolume of sphere: {sphere_vol}\n\n")
side=int(input("Enter side of cube: "))
cube_area=functions.area_cube(side)
cube_vol=functions.vol_cube(side)
print(f"Area of cube: {cube_area}\nVolume of cube:{cube_vol}")
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.
Solution:
import tkinter as tk
import [Link] as tkFont
class App:
def __init__(self):
root=[Link]()
[Link] = [Link](family="Helvetica", size=12)
buttonframe = [Link]()
label = [Link](root, text="Hello, world", font=[Link])
text = [Link](root, width=20, height=2, font=[Link])
[Link](side="top", fill="x")
[Link]()
[Link]()
[Link]("end","press +/- buttons to change\nfont size")
bigger = [Link](root, text="+", command=[Link])
smaller = [Link](root, text="-", command=[Link])
[Link](in_=buttonframe, side="left")
[Link](in_=buttonframe, side="left")
[Link]()
def OnBigger(self):
'''Make the font 2 points bigger'''
size = [Link]['size']
[Link](size=size+2)
def OnSmaller(self):
'''Make the font 2 points smaller'''
size = [Link]['size']
[Link](size=size-2)
app=App()
Slip 7
A) Write Python class to perform addition of two complex numbers using binary + operator
overloading.
Solution:
class complex:
def __init__(self,real,imag):
[Link]=real
[Link]=imag
def __add__(self,other):
real= [Link] + [Link]
imag= [Link] + [Link]
obj3=complex(real,imag)
return obj3
obj1=complex(2,5)
obj2=complex(5,1)
obj3=obj1+obj2
print(f"{[Link]} + {[Link]}i")
print(f"{[Link]} + {[Link]}i")
print(f"Addition: {[Link]} + {[Link]}i")
B) Write python GUI program to generate a random password with upper and lower case letters.
import tkinter as tk
import random
import string
def generate_password():
length = int(length_entry.get())
characters = string.ascii_letters # upper + lower case letters
password = ''.join([Link](characters) for _ in range(length))
password_entry.delete(0, [Link])
password_entry.insert(0, password)
root = [Link]()
[Link]("Random Password Generator")
[Link]("350x200")
[Link](bg="#eef2ff")
[Link](root, text="Random Password Generator", font=("Arial", 14, "bold"),
bg="#eef2ff").pack(pady=10)
[Link](root, text="Enter password length:", font=("Arial", 11), bg="#eef2ff").pack()
length_entry = [Link](root, justify='center', font=("Arial", 11))
length_entry.pack(pady=5)
length_entry.insert(0, "8")
[Link](root, text="Generate Password", command=generate_password, bg="#4a90e2",
fg="white",
font=("Arial", 11, "bold"), relief="ridge").pack(pady=10)
password_entry = [Link](root, width=25, font=("Arial", 12), justify='center')
password_entry.pack(pady=5)
[Link]()
Slip 8
A) Write a python script to find the repeated items of a tuple
Solution:
def count(mytuple):
s=set()
for i in mytuple:
if([Link](i)>1):
[Link](i)
return s
n=int(input("Enter size of tuple: "))
print("Enter elements of tuple: ")
mylist=list()
for i in range(n):
tup_ele=input()
[Link](tup_ele)
mytuple=tuple(mylist)
print(count(mytuple))
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. [25 M]
Solution:
class str_mod:
def get_string(self):
[Link]=input("Enter Your Name: ")
def put_string(self):
s=[Link]
print("String in Upper Case: " , [Link]())
words = [Link](' ')
string =[]
for word in words:
[Link](0, word)
print("String in Reverse & Lower case:")
print(" ".join(string))
obj1=str_mod()
obj1.get_string()
obj1.put_string()
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
from tkinter import font
def change_font():
fname = font_name.get()
fsize = int(font_size.get())
fstyle = "bold" if bold_var.get() == 1 else "normal"
[Link](font=(fname, fsize, fstyle))
root = [Link]()
[Link]("Change Label Font Style")
[Link]("400x300")
[Link](bg="#eef2ff")
label = [Link](root, text="Welcome to Python GUI!", font=("Arial", 14))
[Link](pady=20)
[Link](root, text="Font Name:", bg="#eef2ff").pack()
font_name = [Link](value="Arial")
[Link](root, textvariable=font_name, justify='center').pack(pady=5)
[Link](root, text="Font Size:", bg="#eef2ff").pack()
font_size = [Link](value="14")
[Link](root, textvariable=font_size, justify='center').pack(pady=5)
bold_var = [Link]()
[Link](root, text="Bold", variable=bold_var, bg="#eef2ff").pack(pady=5)
[Link](root, text="Apply Font", command=change_font, bg="#4a90e2", fg="white", font=("Arial",
11, "bold")).pack(pady=10)
[Link]()
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
Solution:
def count_char(str):
mylist=list()
for i in str:
[Link](i)
for j in mylist:
count=[Link](j)
if count>1:
print(j," - ",count)
while count>1:
[Link](j)
count=[Link](j)
str="thequickbrownfoxjumpsoverthelazydog"
count_char(str)
Slip 13
A) Write a Python program to input a positive integer. Display correct message for correct and
incorrect input. (Use Exception Handling)
Solution:
try:
num=int(input("Enter a positive number: "))
if num<0:
raise Exception
print(f"{num} is a positive number.")
except ValueError:
print ("Invalid Input")
except Exception:
print("You entered Negative number. Try again...")
B) Write a program to implement the concept of queue using list.
Solution:
n=int(input("Enter size of queue: "))
print("Enter elements of queue: ")
mylist=list()
for i in range(n):
ele=input()
[Link](ele)
print("Current queue:- ")
print(mylist)
print("\n")
for j in range(len(mylist)):
print(mylist)
pop_ele=[Link](0)
print(pop_ele)
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.
Solution :
class rectangle:
def __init__(self,length,width):
[Link]=length
[Link]=width
def area(self):
return [Link]*[Link]
def perimeter(self):
return 2*([Link]+[Link])
length=int(input("Enter length: "))
width=int(input("Enter Width: "))
obj1=rectangle(length,width)
print("Area: ",[Link]())
print("Perimeter: ",[Link]())
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.
Solution :
Slip 17
A) Write Python GUI program that takes input string and change letter to upper case when a button
is pressed.
Solution :from tkinter import *
def to_upper():
output_var.set(input_var.get().upper())
root = Tk()
[Link]("Uppercase Converter")
input_var = StringVar()
output_var = StringVar()
Label(root, text="Enter text:").pack(pady=5)
Entry(root, textvariable=input_var).pack(pady=5)
Button(root, text="Convert to Uppercase", command=to_upper).pack(pady=5)
Label(root, textvariable=output_var, fg="blue").pack(pady=5)
[Link]()
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.
Solution :
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]()
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.
Solution :
def print_list(mylist):
for i in mylist:
if i<5:
print(i)
mylist=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print_list(mylist)
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.
Solution :class Person:
def __init__(self, name, address):
[Link] = name
[Link] = address
class Employee(Person):
def __init__(self, name, address, staffid, salary):
super().__init__(name, address)
[Link] = staffid
[Link] = salary
def display(self):
print("Name:", [Link])
print("Address:", [Link])
print("Staff ID:", [Link])
print("Salary:", [Link])
print()
n = int(input("Enter number of employees: "))
employees = []
for i in range(n):
name = input("Enter name: ")
address = input("Enter address: ")
staffid = input("Enter staff ID: ")
salary = float(input("Enter salary: "))
[Link](Employee(name, address, staffid, salary))
print("\nEmployee Details:")
for emp in employees:
[Link]()
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)
Solution :
class Circle():
def __init__(self, r):
[Link] = r
def area(self):
return [Link]**2*3.14
def circumference(self):
return 2*[Link]*3.14
radius=int(input("Enter radius of circle: "))
NewCircle = Circle(radius)
print([Link]())
print([Link]())
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}
Solution :
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)
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.
Solution :
class Rectangle():
def __init__(self, l, w):
[Link] = l
[Link] = w
def rectangle_area(self):
area=[Link]*[Link]
perimeter=2*([Link]+[Link])
return area,perimeter
newRectangle = Rectangle(12, 10)
result=newRectangle.rectangle_area()
print("Area: ",result[0])
print("Perimeter: ",result[1])
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))
Solution :
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}")
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.
Solution :class RepeatString:
def __init__(self, string):
[Link] = string
def __mul__(self, n):
return [Link] * n
s = input("Enter a string: ")
n = int(input("Enter number of repetitions: "))
obj = RepeatString(s)
print(obj * n)
B) Write a python script to implement bubble sort using list.
Solution :
lst=[12,10,17,9,1]
cnt=len(lst)
for i in range(0,cnt-1):
for j in range(0,cnt-1):
if lst[j]>lst[j+1]:
temp=lst[j]
lst[j]=lst[j+1]
lst[j+1]=temp
print(lst)
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.
Solution :
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)
B) Write Python GUI program which accepts a number n to displays each digit of number in words.
Solution :from tkinter import *
def show_words():
num = [Link]()
words = {
'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four',
'5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine'
result = ' '.join([Link](d, '') for d in num if [Link]())
output_var.set(result)
root = Tk()
[Link]("Number to Words")
Label(root, text="Enter a number:").pack(pady=5)
entry = Entry(root)
[Link](pady=5)
Button(root, text="Show in Words", command=show_words).pack(pady=5)
output_var = StringVar()
Label(root, textvariable=output_var, fg="blue").pack(pady=5)
[Link]()
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
Solution :
def count(str):
uppercase=0
lowercase=0
for i in str:
if i==" " or i==".":
continue
elif [Link]():
uppercase+=1
elif [Link]():
lowercase+=1
return uppercase,lowercase
str="The quick Brow Fox"
result=count(str)
print("No. of Upper case characters : ",result[0])
print("No. of Lower case Characters : ",result[1])
B) Write a Python script to Create a Class which Performs Basic Calculator Operations.
Solution :
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("Subtraction 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("Multiplication is: ",self.c)
def DivOp(self):
self.a=int(input("Enter first no: "))
self.b=int(input("Enter Second no: "))
self.c= self.a // self.b
print("Division is: ",self.c)
#main body
obj=MathOp()
while True:
print("\n1. Addtion")
print("2. Substraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
ch=int(input("Enter choice to perform any opertaion: "))
if ch==1:
[Link]()
elif ch==2:
[Link]()
elif ch==3:
[Link]()
elif ch==4:
[Link]()
elif ch==5:
break
else:
print("Wrong Choice")
Slip 27
A) Write a Python program to unzip a list of tuples into individual lists.
Solution :
l = [(1,2), (3,4), (8,9)]
print(list(zip(*l)))
B) Write Python GUI program to accept a decimal number and convert and display it to binary, octal
and hexadecimal number.
Solution :from tkinter import *
def convert():
num = int([Link]())
binary_var.set(bin(num)[2:])
octal_var.set(oct(num)[2:])
hexa_var.set(hex(num)[2:].upper())
root = Tk()
[Link]("Number System Converter")
Label(root, text="Enter Decimal Number:").pack(pady=5)
entry = Entry(root)
[Link](pady=5)
Button(root, text="Convert", command=convert).pack(pady=5)
binary_var = StringVar()
octal_var = StringVar()
hexa_var = StringVar()
Label(root, text="Binary:").pack()
Label(root, textvariable=binary_var, fg="blue").pack()
Label(root, text="Octal:").pack()
Label(root, textvariable=octal_var, fg="green").pack()
Label(root, text="Hexadecimal:").pack()
Label(root, textvariable=hexa_var, fg="purple").pack()
[Link]()