0% found this document useful (0 votes)
1 views

Python Programming Lab Manual (Solved)

The document contains a series of Python programming lab exercises from the Dept. of B.C.A., U.C.P.S Manipal. It includes tasks such as finding unique elements in a list, calculating areas of various shapes, manipulating tuples, counting character frequencies in a sentence, and implementing a guessing game with user-defined exceptions. Additionally, it covers creating classes for employee management and bank account operations, along with file handling and data frame manipulation using Pandas.

Uploaded by

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

Python Programming Lab Manual (Solved)

The document contains a series of Python programming lab exercises from the Dept. of B.C.A., U.C.P.S Manipal. It includes tasks such as finding unique elements in a list, calculating areas of various shapes, manipulating tuples, counting character frequencies in a sentence, and implementing a guessing game with user-defined exceptions. Additionally, it covers creating classes for employee management and bank account operations, along with file handling and data frame manipulation using Pandas.

Uploaded by

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

Dept. of B.C.A., U.C.P.

S Manipal Python Programming Lab

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.

#Part_A_Q1 - Unique elements


#using a function
def find_unique_elements(input_list):
unique_list = []
for element in input_list:
if input_list.count(element) == 1:
unique_list.append(element)
return 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)

print("Input List:", input_list)


print("Unique Elements:", result)

'''program without using function

input_list = [1,2,2,3,4,4,5] # Creating a list with N elements (0 to N-1)

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

print("Input List:", input_list)


print("Unique Elements:", unique_list)'''

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

def triangle_area(base, height):


area = 0.5 * base * height
return area

print("Choose a shape to find its area:")


print("1. Rectangle")
print("2. Square")
print("3. Circle")
print("4. Triangle")
choice = int(input("Enter your choice (1-4): "))

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

print("The area of the square is: ", area," sq.units")

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")

3. Consider a tuple t1= (1,2,5,7,9,2,4,6,8,10). Write a program to perform following operations:


a. Print half the values of tuple in one line and the other half in the next line.
b. Print another tuple whose values are even numbers in the given tuple.
c. Concatenate a tuple t2= (11,13,15) with t1.
d. Return maximum and minimum value from this tuple.

#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)

t2 = (11, 13, 15)


pg. 3
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

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.

#A4_count of each character in a sentence


def char_count(sentence) :
char_list=[]
char_count_dict={}

for character in sentence:


if character.isalpha(): #consider only alphabets, ignore other
characters!
char_list.append(character)

for i in char_list:
#print(list.count(i))
char_count_dict[i]= char_list.count(i)

#print(char_count_dict); ignore!

for key,value in char_count_dict.items():


if (value!=1):
pg. 4
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

print(f"The character \'{key}\' appears {value} times.")


elif (value==1):
print(f"The character \'{key}\' appears once.")
#main function
sentence=input("Enter a sentence")
sentence=sentence.lower()
char_count(sentence)

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.

#A5_Strings nearly equal

#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."""

with open(filename, "r") as f:


words = len(f.read().split())

return words

def count_lines(filename):
with open(filename, "r") as f:
lines = len(f.readlines())

return lines

def main():
"""The main function."""

filename = input("Enter file name with complete path: ")

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)

print("The file {} has {} characters, {} words, and {} lines.".format(


filename, characters, words, lines))

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

Que_A_7: exception class


import random

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

# Example usage; main function


secret_number = random.randrange(75) #Return a randomly selected element
from range(stop).
guess_number(secret_number)

8. Write a Pandas program to join the two given data frames


along rows. Sample Data frame may contain details of student
like rollno, name, Total Marks.
CODE
import pandas as pd

# Sample data frames


data1 = {'Rollno': [101, 102, 103],
'Student_Name': ['Akhil', 'Basu',
'Charlie'],
'Total Marks': [450, 480, 430]}
df1 = pd.DataFrame(data1) # df1 =
pd.DataFrame(data1, index=[0, 1, 2])

data2 = {'Rollno': [104, 105, 106],


'Student_Name': ['Dhoni', 'Eva', 'Faruq'],
'Total Marks': [410, 470, 440]}

pg. 8
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

df2 = pd.DataFrame(data2) # df2 = pd.DataFrame(data2, index=[4,5,6])

print(df1, "\n\n", df2)

# Joining the two data frames along rows


result_df = pd.concat([df1, df2], ignore_index=True) # result_df =
pd.concat([df1, df2])

print("\n\n"," Joined Data Frame:\n")


print(result_df)

'''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..

#python lab BCA NEP 2024, PartB_Q1


class Employee:
empno=''
name=''
depname=''
designation=''
age=''
salary=''

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")

print("\n\n"+"-"*15 + "All Employees' Details"+"-"*15)


print("-" * 90)
print("Employee_number\tName\t\tDepartment\tDesignation\tAge\t Salary")
for i in loE:
print("{0:15}\t{1:10}\t{2:10}\t{3:10}\t{4:2}\t{5:10}".format(i.empno,
i.name,
i.depname,

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

def Credit(self, acc_no):


passbook = {} #dictionary item
found=0
for passbook in BankAccount.ledger:
if passbook['account_no'] == acc_no:
found=1
passbook['amount'] = int(input("Enter Amount to credit :"))
passbook['trans_date'] = input("Enter date of transaction :
")
passbook['balance'] += passbook['amount']
passbook['trans_type'] = 'CR'
print("Amount Credited!..")

if found==0:
print("-" * 90)
print(f"Account No {acc_no} NOT found in Bank Ledger")
print("-" * 90)

def Withdraw(self, acc_no):


passbook = {}
found=0
for passbook in BankAccount.ledger:
if passbook['account_no'] == acc_no:
found=1
amt = int(input("Enter Amount to Withdraw :"))
if passbook['balance'] >= amt:
passbook['amount']=amt
passbook['trans_date'] = input("Enter date of transaction
: ")
passbook['balance'] -= passbook['amount']
passbook['trans_type'] = 'DB'
else:
print("-" * 90)
print(f" Insufficient Balance in Account No {acc_no} \n
Ledger balance is {passbook['balance']} ")
print("-" * 90)

if found==0:
print("-" * 90)
print(f"Account No {acc_no} NOT found in Bank Ledger")
print("-" * 90)

def GetBalance(self, acc_no):


found=0
passbook = {}
for passbook in BankAccount.ledger:
if passbook['account_no'] == acc_no:
found=11
print("-" * 90)
print("Account No\tName \t\t\t\tTransaction Date\tTransaction
Type\t\tAmount\t\tBalance")
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')

# Create a function to calculate the average


def calculate_CI():
try:
p = float(entry1.get())
r = float(entry2.get())
t = float(entry3.get())
compound_interest=0
amount=p*(1+(r/100))**t
compound_interest = amount-p
#messagebox.showinfo("Result", f"The CI is: {compound_interest:.2f}")
sample_text.delete(0, "end")

# Insert method inserts the text at


# specified position, Here it is the
# beginning
sample_text.insert(0, f"{compound_interest:.2f}")
except ValueError:
messagebox.showerror("Error", "Please enter valid numbers!")

# Create the main window


root = tk.Tk()
root.geometry("290x175")
root.title("Compound Interest Calculator")
#root.grid(row=0, column=0)

# Create input fields


label1 = tk.Label(root, text="Principal(Rs.): ")
entry1 = tk.Entry(root)
label1.grid(row=1, column=0)
entry1.grid(row=1, column=1)

label2 = tk.Label(root, text="Rate: ")


pg. 15
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

entry2 = tk.Entry(root)
label2.grid(row=2, column=0)
entry2.grid(row=2, column=1)

label3 = tk.Label(root, text="Time in years: ")


label3.grid(row=3, column=0)
entry3 = tk.Entry(root)
entry3.grid(row=3, column=1)

#a blank-gap of 1 row
label4 = tk.Label(root, text=" ")
label4.grid(row=4, column=0)

# Create a button to calculate the Compound Interest


calculate_button = tk.Button(root, text="Calculate\nCompound_Interest",
command=calculate_CI)
calculate_button.grid(row=5, column=0, columnspan=2)

clear_button=tk.Button(root, text="Clear", command=clear_text, )


clear_button.grid(row=5, column=2)

#a blank-gap of 1 row
label5 = tk.Label(root, text=" ")
label5.grid(row=7, column=0)

label6 = tk.Label(root, text="Compound Interest: ")


label6.grid(row=8, column=0 )
# Creating our text widget.
sample_text = tk.Entry(root)
sample_text.grid(row=8, column=1)

# Start the GUI event loop


root.mainloop()

4. Write a GUI program to implement a simple


calculator.
from tkinter import *
expression = ""

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()

expression_field = Entry(root, textvariable= equation,bg ='white',fg


='black',justify = 'left')
expression_field.grid(row=1, columnspan=5, ipadx=60)

button1 = Button(root, text=' 1 ', fg='black', bg='light yellow',


command=lambda:press(1), height=1, width=7)
button1.grid(row=4, column=0)

clear = Button(root, text='Clear', fg='light yellow', bg='navy blue',


command=clear,height=1, width=7)
clear.grid(row=2, columnspan=4, ipadx=70)

button2 = Button(root, text=' 2 ', fg='black', bg='light yellow',


command=lambda:press(2), height=1, width=7)
button2.grid(row=4, column=1)

button3 = Button(root, text=' 3 ', fg='black', bg='light yellow',


command=lambda:press(3), height=1, width=7)
button3.grid(row=4, column=2)
button4 = Button(root, text=' 4 ', fg='black', bg='light yellow',
command=lambda:press(4), height=1, width=7)
button4.grid(row=5, column=0)
button5 = Button(root, text=' 5 ', fg='black', bg='light yellow',
command=lambda:press(5), height=1, width=7)
button5.grid(row=5, column=1)
button6 = Button(root, text=' 6 ', fg='black', bg='light yellow',
command=lambda:press(6), height=1, width=7)
button6.grid(row=5, column=2)
button7 = Button(root, text=' 7 ', fg='black', bg='light yellow',
command=lambda:press(7), height=1, width=7)
button7.grid(row=6, column=0)
button8 = Button(root, text=' 8 ', fg='black', bg='light yellow',
command=lambda:press(8), height=1, width=7)
button8.grid(row=6, column=1)
button9 = Button(root, text=' 9 ', fg='black', bg='light yellow',
command=lambda:press(9), height=1, width=7)
button9.grid(row=6, column=2)
button0 = Button(root, text=' 0 ', fg='black', bg='light yellow',
command=lambda:press(0), height=1, width=7)
button0.grid(row=7, column=1)
pg. 17
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

plus = Button(root, text=' + ', fg='black', bg='light blue',


command=lambda:press("+"), height=1, width=7)
plus.grid(row=4, column=3)
minus = Button(root, text=' - ', fg='black', bg='light blue',
command=lambda:press("-"), height=1, width=7)
minus.grid(row=5, column=3)
multiply = Button(root, text=' * ', fg='black', bg='light blue',
command=lambda:press("*"), height=1, width=7)
multiply.grid(row=6, column=3)
divide = Button(root, text=' / ', fg='black', bg='light blue',
command=lambda:press("/"), height=1, width=7)
divide.grid(row=7, column=3)
equal = Button(root, text=' = ', fg='black', bg='light blue',
command=equalpress,height=1, width=7)
equal.grid(row=7, column=2)
Decimal = Button(root, text='.', fg='black', bg='light yellow',
command=lambda:press('.'), height=1, width=7)
Decimal.grid(row=7, column=0)

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"
)

# Create a cursor object


mycursor = mydb.cursor()

# Creating the student_table if not exists


mycursor.execute("CREATE TABLE IF NOT EXISTS student_table (regno INT PRIMARY
KEY, name VARCHAR(50), marks_subject1 INT, marks_subject2 INT, marks_subject3
INT)")

def add_student(regno, name, marks_subject1, marks_subject2, marks_subject3):


# Inserting student details
sql = "INSERT INTO student_table (regno, name, marks_subject1,
marks_subject2, marks_subject3) VALUES (%s, %s, %s, %s, %s)"
val = (regno, name, marks_subject1, marks_subject2, marks_subject3)
mycursor.execute(sql, val)
mydb.commit()
print("Student added successfully.")

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.")

# Example usage: main_function

print("Details of all students(student_table): ")


display_students()

# 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

m1 = int(input("Enter marks in subject1: "))


m2 = int(input("Enter marks in subject2: "))
m3 = int(input("Enter marks in subject3: "))
add_student(regno,name,m1,m2,m3)
ans=input("Add a student?(y/n): ")
print("Completed all insertions!")

# Display all students


print()
print("Details of all students:")
display_students()

# 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)

# Display all students after deletion


print("Details of all students after deletion:")
display_students()

# Close the connection


mydb.close()

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

# Connect to MySQL database


mydb = mysql.connector.connect(
host="localhost",
user="root",
password="mysql",
database="mydatabase"
)

if mydb.is_connected():
print("Connected to MySQL database!")

cursor = mydb.cursor()

# Function to create the employee table if not exists


def create_employee_table(cursor):
cursor.execute("""
CREATE TABLE IF NOT EXISTS employee (
empno INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
salary FLOAT NOT NULL
)
""")

# Function to insert employee details into the database


def insert_employee_details(cursor, name, salary):
sql = "INSERT INTO employee (name, salary) VALUES (%s, %s)"
val = (name, salary)
cursor.execute(sql, val)
mydb.commit()
print("Employee details inserted successfully!")

# Function to display all employee details from the database


def display_all_employee_details(cursor):
sql="select * from employee"
cursor.execute(sql)
results=cursor.fetchall()
if results:
print("All employees' details")
print("-------------------------------")
for result in results:
print("Employee Number:", result[0])
print("Name:", result[1])
print("Salary:", result[2])
print("-------------------------------")
else:
print("No records found!")

pg. 22
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

#Function to delete all records from database


def delete_table(cursor):
sql = "drop table employee"
cursor.execute(sql)
mydb.commit()
print("All records successfully deleted")

# Function to display details of a specific employee


def display_employee_details(cursor, empno):
sql = "SELECT * FROM employee WHERE empno = %s"
cursor.execute(sql, (empno,))
result = cursor.fetchone()
if result:
print("Employee Details:")
print("-------------------------------")
print("Employee Number:", result[0])
print("Name:", result[1])
print("Salary:", result[2])
else:
print("Employee not found!")

# Function to display employee details within a salary range


def display_employee_in_salary_range(cursor, min_salary, max_salary):
sql = "SELECT * FROM employee WHERE salary BETWEEN %s AND %s"
cursor.execute(sql, (min_salary, max_salary))
results = cursor.fetchall()
if results:
print("Employees within salary range:")
print("-------------------------------")
for result in results:
print("Employee Number:", result[0])
print("Name:", result[1])
print("Salary:", result[2])
print("-------------------------------")
else:
print("No employees found within the specified salary range.")

# Main function
def main():

# Create employee table


create_employee_table(cursor)

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")

choice = input("Enter your choice: ")

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.")

# Close cursor and connection


cursor.close()
mydb.close()
print("MySQL connection closed.")

if __name__ == "__main__":
main()

7. Create a table electricity_bill(TariffCode, Customer_Name, Meter Number,


Previous_Reading and Current_Reading) using MySQL and perform the followings
a. To accept the details of employees and store it in database.
b. To Update the Customer details by Meter Number.
c. Calculate Bill of a particular Customer using below criteria

pg. 24
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

Sample Output:

import mysql.connector

# Establish connection to MySQL


mydb = mysql.connector.connect(
host="localhost",
user="root",
password="mysql",
pg. 25
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

database="mydatabase"
)

# Create a cursor object to execute SQL queries


cursor = mydb.cursor()

# Function to create electricity_bill table


def create_table():
create_query = """
CREATE TABLE IF NOT EXISTS electricity_bill (
Tariff_Code VARCHAR(5) NOT NULL,
Customer_Name VARCHAR(255) NOT NULL,
Meter_Number INT AUTO_INCREMENT PRIMARY KEY,
Previous_Reading INT,
Current_Reading INT,
Units_Consumed INT,
Bill_Amount FLOAT
)
"""
cursor.execute(create_query)
mydb.commit()
print("Table electricity_bill created successfully")

# Function to insert customer details


def insert_customer_details(cursor, Tariff_Code, Customer_Name):
query = """INSERT INTO electricity_bill (Tariff_Code, Customer_Name)
VALUES (%s, %s)""" #multi-line query
val = (Tariff_Code, Customer_Name)
cursor.execute(query, val)
mydb.commit()
print("Customer details inserted successfully")

# Function to display details of a specific customer


def display_customer_details(cursor, Meter_Number):
query = "SELECT * FROM electricity_bill WHERE Meter_Number = %s"
cursor.execute(query, (Meter_Number,)) #2nd argument is a tuple with one
value; comma required
result = cursor.fetchone()
if result:
print("Customer Details:")
print("-------------------------------")
print("TariffCode : ", result[0])
print("Customer-Name : ", result[1])
print("Meter-Number : ", result[2])
print("Previous-Reading: ", result[3])
print("Current-Reading: ", result[4])
print("-------------------------------")

else:
print("Customer not found!")

# Function to update customer details by Meter Number


def update_customer_details(cursor, Meter_Number, Previous_Reading,
Current_Reading):
pg. 26
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

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")

# Function to display all employee details from the database


def display_all_customer_details(cursor):
query = "select * from electricity_bill"
cursor.execute(query)
results = cursor.fetchall()
if results:
print("All Customers' details")
print("-------------------------------")
for result in results:
print("TariffCode : ", result[0])
print("Customer-Name : ", result[1])
print("Meter-Number : ", result[2])
print("Previous-Reading: ", result[3])
print("Current-Reading: ", result[4])
print("-------------------------------")

else:
print("No records found!")

#Function to delete all records from database


def delete_table(cursor):
query = "drop table electricity_bill"
cursor.execute(query)
mydb.commit()
print("All records successfully deleted")

#Function to calculate bill amount from database


def calculate_bill_amt(cursor, Meter_Number):
query = "SELECT * FROM electricity_bill WHERE Meter_Number = %s"
cursor.execute(query, (Meter_Number,)) # 2nd argument is a tuple with one
value; comma required
result = cursor.fetchone()
if result:
print("Customer Details:")
print("-------------------------------")
print("TariffCode: ", result[0])
print("Customer-Name : ", result[1])
print("Previous-Reading: ", result[3])
print("Current-Reading: ", result[4])
if(result[3]==None and result[4]==None):
print("Previous and current readings not updated")
return

units_consumed=result[4]-result[3]
pg. 27
Dept. of B.C.A., U.C.P.S Manipal Python Programming Lab

print("Units-Consumed: ", units_consumed)


if(result[0]=='LT1'):
if(units_consumed>=0 and units_consumed<=30):
bill_amt =units_consumed*2
if (units_consumed >= 31 and units_consumed <= 100):
bill_amt =units_consumed*3.5
if (units_consumed >= 101 and units_consumed <= 200):
bill_amt =units_consumed*4.5
if (units_consumed >200):
bill_amt =units_consumed*5
print("Bill-Amount: Rs. ", bill_amt)
elif (result[0] == 'LT2'):
if (units_consumed >= 0 and units_consumed <= 30):
bill_amt = units_consumed * 3.5
if (units_consumed >= 31 and units_consumed <= 100):
bill_amt = units_consumed * 5.0
if (units_consumed >= 101 and units_consumed <= 200):
bill_amt = units_consumed * 6.0
if (units_consumed > 200):
bill_amt = units_consumed * 7.5
print("Bill-Amount: Rs. ", bill_amt)
query = """
UPDATE electricity_bill
SET Units_Consumed = %s, Bill_Amount = %s
WHERE Meter_Number = %s
"""
val = (units_consumed, bill_amt, Meter_Number)
cursor.execute(query, val)
mydb.commit()
print("Customer bill updated successfully")
else:
print("Customer not found!")

# Main function
def main():
create_table()

#menu; loops infintely till you choose to exit


while True:
print("\n1. Insert Customer-Details")
print("2. Display Customer-Details by Meter-Number")
print("3. Update Customer-Details by Meter-Number")
print("4. Display all Customer Details")
print("5. Calculate Bill for a customer")
print("6. Delete table permanently")
print("7. Exit")
choice = input("Enter your choice: ")

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")

elif choice == '2':


Meter_Number = int(input("Enter Meter-Number of the customer: "))
display_customer_details(cursor, Meter_Number)

elif choice == '3':


Meter_Number = input("Enter Meter-Number: ")

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)

elif choice == '4':


display_all_customer_details(cursor)

elif choice == '5':


Meter_Number = int(input("Enter Meter-Number of the customer: "))
calculate_bill_amt(cursor, Meter_Number)

elif choice == '6':


ans=input("Are you absolutely sure? (y/n): ")
if(ans=='y'):
delete_table(cursor)
quit = input("Terminating program.....(press any key)")
break
else:
continue
elif choice == '7':
break
else:
print("Invalid choice! Please try again.")

# 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())]

# Append data to the CSV file


with open('batsman_scores.csv', 'a') as file:
file.write(f'\n{batsman},{",".join(map(str, scores))}')

messagebox.showinfo("Success", "Data saved successfully!")

# clear all the entry widgets


batsman_entry.delete(0, 'end')
score_entry_2017.delete(0, 'end')
score_entry_2018.delete(0, 'end')
score_entry_2019.delete(0, 'end')
score_entry_2020.delete(0, 'end')
batsman_entry.focus_set()# place the cursor in batsman widget

def plot_graph():
# Read data from CSV file
data = pd.read_csv('batsman_scores.csv')

# Extracting batsmen names


batsmen = data['Batsman']

# Extracting scores for each batsman


scores = data.drop('Batsman', axis=1).values.tolist()

# 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.set_ylabel('Score',fontweight ='bold', fontsize = 15)


ax.set_xlabel('Year',fontweight ='bold', fontsize = 15)
ax.set_title('Scores by Batsman',fontweight ='bold', fontsize = 15)

ax.legend()

plt.show()

# GUI
root = tk.Tk()
root.title("Batsman Scores")

batsman_label = ttk.Label(root, text="Batsman:")


batsman_label.grid(row=0, column=0, padx=5, pady=5)

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_label = ttk.Label(root, text="Scores:")


score_label.grid(row=1, column=0, padx=5, pady=5)

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_2019_label.grid(row=2, column=3, padx=5, pady=5)

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)

add_button = ttk.Button(root, text="Add Data", command=add_data)


add_button.grid(row=3, column=0, columnspan=5, padx=5, pady=5)

plot_button = ttk.Button(root, text="Plot Graph", command=plot_graph)


plot_button.grid(row=4, column=0, columnspan=5, 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

You might also like