Slip1:-A) Write a Python program to accept n numbers
in list and remove duplicates from a list.
mylist = [3,2,4,2,1,5,2,7,1]
mylist = list(dict.fromkeys(mylist))
print(mylist)
output:
[3, 2, 4, 1, 5, 7]
Slip1B)Write Python GUI program to take accept your birthdate and
output your age when a button is pressed.
from tkinter import *
from datetime import date
root = Tk()
root.geometry("700x500")
root.title("Age Calculator")
def calculateAge():
today = date.today()
birthDate = date(int(yearEntry.get()), int(monthEntry.get()), int(dayEntry.get())
) age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day))
Label(text=f"{nameValue.get()} 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)
nameEntry.grid(row=1, column=1, pady=10)
yearEntry.grid(row=2, column=1, pady=10)
monthEntry.grid(row=3, column=1, pady=10)
dayEntry.grid(row=4, column=1, pady=10)
computeButton = Button(text="CalculateAge", command=calculateAge)
computeButton.grid(row=5, column=1, pady=10)
root.mainloop()
output:
Slip2:-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 upplower():
uno = 0
lno = 0
str1 = input('Enter the String : ')
for x in str1:
if x.isupper():
uno =uno+1
elif x.islower():
lno =lno+1
print('Number of Upper Characters in the Entered Strings are : ' ,uno)
print('Number of Lower Characters in the Entered Strings are : ' ,lno)
upplower()
output:
Enter the String : HeLLo WoRlD
Number of Upper Characters in the Entered Strings are : 6
Number of Lower Characters in the Entered Strings are : 4
slip2B)WritePythonGUIprogramtocreateadigitalclockwithTkinterto displaythetime
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="blue", fg="white", bd =30)
label.grid(row =0, column=1)
def digitalclock():
text_input = time.strftime("%H:%M:%S")
label.config(text=text_input)
label.after(200, digitalclock)
digitalclock()
canvas.mainloop()
output:
Slip3:-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(20)
output:
Key is present in the dictionary
Key is not present in the dictionary
slip3 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:
marks = []
def getData(self, rn, name, m1, m2, m3):
Student.rn = rn
Student.name = name
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
print ("Roll Number is: ", Student.rn)
print ("Name is: ", Student.name)
#print ("Marks in subject 1: ", Student.marks[0])
#print ("Marks in subject 2: ", Student.marks[1])
#print ("Marks in subject 3: ", Student.marks[2])
print ("Marks are: ", Student.marks)
print ("Total Marks are: ", self.total())
def total(self):
return (Student.marks[0] + Student.marks[1] +Student.marks[2])
r = int (input("Enter the roll number: "))
name = input("Enter the name: ")
m1 = int (input("Enter the marks in the first subject: "))
m2 = int (input("Enter the marks in the second subject: "))
m3 = int (input("Enter the marks in the third subject: "))
s1 = Student()
s1.getData(r, name, m1, m2, m3)
s1.displayData()
output:
Enter the roll number: 234
Enter the name: shamal
Enter the marks in the first subject: 53
Enter the marks in the second subject: 67
Enter the marks in the third subject: 89
Roll Number is: 234
Name is: shamal
Marks are: [53, 67, 89]
Total Marks are: 209
slip4A)Write Python GUI program to create background with changing color
from tkinter import Button,Entry,Label,Tk
def changecolor():
newvalue=value.get()
gui.configure(background=newvalue)
gui=Tk()
gui.title("colorchange.")
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()
output:
slip4B)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. Createn 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):
self.id=id
self.name=name
self.department=department
self.salary=salary
class manager(Employee):
def __init__(self,id,name,department,salary,bonus):
super(manager,self).__init__(id,name,department,salary)
self.bonus=bonus
def totalsalary(self):
print(self.name,'gottotalsalary:',self.salary+self.bonus)
n=manager('A023','ABC','GENERALMANAGEMENT',20000,8000)
m=manager('A025','pQR','MARKETIG',25000,6400)
n.totalsalary()
m.totalsalary()
output:
ABC gottotalsalary: 28000
pQR gottotalsalary: 31400
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 uppercase
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:
shamal
SHAMAL
Slip5:-B) Write a python script to generate Fibonacci terms using generator function
n=int(input("Enter the value of 'n': "))
def f():
first=0
second=1
sum=0
count=1
while(count<=n):
print(sum)
count+=1
first=second
second=sum
sum=first+second
f()
output:
Enter the value of 'n': 9
0
1
1
2
3
5
8
13
21
Or
def fibonacci():
a=0
b=1
for i in range(6):
print(b)
a,b= b,a+b
fibonacci()
output
1
1
2
3
5
8
Slip6A)Write python script using package to calculate area and volume of cube
and spher
import math
class cube():
def __init__(self,edge):
self.edge=edge
def cube_area(self):
cubearea=6*self.edge*self.edge
print("Areaofcube:",cubearea)
def cube_volume(self):
cubevolume=self.edge*self.edge*self.edge
print("Volumeofcube:",cubevolume)
class sphere():
def __init__(self,radius):
self.radius=radius
def sphere_area(self):
spherearea=4*math.pi*self.radius*self.radius
print("Areaofsphere:",spherearea)
def sphere_volume(self):
spherevolume=float(4/3*math.pi*self.radius**3)
print("volumeofsphere:",spherevolume)
e1=cube(5)
e1.cube_area()
e1.cube_volume()
r1=sphere(5)
r1.sphere_area()
r1.sphere_volume()
output:
Areaofcube: 150
Volumeofcube: 125
Areaofsphere: 314.1592653589793
volumeofsphere: 523.5987755982989
slip6 B)Write a Python GUI program to create a label and change the label font style(font name,bold,size).Specify separate checkbutton for each style
#Import the required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Set the geometry of frame
win.geometry("650x250")
#Define all the functions
def size_1():
text.config(font=('Helvatical bold',20))
def size_2():
text.config(font=('Helvetica bold',40))
#Create a Demo Label to which the changes has to be done
text=Label(win, text="Hello World!")
text.pack()
#Create a frame
frame= Frame(win)
#Create a label
Label(frame, text="Select the Font-Size").pack()
#Create Buttons for styling the label
button1=Checkbutton(frame, text="20", command= size_1)
button1.pack(pady=10)
button2=Checkbutton(frame, text="40", command=size_2)
button2.pack(pady=10)
frame.pack()
win.mainloop()
OUTPUT:
Slip7A)Write Python class to perform addition of two complex numbers using binary+operator overloading
class Complex():
def initComplex(self):
self.realPart=int(input("EntertheRealPart:"))
self.imgPart=int(input("EntertheImaginaryPart:"))
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("Enterfirstcomplexnumber")
c1.initComplex()
print("FirstComplexNumber:",end="")
c1.display()
print("Entersecondcomplexnumber")
c2.initComplex()
print("SecondComplexNumber:",end="")
c2.display()
print("Sumoftwocomplexnumbersis",end="")
c3.sum(c1,c2)
c3.display()
output:
Enterfirstcomplexnumber
EntertheRealPart:5
EntertheImaginaryPart:3
FirstComplexNumber:5+3i
Entersecondcomplexnumber
EntertheRealPart:3
EntertheImaginaryPart:5
SecondComplexNumber:3+5i
Sumoftwocomplexnumbersis8+8i
Slip7B)Write python GUI program to generate a random password with upper and lower caseletters.
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:
Slip8:-A) Write a python script to find the repeated items of a tuple
tup=(10,20,30,40,45,10,20,39)
for i in tup:
if tup.count(i) > 1:
print(i)
output:
10
20
10
20
Or
mylist=(10,20,34,45,10,20,34,70)
print("my list :",mylist)
duplicate={x for x in mylist if mylist.count(x)>1}
mylist=tuple(duplicate)
print("Duplicate items are :",mylist)
output:
my list : (10, 20, 34, 45, 10, 20, 34, 70)
Duplicate items are : (10, 20, 34)
or
import collections
tuplex = 2,4,5,6,2,3,4,4,7,5,6,7,1
dictx=collections.defaultdict(int)
for x in tuplex:
dictx[x]+=1
for x in sorted(dictx,key=dictx.get):
if dictx[x]>1:
print('%d repeted %d times'%(x,dictx[x]))
output:
2 repeted 2 times
5 repeted 2 times
6 repeted 2 times
7 repeted 2 times
4 repeted 3 times
slip8B)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):
self.demo=demo
def set_String(self,demo):
demo=demo.upper()
self.demo=demo
def print_streing(self):
return self.demo
A=Str1()
str1=input('enter a string to display :')
A.set_String(str1)
print('Upper string :',A.print_streing())
output:
enter a string to display :HI I Am ShaMal
Upper string : HI I AM SHAMAL
slip9A)Write a Python script using class to reverse a string word by word
def reverse_words(s):
return ' '.join(reversed(s.split()))
str1=input('Enter a string : ')
print(reverse_words(str1))
output:
Enter a string : welcome to BJS
BJS to welcome
Slip9B)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()
output:
Slip10A)Write Python GUI program to display an alert message when a button is pressed.
from tkinter import *
from tkinter import messagebox
def clicked():
messagebox.showinfo('Button','Button is pressed.')
root=Tk()
root.geometry('300x200')
word= Label(root,text='messagebox from button')
Button1=Button(root,text='BUTTON',command=clicked)
word.pack()
Button1.pack()
root.mainloop()
output:
Slip10B) 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 validity:
def f(str):
a= ['()', '{}', '[]']
while any(i in str for i in a):
for j in a:
str = str.replace(j, '')
return not str
s = input("enter : ")
print(s, "-", "is balanced"
if validity.f(s) else "is Unbalanced")
output:
enter : {{}
{{} - is Unbalanced
enter : {}()[]
{}()[] - is balanced
Slip11:-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)
def test(lst):
result = map(sum, lst)
return list(result)
nums = [(3,4,2), (2,9,3), (3,4,5)]
print("Original list of tuples:")
print(nums)
print("\nSum of all the elements of each tuple stored inside the said list of tuples:")
print(test(nums))
output:
Original list of tuples:
[(3, 4, 2), (2, 9, 3), (3, 4, 5)]
Sum of all the elements of each tuple stored inside the said list of tuples:
[9, 14, 12]
slip11B)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, mainloop
def redcolor():
root.configure(background = 'red')
def greencolor():
root.configure(background = 'green')
def yellowcolor():
root.configure(background = 'yellow')
def violetcolor():
root.configure(background = 'violet')
def bluecolor():
root.configure(background = 'blue')
def cyancolor():
root.configure(background = 'cyan')
root = Tk()
root.title('COLOR MENU')
menubar = Menu(root)
color = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='color', menu = color)
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 = root.destroy)
root.config(menu = menubar)
mainloop()
output:
slip12A)Write a Python GUI program to create a label and change the label font
style (font name, bold, size) using tkinter module.
from tkinter import Label, Tk
top=Tk()
top.geometry("200x300")
top.title="font style"
label=Label(top,text="Welcome",font=("Helvetica",25))
label.pack()
top.mainloop()
output:
Slip12:-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
def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency('hello world'))
output:
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Slip13A)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)
output:
Enter a number :h
This is not a number!
Slip13:-B) Write a program to implement the concept of queue using list.
q=[]
q.append(10)
q.append(100)
q.append(1000)
q.append(10000)
print("InitialQueueis:",q)
print(q.pop(0))
print(q.pop(0))
print(q.pop(0))
print("After Removing elements:",q)
output:-
InitialQueueis: [10, 100, 1000, 10000]
10
100
1000
After Removing elements: [10000]
Slip14A)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 checkError() :
if (RadiusField.get() == "" or HeightField.get() == "") :
messagebox.showerror("Input Error")
clearAll()
return -1
def result() :
value = checkError()
if value == -1 :
return
else :
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:
Slip14B)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 : Welcome To BJS
ENtER number to shift pattern encript : 6
Plain txt : Welcome To BJS
Shift pattern : 6
Cipher: DlsjvtluAvuIQZ
Slip15A)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
self.marks=marks
def get_marks(self):
print("\nOriginal name and values")
print(self.Student_name,'marks : ',self.marks)
def modify_marks(self):
self.Student_name1=input('Enter modifyed name : ')
self.marks1=int(input('Enter modifyed marks : '))
print(self.Student_name1,'modifyed marks',self.marks)
def modifyed_marks(self):
print("\nmodified name and values")
print(self.Student_name1,'marks : ',self.marks1)
x=Student('Manav',81)
x.get_marks()
x.modify_marks()
x.get_marks()
x.modifyed_marks()
ouput:
Original name and values
Manav marks : 81
Enter modifyed name : Shamal
Enter modifyed marks : 88
Shamal modifyed marks 81
Original name and values
Manav marks : 81
modified name and values
Shamal marks : 88
Slip15:-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(odd_values_string('hello'))
output:-
hlo
Slip16A)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)
L=int(input('enter Length of Rectangle :'))
W=int(input('enter Width of Rectangle :'))
a1=Ractangle(L,W)
print(a1.rectangle_area())
print(a1.rectangle_Perimeter())
output:
enter Length of Rectangle :6
enter Width of Rectangle :7
42
26
Slip16B)
Slip17A)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() :
value = checkError()
if value == -1 :
return
else :
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:
Slip17B)
Slip18:-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
list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for item in list:
if item < 5:
print(item)
output:-
1
1
2
3
Slip18B)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):
self.empname=name
self.address=address
def display(self):
print('name : {}\taddress : {}\tsalary : {}'.format(self.empname,
self.address,a.getsalary()))
class employee(person):
def __init__(self, name, address,salary):
super().__init__(name, address)
self.salary=salary
def getsalary(self):
return self.salary
name1=input('enter name : ')
address=input('enter address : ')
salary=int(input('enter salary : '))
a=employee(name1,address,salary)
a.display()
output:
enter name : Rahul
enter address : Pune
enter salary : 34000
name : Rahul address : Pune salary : 34000
Slip19A)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("400x400")
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:
Slip19B) 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.
Slip20A)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):
self.Radius=Radius
def area(self):
a=pi*self.Radius*self.Radius
return round(a,2)
def circumference(self):
c=2*self.Radius*pi
return round(c,2)
r= int(input('enter radius of circle : '))
a=Circle(r)
print('Area of circle is : ',a.area())
print('Circumference of circle is : ',a.circumference())
output:
enter radius of circle : 4
Area of circle is : 50.27
Circumference of circle is : 25.13
Slip20:-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 ={}
for x in range(1,n+1):
d[x]=x*x
print(d)
output:
Input a number : 6
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
Slip21A)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)
L=int(input('enter Length of Rectangle :'))
W=int(input('enter Width of Rectangle :'))
a1=Ractangle(L,W)
print(a1.rectangle_area())
print(a1.rectangle_Perimeter())
output:
enter Length of Rectangle :6
enter Width of Rectangle :5
30
22
Slip21:-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 tuple_int_str(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(tuple_int_str(tuple_str))
output:-
Original tuple values:
(('333', '33'), ('1416', '55'))
New tuple values:
((333, 33), (1416, 55))
Slip22A)Write a python class to accept a string and number n from user and
display n repetition of strings by overloading * operator.
Slip22:-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())
list1.append(value)
print("The unsorted list is: ", list1)
print("The sorted list is: ", bubble_sort(list1))
output:
Enter number of elements : 5
8
0
8
8
4
The unsorted list is: [8, 0, 8, 8, 4]
The sorted list is: [0, 4, 8, 8, 8]
Slip23A)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 BJS")
parent.geometry("200x100")
my_label = tk.Label(parent, text="BJS", font=("Arial Bold", 70))
my_label.grid(column=0, row=0)
parent.mainloop()
Output:
Slip23B)
Slip24:-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.
class factorial():
def __init__(self,num):
self.num=num
factnum=1
if self.num<0:
print("Sorry, factorial does not exist for negative numbers")
elif self.num==0:
print("The factorial of 0 is 1")
else:
for i in range(1,num+1):
factnum=factnum*i
print('The factorial of {} is {} factorial'.format(num,factnum))
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
factorial(num)
output:
Enter a number: 7
7 is a prime number
The factorial of 7 is 5040 factorial
Slip24B) 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()
Slip25:-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 upplower():
uno = 0
lno = 0
str1 = input('Enter the String : ')
for x in str1:
if x.isupper():
uno =uno+1
elif x.islower():
lno =lno+1
print('no.of uppercase character:',uno)
print('no.of lowercase character::',lno)
upplower()
output:
Enter the String : HeLLo WoRlD
Number of Upper Characters in the Entered Strings are : 6
Number of Lower Characters in the Entered Strings are : 4
Slip25B)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
self.operation=operation
if self.operation=='*':
print('Multiplication of {} and {} is : '.format(num1,num2),
self.num1*self.num2)
elif self.operation=='/':
print('division of {} and {} is : '.format(num1,num2),
self.num1/self.num2)
elif self.operation=='-':
print('Subtraction of {} and {} is : '.format(num1,num2),
self.num1/self.num2)
elif self.operation=='+':
print('Addition of {} and {} is : '.format(num1,num2),
self.num1+self.num2)
num1=int(input('Enter 1st number : '))
operator1=input('ENTER A CALCULATOR OPERATOR FROM FOLLOWING : / , * , - , +\n')
num2=int(input('Enter 2st number : '))
Calculator(num1,num2,operator1)
output:
Enter 1st number : 3
ENTER A CALCULATOR OPERATOR FROM FOLLOWING : / , * , - , +
+
Enter 2st number : 4
Addition of 3 and 4 is : 7
Slip26:-A) Write an anonymous function to find area of square and rectangle
area_square=lambda x: x*x #area of square is a^2
side=int(input('Enter a side value of square : '))
print(area_square(side))
area_rectangle=lambda x,y:x*y #area of rectangle is l*w
Length=int(input('Enter a Length value of rectangle : '))
Width=int(input('Enter a Width value of rectangle : '))
print(area_rectangle(Length,Width))
output:
Enter a side value of square : 4
16
Enter a Length value of rectangle : 3
Enter a Width value of rectangle : 7
21
Slip26B)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 checkError() :
if (str1Field.get() == "" ) :
messagebox.showerror("Input Error")
clearAll()
return -1
def occurrences() :
value = checkError()
if value == -1 :
return
else :
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")
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 = 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)
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:
Slip27:-A) Write a Python program to unzip a list of tuples into individual lists
sr= [(1,2), (3,4), (8,9)]
print(list(zip(*sr)))
output:-
[(1, 3, 8), (2, 4, 9)]
Slip27B)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 checkError() :
if (numberField.get() == "") :
messagebox.showerror("Input Error")
clearAll()
return -1
def calculateAge() :
value = checkError()
if value == -1 :
return
else :
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")
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)
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)
number.grid(row = 0, column = 1)
number1.grid(row = 1, column = 1)
numberField.grid(row = 2, column = 1)
result.grid(row = 3, 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()
output:
Slip28A)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
Slip28:-B) Write a Python program to accept two lists and merge the two lists
into list of tuple
def merge(l1,l2):
merged_list = [(l1[i], l2[i]) for i in range(0,len(l1))]
return merged_list
l1 = [1, 2, 3]
l2 = ['x', 'y', 'z']
print(merge(l1, l2))
output:
[(1, 'x'), (2, 'y'), (3, 'z')]
Slip29A)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 checkError() :
if (radiusField.get() == "") :
messagebox.showerror("Input Error")
clearAll()
return -1
def getvolume() :
value = checkError()
if value == -1 :
return
else :
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")
Radiuslabel = Label(gui, text = "given Radius", bg = "#00ffff")
volumelabel = Label(gui, text = "result volume", bg = "#00ffff")
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)
Radiuslabel.grid(row = 0, column = 1)
Radius1.grid(row = 1, column = 0)
radiusField.grid(row = 1, column = 1)
volumelabel.grid(row = 0, column = 4)
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:
Slip29:-B) Write a Python script to sort (ascending and descending) a dictionary
by key and value.
d={'apple':40,'banana':2,'cherry':1}
l=list(d.items())
l.sort()
print('Ascending order is',l)
l=list(d.items())
l.sort(reverse=True)
print('Descending order is',l)
dict=dict(l)
print("Dictionary",dict)
output:
Ascending order is [('apple', 40), ('banana', 2), ('cherry', 1)]
Descending order is [('cherry', 1), ('banana', 2), ('apple', 40)]
Dictionary {'cherry': 1, 'banana': 2, 'apple': 40}
Slip30A)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 checkError() :
if (str1Field.get() == "" or char1Field.get() == "") :
messagebox.showerror("Input Error")
clearAll()
return -1
def occurrences() :
value = checkError()
if value == -1 :
return
else :
String0 = (str1Field.get())
char0 = (char1Field.get())
i=0
count=0
while(i<len(String0)):
if(String0[i]==char0):
count=count+1
i=i+1
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")
Stringin = Label(gui, text = " given String", bg = "#00ffff")
char = Label(gui, text = "given character", bg = "#00ffff")
str1 = Label(gui, text = "String", bg = "light green")
char1 = Label(gui, text = "character", bg = "light green")
occurrenceslabel = Label(gui, text = "occurrences \n 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)
Stringin.grid(row = 0, column = 1)
str1.grid(row = 1, column = 0)
str1Field.grid(row = 1, column = 1)
char.grid(row = 0, column = 4)
char1.grid(row = 1, column = 3)
char1Field.grid(row = 1, column = 4)
result.grid(row = 4, column = 2)
occurrenceslabel.grid(row = 5, column = 2)
resultField.grid(row = 6, column = 2)
clearAllEntry.grid(row = 12, column = 2)
gui.mainloop()
output:
Slip30B)Python Program to Create a Class in which One Method Accepts a String from the User and Another method Prints it.
class stringmethod():
def __init__(self):
self.string=""
def get(self):
self.string=input("Enter string: ")
def put(self):
print("String is:")
print(self.string)
obj=stringmethod()
obj.get()
obj.put()
output:
Enter string: Welcome to BJS
String is:
Welcome to BJS
No comments:
Post a Comment