Python Programming Lab Manual (Solved)
Python Programming Lab Manual (Solved)
Part-A
1. Write a program create list with N elements. find all unique elements in the list. If an element
is found only once in the list, then add that element to the unique list.
input_list = []
n=int(input("Enter number of elements"))
print("Enter the elements")
for i in range(n) :
num = int(input(f"Enter element no. {i+1}: "))
input_list.append(num)
#main function
result = find_unique_elements(input_list)
unique_list = []
for element in input_list:
if input_list.count(element) == 1:
unique_list.append(element)
pg. 1
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
2. Program, using user-defined functions to find the area of rectangle, square, circle and triangle
by accepting suitable input parameters from user.
#Part_A_Q2 - Areas
def rectangle_area(length, width):
area = length * width
return area
def square_area(side):
area = side ** 2 #** is the exponent-operator
return area
def circle_area(radius):
area = 3.14159 * radius ** 2
return area
if choice == 1:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = rectangle_area(length, width)
print("The area of the rectangle is: ", area," sq.units")
elif choice == 2:
side = float(input("Enter the length of a side of the square: "))
area = square_area(side)
pg. 2
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
elif choice == 3:
radius = float(input("Enter the radius of the circle: "))
area = circle_area(radius)
print("The area of the circle is: ", area," sq.units")
elif choice == 4:
base= float(input("Enter the base of the triangle "))
height = float(input("Enter the height of the triangle "))
area = triangle_area(base, height)
print("The area of the rectangle is: ", area," sq.units")
else:
print("Wrong Choice")
#Part_A_Q3 - Tuple
t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10)
print("\nTuple t1 = ",t1,"\n")
print("\nHalf the values of t1 in one line and the other half in the next
line.")
half_len = len(t1) // 2
print(t1[:half_len])
print(t1[half_len:])
t2=()
for i in t1:
if i%2==0:
t2+=(i,)
print("\nanother tuple whose values are even numbers in the given tuple:
",t2)
t3 = t1 + t2
print("\na tuple t2= (11,13,15) concatenated with t1, i.e., (t1+t2): ",t3)
max_val = max(t1)
min_val = min(t1)
print(f"\nMax value from t1: {max_val}")
print(f"Min value from t2: {min_val}")
4. Write a function that takes a sentence as input from the user and calculates the frequency of
each letter. Use a variable of dictionary type to maintain the count.
for i in char_list:
#print(list.count(i))
char_count_dict[i]= char_list.count(i)
#print(char_count_dict); ignore!
5. Write a function nearly equal to test whether two strings are nearly equal. Two strings a and
b are nearly equal if one character change in b results in string a.
#function body/definition
def nearly_equal(str1,str2):
list1=[]
for i in str1:
list1.append(i)
list2=[]
for i in str2:
list2.append(i)
no_match_count=0
if len(str1)>=len(str2)+1 or len(str2)>=len(str1)+1 :
print("The strings are not at all equal")
exit()
if len(list1)==len(list2) :
for i in range(len(list1)):
if list1[i]!=list2[i]:
no_match_count+=1
if no_match_count==1:
print("The two strings entered are nearly equal")
elif no_match_count==0:
print("The two strings entered are equal")
else:
print("The two strings entered are not equal")
#main function
str1=input("Enter a sentence for string_1")
str2=input("Enter a sentence for string_2")
nearly_equal(str1,str2) #function call
pg. 5
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
6. Write a program to create a text file and compute the number of characters, words and lines
in a file.
#A6_text_file
import os
def count_characters(filename):
with open(filename, "r") as f:
characters = len(f.read())
return characters
def count_words(filename):
"""Counts the number of words in a file."""
return words
def count_lines(filename):
with open(filename, "r") as f:
lines = len(f.readlines())
return lines
def main():
"""The main function."""
if not os.path.exists(filename):
with open(filename, "w") as f:
print("Enter data to store in file: ")
data = input()
while data.upper() != "EOF":
f.write(data + "\n")
data = input()
characters = count_characters(filename)
words = count_words(filename)
pg. 6
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
lines = count_lines(filename)
if __name__ == "__main__":
main()
7. Program using user defined exception class that will ask the user to enter a number until he
guesses a stored number correctly. To help him/her figure it out, a hint is provided whether
his/her guess is greater than or less than the stored number using user defined exceptions
class GuessTooLow(Exception):
pass
class GuessTooHigh(Exception):
pass
class CorrectGuess(Exception):
pass
class GuessSlightlyLess(Exception):
pass
class GuessSlightlyMore(Exception):
pg. 7
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
pass
def guess_number(secret_number):
while True:
try:
guess = int(input("Guess a number between 0 and 75: "))
if guess < (secret_number) and (guess > secret_number - 10):
raise GuessSlightlyLess
elif guess < secret_number:
raise GuessTooLow
elif guess > (secret_number) and (guess < secret_number + 10):
raise GuessSlightlyMore
elif guess > secret_number:
raise GuessTooHigh
else:
raise CorrectGuess
except GuessTooLow:
print("Too low! Try again.")
except GuessSlightlyLess:
print("Slightly less! Try again")
except GuessTooHigh:
print("Too high! Try again.")
except GuessSlightlyMore:
print("Slightly more! Try again")
except CorrectGuess:
print("Congratulations! You guessed the correct number:",
secret_number)
break
pg. 8
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
'''This code will concatenate df1 and df2 along rows (axis 0),
ignoring the index of the original data frames, and create a new data frame
result_df.'''
Part-B
1. Program to create a class Employee with empno, name, depname, designation, age and
salary and perform the following function.
i) Accept details of N employees
ii) Search given employee using empno
iii) Display employee details in a neat format..
def setEmployee(self):
self.empno = input("Enter employee number: ")
self.name=input("Enter name: ")
self.depname=input("Enter name of the dept: ")
self.designation=input("Enter designation: ")
self.age=int(input("Enter age in years: "))
self.salary=float(input("Enter Salary of the employee: "))
pg. 9
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
def showEmployee(self):
print("Employee details:")
print(f"\tEmployee number: {self.empno}")
print(f"\tEmployee name: {self.name}")
print(f"\tEmployee department: {self.depname}")
print(f"\tEmployee designation: {self.designation}")
print(f"\tEmployee age: {self.age}")
print(f"\tEmployee salary: {self.salary}")
#print(f"\tEmployee_number\tName\tDepartment\tDesignation\tAge\tSalary")
#print(f"\t{self.empno} \t {self.name} \t {self.depname} \t
{self.designation} \t {self.age} \t {self.salary}")
# main
n=int(input("Enter number of employees: "))
loE=[]
for i in range(0,n):
e=Employee()
e.setEmployee()
loE.append(e)
print("\n")
i.designation,i.age,i.salary))
print("-" * 90)
#i.showEmployee()
#print(" ")
found=0
search_empno = int(input("Enter Employee Number to search: "))
for i in loE:
if int(i.empno)==search_empno:
print("Employee found")
found=1
i.showEmployee()
if found==0:
print("Employee not found")
2. Write a program menu driven to create a BankAccount class. class should support the
following methods for i) Deposit ii) Withdraw iii) GetBalanace. Create a subclass
pg. 10
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
SavingsAccount class that behaves just like a BankAccount, but also has an interest rate and a
method that increases the balance by the appropriate amount of interest.
class BankAccount:
ledger = [] #list item
def __init__(self):
self.account_no = 0
self.name = ""
self.acc_type = ""
self.amount = 0
self.balance = 0
self.trans_type = ""
self.trans_date = ""
def GetLedger(self):
passbook = {} #dictionary item
passbook['account_no'] = int(input("Enter Account No : "))
passbook['name'] = input("Enter Account holder Name : ")
passbook['trans_date'] = ""
passbook['amount'] = 0
passbook['balance'] = 0
passbook['trans_type'] = ""
BankAccount.ledger.append(passbook)
pg. 11
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
if found==0:
print("-" * 90)
print(f"Account No {acc_no} NOT found in Bank Ledger")
print("-" * 90)
if found==0:
print("-" * 90)
print(f"Account No {acc_no} NOT found in Bank Ledger")
print("-" * 90)
pg. 12
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
print("{0:10}\t{1:20}\t{2:16}\t{3:10}\t{4:15}\t{5:10}".format(passbook['accou
nt_no'],
passbook['name'],
passbook['trans_date'],
passbook['trans_type'],
passbook['amount'],
passbook['balance']))
if found==0:
print("-" * 90)
print(f"Account No {acc_no} NOT found in Bank Ledger")
print("-" * 90)
def ShowLedger(self):
passbook = {}
print("-" * 90)
print("Account No\t Name \t\t\t\t Transaction Date\tTransaction
Type\tAmount\t\tBalance")
print("-" * 90)
for passbook in BankAccount.ledger:
print("{0:10}\t{1:20}\t{2:16}\t{3:10}\t{4:10}\t{5:10}".format(passbook['accou
nt_no'],
passbook['name'],
passbook['trans_date'],
passbook['trans_type'],
passbook['amount'],
passbook['balance']))
print("-" * 90)
class SavingsAccount(BankAccount):
def Update_Interest(self):
passbook = {}
for passbook in BankAccount.ledger:
passbook['balance'] += passbook['balance'] * 0.35
print("Intrest updated")
# Main Function
BankDetail = SavingsAccount()
ch = 0
pg. 13
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
while ch != 7:
try:
print("-" * 40)
print("Select your Option")
print("-" * 40)
print("1. Legder Entry")
print("2. Credit Amount")
print("3. Withdraw Amount")
print("4. Get Balance")
print("5. Update Interest amount")
print("6. Show Bank Details")
print("7. Quit")
print("-" * 40)
ch = int(input("Enter your option : "))
if ch == 1:
BankDetail.GetLedger()
elif ch == 2:
Acc_no = int(input("Enter Account Number : "))
BankDetail.Credit(Acc_no)
elif ch == 3:
Acc_no = int(input("Enter Account Number : "))
BankDetail.Withdraw(Acc_no)
elif ch == 4:
Acc_no = int(input("Enter Account Number : "))
BankDetail.GetBalance(Acc_no)
elif ch == 5:
BankDetail.Update_Interest()
elif ch == 6:
BankDetail.ShowLedger()
elif ch == 7:
print("Thank you for Banking with us .....")
except ValueError:
print("Invalid Data ...... ")
finally:
print("\n")
pg. 14
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
3. Create a GUI to input Principal amount, rate of interest and number of years, Calculate
Compound interest. When button submit is pressed Compound interest should be displayed
in a textbox. When clear button is pressed all contents should be cleared.
import tkinter as tk
from tkinter import messagebox
def clear_text():
entry1.delete(0,'end')
entry2.delete(0,'end')
entry3.delete(0,'end')
sample_text.delete(0,'end')
entry2 = tk.Entry(root)
label2.grid(row=2, column=0)
entry2.grid(row=2, column=1)
#a blank-gap of 1 row
label4 = tk.Label(root, text=" ")
label4.grid(row=4, column=0)
#a blank-gap of 1 row
label5 = tk.Label(root, text=" ")
label5.grid(row=7, column=0)
def press(num):
global expression
expression = expression + str(num)
equation.set(expression)
def equalpress():
try:
global expression
total = str(eval(expression))
equation.set(total)
expression = str(total)
except:
equation.set("ERORR ")
expression = ""
pg. 16
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
def clear():
global expression
expression = ""
equation.set("")
if __name__ == "__main__":
root = Tk()
root.configure(background='aqua')
root.title("Simple Calculator")
root.geometry("250x190")
equation = StringVar()
root.mainloop()
5. Python program to Create a table student_table (regno, name and marks in 3 subjects) using
MySQL and perform the following
a. To accept the details of students and store it in a database.
b. To display the details of all the students
c. Delete a particular student record using regno
pg. 18
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
Code:
import mysql.connector
# Connect to MySQL
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="mysql",
database="mydatabase"
)
def display_students():
# Displaying details of all students
mycursor.execute("SELECT * FROM student_table")
result = mycursor.fetchall()
for row in result:
print(row)
def delete_student(regno):
# Deleting a particular student record using regno
sql = "DELETE FROM student_table WHERE regno = %s"
val = (regno,)
mycursor.execute(sql, val)
mydb.commit()
print("Student deleted successfully.")
# Add a student
ans=input("Add a student?(y/n): ")
while(ans!='n'):
regno=int(input("Enter student Registration Number: "))
name=input("Enter name: ")
pg. 19
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
# Delete a student
ans=input("Delete a student?(y/n): ")
if(ans=='y'):
regno=int(input("Enter reg_no of student to be deleted: "))
delete_student(regno)
Note:
• First of all, establish python-mysql connection by watching this link--
https://www.youtube.com/watch?v=MhaH7o3lf4E
• Second of all, master all basic skills required to do python-mysql programming by using
below link
(copy-paste code examples in pycharm demo-file and check outputs)
https://www.w3schools.com/python/python_mysql_getstarted.asp
If, "mysql.connector.connect" is giving an error:
When you encounter an issue with importing mysql.connector in PyCharm, there are a few
steps you can take to troubleshoot and resolve the problem:
Check Your Interpreter Configuration:
In PyCharm, go to File → Settings → Project Interpreter.
Ensure that the interpreter configured in PyCharm matches the one you installed the mysql-
connector package for.
Verify that the interpreter path in PyCharm corresponds to the same Python distribution you see
when typing where python in the terminal or command line.
Confirm that pip also points to the same Python distribution.
pg. 20
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
6. Create a table employee (empno, name and salary) using MySQL and perform the followings
a. To accept the details of employees and store it in database.
b. To display the details of a specific employee
c. To display employee details whose salary lies within a certain range
Sample Output:
pg. 21
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
import mysql.connector
if mydb.is_connected():
print("Connected to MySQL database!")
cursor = mydb.cursor()
pg. 22
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
# Main function
def main():
while True:
print("\n1. Insert Employee Details")
print("2. Display Employee Details")
print("3. Display Employee Details within Salary Range")
print("4. Display all Employee Details")
print("5. Delete all rows")
pg. 23
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
print("6. Exit")
if choice == '1':
name = input("Enter employee name: ")
salary = float(input("Enter employee salary: "))
insert_employee_details(cursor, name, salary)
elif choice == '2':
empno = int(input("Enter employee number: "))
display_employee_details(cursor, empno)
elif choice == '3':
min_salary = float(input("Enter minimum salary: "))
max_salary = float(input("Enter maximum salary: "))
display_employee_in_salary_range(cursor, min_salary,
max_salary)
elif choice == '4':
display_all_employee_details(cursor)
elif choice == '5':
delete_table(cursor)
break
elif choice == '6':
break
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
main()
pg. 24
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
Sample Output:
import mysql.connector
database="mydatabase"
)
else:
print("Customer not found!")
query = """
UPDATE electricity_bill
SET Previous_Reading = %s, Current_Reading = %s
WHERE Meter_Number = %s
"""
val = (Previous_Reading, Current_Reading, Meter_Number)
cursor.execute(query, val)
mydb.commit()
print("Customer details updated successfully")
else:
print("No records found!")
units_consumed=result[4]-result[3]
pg. 27
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
# Main function
def main():
create_table()
if choice == '1':
Customer_Name=input("Enter customer name: ")
while True:
Tariff_Code = input("Enter Tariff-Code(LT1/LT2): ")
if (Tariff_Code == "LT1"):
insert_customer_details(cursor, Tariff_Code, Customer_Name)
pg. 28
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
break
elif (Tariff_Code=="LT2"):
insert_customer_details(cursor, Tariff_Code, Customer_Name)
break
else:
print("Invalid tariff code! Enter as LT1 or LT2")
while True:
Previous_Reading = int(input("Enter Previous Reading: "))
Current_Reading = int(input("Enter Current Reading: "))
if(Current_Reading<Previous_Reading):
print("Current reading needs to be greater than or equal to
previous reading")
else:
break
update_customer_details(cursor, Meter_Number, Previous_Reading,
Current_Reading)
# Closing connection
cursor.close()
mydb.close()
if __name__ == "__main__":
main()
pg. 29
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
Sample Output:
This script will create a GUI window where you can input the batsman's name and their scores for each
year. Clicking the "Add Data" button will create the CSV file for the first time, and later it appends
this data to the CSV file(csv-comma separated values). Clicking the "Plot Graph" button will plot a
bar graph using matplotlib based on the data in the CSV file.
pg. 30
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
Code
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import pandas as pd
import matplotlib.pyplot as plt
def callback():
# remove all data from the file, at the beginning; every time file is newly
written
with open('cricket_data.csv', 'w') as f:
f.truncate()
#open file and write Column-titles; program doesnt work without col-titles in
csv file
with open('batsman_scores.csv', 'w') as file:
file.write("Batsman, 2017, 2018, 2019, 2020")
batsman_entry.unbind('<Visibility>')#make sure callback() is called only
once after root window is visible
def add_data():
# Get values from the entry widgets
batsman = batsman_entry.get()
scores = [int(score_entry_2017.get()), int(score_entry_2018.get()),
int(score_entry_2019.get()), int(score_entry_2020.get())]
def plot_graph():
# Read data from CSV file
data = pd.read_csv('batsman_scores.csv')
# Years
years = list(data.columns[1:])
pg. 31
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
# Plotting
x = range(len(years)) # Assuming all years have same number of scores
width = 0.075 # Width of the bars
fig, ax = plt.subplots()
for i, batsman_scores in enumerate(scores):
ax.bar([pos + i * width for pos in x], batsman_scores, width,
label=batsmen[i])
ax.set_xticks([pos + i * width for pos in x])
ax.set_xticklabels(years)
ax.legend()
plt.show()
# GUI
root = tk.Tk()
root.title("Batsman Scores")
batsman_entry = ttk.Entry(root)
batsman_entry.grid(row=0, column=1, padx=5, pady=5)
batsman_entry.bind('<Visibility>', callback())
'''make sure callback()
is called only once after root window(batsman_entry widget) is visible;
callback() function adds column-titles line in csv file once, when the
program starts'''
score_entry_2017 = ttk.Entry(root)
score_entry_2017.grid(row=1, column=1, padx=5, pady=5)
#score_entry_2017.insert(0, "0")
score_2017_label = ttk.Label(root, text="2017")
score_2017_label.grid(row=2, column=1, padx=5, pady=5)
score_entry_2018 = ttk.Entry(root)
score_entry_2018.grid(row=1, column=2, padx=5, pady=5)
score_2018_label = ttk.Label(root, text="2018")
score_2018_label.grid(row=2, column=2, padx=5, pady=5)
score_entry_2019 = ttk.Entry(root)
score_entry_2019.grid(row=1, column=3, padx=5, pady=5)
score_2019_label = ttk.Label(root, text="2019")
pg. 32
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab
score_entry_2020 = ttk.Entry(root)
score_entry_2020.grid(row=1, column=4, padx=5, pady=5)
score_2020_label = ttk.Label(root, text="2020")
score_2020_label.grid(row=2, column=4, padx=5, pady=5)
root.mainloop()
******
Note:
1. It is important to understand basics of GUI-Python first, in order to understand the above
code.
2. Do study basic concepts and programming examples of Python-MatplotLib
a. Quickly go through the topics and examples using the following link
https://www.w3schools.com/python/matplotlib_intro.asp
b. For plotting bar graphs: https://www.w3schools.com/python/matplotlib_bars.asp
c. Go through the code and the outputs in the below webpage
https://www.geeksforgeeks.org/bar-plot-in-matplotlib/
3. Installation of Matplotlib: If you have Python and PIP already installed on a system, then
installation of Matplotlib is very easy.Install it using this command in CMD-Prompt:
pg. 33