0% found this document useful (0 votes)
7 views19 pages

Python Programming Exercises and Solutions

Uploaded by

shelkearjun1221
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views19 pages

Python Programming Exercises and Solutions

Uploaded by

shelkearjun1221
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Slip 2:

A. Write a Python function that accepts a string and calculate the number of upper case letters and
lower case letters. Sample String: 'The quick Brown Fox' Expected Output: No. of Upper case
characters: 3 No. of Lower case characters: 13
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if [Link]():
d["UPPER_CASE"]+=1
elif [Link]():
d["LOWER_CASE"]+=1
else:
pass
print ("Original String : ", s)
print ("No. of Upper case characters : ", d["UPPER_CASE"])
print ("No. of Lower case Characters : ", d["LOWER_CASE"])
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()
[Link]("Digital Clock")
[Link]("350x200")
[Link](1,1)
label = Label(canvas, font=("Courier", 30, 'bold'), bg="red", fg="white", bd
=30) [Link](row =0, column=1)
def digitalclock():
text_input = [Link]("%H:%M:%S
%p") [Link](text=text_input)
[Link](200, digitalclock)
digitalclock()
[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.
d={'A':1,'B':2,'C':3}
key=input("Enter key to check:")
check_value = input("Enter Value: ")
if key in [Link]():
print("Key is present and value of the key is:")
print(d[key])
[Link](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):
[Link]=int(input("\nEnter Student Roll No:"))
[Link]=input("Enter Student Name:")
[Link]=int(input("Enter Student Age:"))
[Link]=input("Enter Student Gender:")
def PutStudent(self):
print("Student Roll No:",[Link])
print("Student Name:",[Link])
print("Student Age:",[Link])
print("Student Gender:",[Link])
class Test(Student):
def GetMarks(self):
[Link]=int(input("Enter Marks of Marathi Subject"))
[Link]=int(input("Enter Marks of Hindi Subject"))
[Link]=int(input("Enter Marks of Eglish Subject"))
def PutMarks(self):
print("Marathi Marks:", [Link])
print("Hindi Marks:", [Link])
print("English Marks:", [Link])
print("Total Marks:",[Link]+[Link]+[Link])

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


lst=[]
for i in range(0,n):
obj=input("Enter Object Name:")
[Link](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 = [Link]()
[Link](background = n)
gui=Tk()
[Link]("color change.")
[Link](background = "gray")
[Link]("400x300")
color = Label(gui, text = "color", bg =
"gray") value = Entry(gui)
apply = Button(gui, text = "Apply", fg = "Black", bg = "gray",
command=changecolor) [Link](row=0,column=0)
[Link](row=0,column=1)
[Link](row=0,column=2)
[Link]()

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

class

Manager(Employee):

def

AcceptMgr(self):
[Link]=int(input("Enter Manager Bonus"))
def DisplayMgr(self):
[Link]=0
print("Manger Bonus is:",[Link])
[Link]=[Link]+[Link]
print("Total Salary: ",
[Link])

n=int(input("Enter How may


Managers:")) lst=[]
for i in range(0,n):
obj=input("Enter Object
Name:") [Link](obj)
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([Link]())

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 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) + ":"))
[Link](element)
lst=[]
print("Repeated elements in given tuple ")
for i in range(0, len(t)):
if [Link](t[i])>1 :
if t[i] not in lst:
[Link](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):
[Link]=input("Enter any String: ")
def Print_String(self):
s=[Link]
print("String in Upper Case: " , [Link]())
cnt=len(s)
i=cnt-1
RevStr=""
while(i >= 0):
RevStr=RevStr + s[i]
i=i-1
print("String in Reverse & Lower case:" , [Link]())

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

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 = [Link](int)
for c in str1:
d[c] += 1
for c in sorted(d, key=[Link], 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 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):
[Link]=input("Enter Student Name:")
[Link]=int(input("Enter Student Total Marks:"))
def Modify(self):
[Link]=[Link]
[Link]=int(input("Enter Student New Total Marks:"))
print("Student Name:",[Link])
print("Old Total Mark:",[Link])
print("New Total Mark:",[Link])
Stud1=Student()
[Link]()
[Link]()
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 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):
[Link]=input("\n Enter tne name of Person: ")
[Link]=input("Enter Address of Person: ")
def PutPerson(self):
print("Person Name:",[Link])
print("Student Address:",[Link])

class Employee(Person):
def GetSalary(self):
[Link]=int(input("Enter Salary of Employee"))
def PutSalary(self):
print("Salary of Employee:",[Link])

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


lst=[]
for i in range(0,n):
obj=input("Enter Object Name:")
[Link](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 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): [Link]
=r
def area(self):
return [Link]**2*3.14
def perimeter(self):
return 2*[Link]*3.14

NewCircle = Circle(8)
print([Link]())
print([Link]())

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):
[Link] = l
[Link] = w
def rectangle_area(self):
return [Link]*[Link]

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 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([Link]()):
count1=count1+1
elif([Link]()):
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:
[Link]()
elif ch==2:
[Link]()
elif ch==3:
[Link]()
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 28:
A: Write a Python GUI program to create a list of Computer Science Courses using Tkinter
module (use Listbox).
from tkinter import *
top = Tk()
[Link]('Course')
[Link]("300x250
")
Lb1 =Listbox(top,fg='yellow',width=30,bg='gray',bd=1,activestyle='dotbox')
[Link](1, "Computer
Programming") [Link](2,
"Information Science") [Link](3,
"Networking") [Link](4,
"Operating Systems") [Link](5,
"Artificial Intelligence")
[Link](6, "Information
Technology")
[Link](7,'Information Security')
[Link](8, "Cyber Security")
[Link]()
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())
[Link](ele)
print(list1)
n1 = int(input("Enter number of elements of second list : "))
for i in range(0, n1):
ele1 = int(input())
[Link](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)]

You might also like