Final Python Record

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

IV SEMESTER

INDEX

Sl. No. PART-A Page


No.

Write a program create list with N elements. find all unique elements in
1 the list. If an element is found only once in the list,then add that element to 1-2
the unique list.

Write a program, using user-defined functions to find the area ofrectangle,


2 square, circle and triangle by accepting suitable input parameters from user. 3-4

Consider a tuple t1= (1,2,5,7,9,2,4,6,8,10). Write a program toperform


following operations:
a. Print half the values of tuple in one line and the other halfin the next
3 line.
5-6
b. Print another tuple whose values are even numbers in thegiven tuple.
c. Concatenate a tuple t2= (11,13,15) with t1.
d. Return maximum and minimum value from this tuple.

Write a function that takes a sentence as input from the user andcalculates
4
the frequency of each letter. Use a variable of dictionary type to maintain 7-8
the count.
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

6 Write a program to create a text file and compute the number ofcharacters,
9-10
words and lines in a file.

Program using user defined exception class that will ask the userto enter a
number until he guesses a stored number correctly. Tohelp them figure it
7 out, a hint is provided whether their guess is greater than or less than the 11-12
stored number using user defined exceptions.

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.

Bearys Institute of Emerging Sciences, Mangalore 1|P a g e


IV SEMESTER

Sl. PART-B Page No.


No.

Program to create a class Employee with empno, name, depname,


designation, age and salary and perform the following function.
1 i) Accept details of N employees
ii) Search given employee using empno
iii) Display employee details in neat format.
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
SavingsAccount class that behaves just like a BankAccount, but also has an interest
2 rate and a method that increases the balance by the appropriate amount of interest.
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
3 displayed in a textbox. When clear button is pressed all contents should be cleared.
4 Write a GUI program to implement Simple Calculator

Create a table student table (regno, name and marks in 3 subjects) usingMySQL
and perform the followings
a. To accept the details of students and store it in database.
5 b. To display the details of all the students
c. Delete particular student record using regno.

Create a table employee (empno, name and salary) using MySQL andperform
the followings
6 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
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 Particular Customer using below criteria.

Bearys Institute of Emerging Sciences, Mangalore 2|P a g e


IV SEMESTER

8
Consider following data and draw the bar graph using matplot library.(Use CSV or
Excel).Add the data Using GUI

Batsman 2017 2018 2019 2020

Virat Kohli 2501 1855 2203 1223

Steve Smith 2340 2250 2003 1153

Babar Azam 1750 2147 1896 1008

Rohit Sharma 1463 1985 1854 1638

Kane Williamson 1256 1785 1874 1974

Jos Butler 1125 1853 1769 1436

Display appropriate title for axis and chart. Also show legends.

Bearys Institute of Emerging Sciences, Mangalore 3|P a g e


IV SEMESTER

Bearys Institute of Emerging Sciences, Mangalore 4|P a g e


IV SEMESTER

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

def unique(list):
list1=[]
for ele in list:
if ele not in list1:
list1.append(ele)
return list1
list=[]
n=int(input("ENTER THE NO OF ELEMENTS IN THE LIST :"))
print("ENTER THE ELEMENTS :")
for i in range(0,n):
element=input()
list.append(element)
print("LIST GIVEN BY USER :",list)
print("UNIQUE LIST :",unique(list))

OUTPUT:
ENTER THE NO OF ELEMENTS IN THE LIST :5
ENTER THE ELEMENTS :
10
25
13
25
10
LIST GIVEN BY USER : ['10', '25', '13', '25', '10']
UNIQUE LIST : ['10', '25', '13']

Bearys Institute of Emerging Sciences, Mangalore 5|P a g e


IV SEMESTER

PROGRAM 2
Program, using user-defined functions to find the area of rectangle, square, circle and triangle by
accepting suitable input parameters from user.

def calculate_area(name):
name=name.lower()
if name=="rectangle":
l=int(input("ENTER THE LENGTH :"))
b=int(input("ENTER THE BREADTH :"))
rect_area=l*b
print("AREA OF RECTANGLE = ",rect_area)
elif name=="square":
s=int(input("ENTER THE LENGTH OF ONE SIDE :"))
sqr_area=s*s
print("AREA OF SQUARE = ",sqr_area)
elif name=="triangle":
h=int(input("ENTER THE HEIGHT :"))
b=int(input("ENTER THE BREADTH :"))
tri_area=0.5*b*h
print("AREA OF TRIANGLE = ",tri_area)
elif name=="circle":
r=int(input("ENTER THE RADIUS :"))
pi=3.14
circ_area=pi*r*r
print("AREA OF CIRCLE = ",circ_area)
else:
print("SORRY!!!SHAPE UNAVAILABLE...TRY AGAIN")
print("CALCULATE SHAPE AREA")

Bearys Institute of Emerging Sciences, Mangalore 6|P a g e


IV SEMESTER

shape_name=input("ENTER A SHAPE TO FIND ITS AREA : ")


calculate_area(shape_name)

OUTPUT:
CALCULATE SHAPE AREA
ENTER A SHAPE TO FIND ITS AREA : rectangle
ENTER THE LENGTH :25
ENTER THE BREADTH :40
AREA OF RECTANGLE = 1000

CALCULATE SHAPE AREA


ENTER A SHAPE TO FIND ITS AREA : SQUARE
ENTER THE LENGTH OF ONE SIDE :5
AREA OF SQUARE = 25

CALCULATE SHAPE AREA


ENTER A SHAPE TO FIND ITS AREA : triangle
ENTER THE HEIGHT :5
ENTER THE BREADTH :6
AREA OF TRIANGLE = 15.0

CALCULATE SHAPE AREA


ENTER A SHAPE TO FIND ITS AREA : circle
ENTER THE RADIUS :5
AREA OF CIRCLE = 78.5

CALCULATE SHAPE AREA


ENTER A SHAPE TO FIND ITS AREA : 5
SORRY!!!SHAPE UNAVAILABLE...TRY AGAIN

Bearys Institute of Emerging Sciences, Mangalore 7|P a g e


IV SEMESTER

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

t1=(1,2,5,7,9,2,4,6,8,10)
half=int(len(t1)/2)
print('FIRST HALF : ',t1[:half])
print('SECOND HALF : ',t1[half:])

def even(t):
evens=[]
for num in t:
if num%2==0:
evens.append(num)
return set(evens)
print('EVEN NUMBERS : ',even(t1))
t2=(11,13,15)
t3=t1+t2
print("CONCATENATED TUPLE : ",t3)
print("MAX : ",max(t3),'\t min : ',min(t3))

OUTPUT:
FIRST HALF : (1, 2, 5, 7, 9)
SECOND HALF : (2, 4, 6, 8, 10)
EVEN NUMBERS : {2, 4, 6, 8, 10}
CONCATENATED TUPLE : (1, 2, 5, 7, 9, 2, 4, 6, 8, 10, 11, 13, 15)
MAX : 15 min : 1

Bearys Institute of Emerging Sciences, Mangalore 8|P a g e


IV SEMESTER

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

def frequency(sent):
sent=sent.lower()
myDict={}
for i in sent:
if i=='':continue
if i not in myDict.keys():
myDict.__setitem__(i,1)
else:
count=1+myDict[i]
myDict.__setitem__(i,count)
return myDict
sents=input("ENTER THE SENTENCE : ")
print(f"FREQUENCY : ",frequency(sents))

OUTPUT:
ENTER THE SENTENCE : HHELLO
FREQUENCY : {'h': 2, 'e': 1, 'l': 2, 'o': 1}

ENTER THE SENTENCE : PYTHON PROGRAMMING


FREQUENCY : {'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 2, ' ': 1, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 1}

Bearys Institute of Emerging Sciences, Mangalore 9|P a g e


IV SEMESTER

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

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[2]:
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")

str1=input("ENTER A SENTENCE FOR STRING_1:")


str2=input("ENTER A SENTENCE FOR STRING_2:")
nearly_equal(str1,str2)

OUTPUT:
ENTER A SENTENCE FOR STRING_1: Hello sir
ENTER A SENTENCE FOR STRING_2: Hellu sur
THE TWO STRINGS ENTERED ARE NOT EQUAL

ENTER A SENTENCE FOR STRING_1:Hello sir


ENTER A SENTENCE FOR STRING_2:Hello sir
THE TWO STRINGS ENTERED ARE NOT EQUAL

Bearys Institute of Emerging Sciences, Mangalore 10 | P a g e


IV SEMESTER

PROGRAM 6
Write a program to create a text file and compute the number of characters, words and lines in a file.

def writeToFile(path,content):
file=open(path,"w")
file.write(content)

path_to_my_file='new.txt'
content_to_my_file='welcome\nto\nthe page.'
writeToFile(path_to_my_file,content_to_my_file)
print(f"Text file is Created")

file=open("new.txt","r")
data=file.read()
words=data.split()

with open("new.txt",'r')as rd:


lines=len(rd.readlines())
print('NUMBER OF WORDS IN TEXT FILE :',len(words))

print('NUMBER OF CHARACTER IN TEXT FILE :',len(data))


print('NUMBER OF LINES IN TEXT FILE :',lines)

OUTPUT:

Text file is Created


NUMBER OF WORDS IN TEXT FILE : 4
NUMBER OF CHARACTER IN TEXT FILE : 20
NUMBER OF LINES IN TEXT FILE : 3

Bearys Institute of Emerging Sciences, Mangalore 11 | P a g e


IV SEMESTER

PROGRAM 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 them figure it out, a hint is provided whether their guess is greater th
an or less than the stored number using user defined exceptions.

class Error(Exception):
pass

class ValueTooLargeError(Error):
pass

class ValueTooSmallError(Error):
pass

number=7

while True:
try:
i_num=int(input("ENTER A NUMBER : "))
if i_num<number:
raise ValueTooSmallError
elif i_num>number:
raise ValueTooLargeError
break

except ValueTooSmallError:
print("THIS VALUE IS SMALLER ! TRY AGAIN...")
print()
except ValueTooLargeError:
print("THIS VALUE IS LARGER ! TRY AGAIN...")
print()

print("NICE !!! YOU GUESSED IT CORRECTLY.")

OUTPUT:
ENTER A NUMBER : 5
THIS VALUE IS SMALLER ! TRY AGAIN...

ENTER A NUMBER : 9
THIS VALUE IS LARGER ! TRY AGAIN...

ENTER A NUMBER : 7
NICE !!! YOU GUESSED IT CORRECTLY.

Bearys Institute of Emerging Sciences, Mangalore 12 | P a g e


IV SEMESTER

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

import pandas as pd

data1={'Rollno':[101,102,103],
'Student_Name':['Akhil','Basu','charlie'],
'Total Marks':[450,480,430]}
df1=pd.DataFrame(data1)

data2={'Rollno':[104,105,106],
'Student_Name':['Dhoni','Eva','Faruq'],
'Total Marks':[410,470,440]}

df2=pd.DataFrame(data2)

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

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

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


print(result_df)

OUTPUT:
Rollno Student_Name Total Marks
0 101 Akhil 450
1 102 Basu 480
2 103 charlie 430

Rollno Student_Name Total Marks


0 104 Dhoni 410
1 105 Eva 470
2 106 Faruq 440

joined Data Frame:

Rollno Student_Name Total Marks


0 101 Akhil 450
1 102 Basu 480
2 103 charlie 430
3 104 Dhoni 410
4 105 Eva 470
5 106 Faruq 440

Bearys Institute of Emerging Sciences, Mangalore 13 | P a g e


IV SEMESTER

Bearys Institute of Emerging Sciences, Mangalore 14 | P a g e


IV SEMESTER

PROGRAM 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 neat format.

class Employee:
def GetEmployee(self):
self.empno=int(input('enter employee number : '))
self.name=input('enter employee name : ')
self.depname=input('enter the department name : ')
self.designation=input('enter the designation : ')
self.age=int(input('enter the age : '))
self.salary=int(input('enter the basic salary : '))
def PutEmployee(self):
print(self.empno,"\t",self.name,"\t",self.depname,"\t",self.designation,"\t",self.age,"\t",self.s
alary)
def SearchEmp(self,num):
if (num==self.empno):
return True
else:
return False
n=int(input('enter the number of employees : '))
EmpList=list()
for i in range(n):
Emp=Employee()
Emp.GetEmployee()
EmpList.append(Emp)
print("emp no\t name\t dept\t designation\t age\t salary\t")
print("****************************************************")
for E in EmpList:
E.PutEmployee()
num=int(input('enter the employee number to be searched : '))
for E in EmpList:
found=E.SearchEmp(num)
if(found):
E.PutEmployee()
break
if(not(found)):
print('employee does not exist')

Bearys Institute of Emerging Sciences, Mangalore 15 | P a g e


IV SEMESTER

OUTPUT:
enter the number of employees : 3
enter employee number : 101
enter employee name : Raj
enter the department name : IT
enter the designation : Manager
enter the age : 25
enter the basic salary : 120000
enter employee number : 102
enter employee name : Ravi
enter the department name : CS
enter the designation : Executive
enter the age : 24
enter the basic salary : 289000
enter employee number : 103
enter employee name : Ram
enter the department name : IT
enter the designation : Employee
enter the age : 35
enter the basic salary : 239800
emp no name dept designation age salary
****************************************************
101 Raj IT Manager 25 120000
102 Ravi CS Executive 24 289000
103 Ram IT Employee 35 239800
enter the employee number to be searched: 103
103 Ram IT Employee 35 239800

Bearys Institute of Emerging Sciences, Mangalore 16 | P a g e


IV SEMESTER

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

from sys import exit


class BankAccount:
def __init__(self):
self.balance=5000

def deposit(self):
amount=float(input("Enter the amount to be deposited:"))
if amount>0:
self.balance = self.balance + amount
else:
print("Enter valid amount.Transaction Failed")

def withdraw(self):
amount=float(input("Enter the amount to withdraw:"))
if self.balance-amount>500:
self.balance = self.balance - amount
else:
print("Insufficient Balance.Transaction Failed")
return None

def getBalance(self):
print(f"Current balance={self.balance}")
return None

class SavingsAccount(BankAccount):
def __init__(self):
super().__init__()
self.interest = 0.09

def addInterest(self):
print(f"Updated balance with interest rate ={self.interest} ")

self.balance += self.balance * self.interest


return None

Bearys Institute of Emerging Sciences, Mangalore 17 | P a g e


IV SEMESTER

savAc=SavingsAccount()

while True:
print("--------------------------")

print("1:Deposit Amount \n2:Withdraw Amount \n3:Get Balance \n4:UpdateInterest \n5:Exit ")


choice=int(input("Enter your choice:"))
if choice==1:
savAc.deposit()
elif choice==2:
savAc.withdraw()
elif choice==3:
savAc.getBalance()
elif choice==4:
savAc.addInterest()
elif choice==5:
exit()
else:
print("Invalid Choice ...Try Again..")

OUTPUT:
--------------------------
1:Deposit Amount
2:Withdraw Amount
3:Get Balance
4:UpdateInterest
5:Exit
Enter your choice: 1
Enter the amount to be deposited: 4000
--------------------------
1:Deposit Amount
2:Withdraw Amount
3:Get Balance
4:Update Interest
5:Exit
Enter your choice: 3
Current balance=9000.0
--------------------------
1:Deposit Amount
2:Withdraw Amount
3:Get Balance
4:Update Interest
5:Exit

Bearys Institute of Emerging Sciences, Mangalore 18 | P a g e


IV SEMESTER

Enter your choice: 2


Enter the amount to withdraw: 1000

--------------------------
1:Deposit Amount
2:Withdraw Amount
3:Get Balance
4:Update Interest
5:Exit
Enter your choice: 4

Updated balance with interest rate =0.09


--------------------------
1:Deposit Amount
2:Withdraw Amount
3:Get Balance
4:UpdateInterest
5:Exit
Enter your choice: 3
Current balance=8720.0
--------------------------
1:Deposit Amount
2:Withdraw Amount
3:Get Balance
4:Update Interest
5:Exit
Enter your choice: 5

Bearys Institute of Emerging Sciences, Mangalore 19 | P a g e


IV SEMESTER

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

from tkinter import*


def clear_all():
principle_field.delete(0,END)
rate_field.delete(0,END)
time_field.delete(0,END)
compound_field.delete(0,END)
principle_field.focus_set()

def calculate_ci():
principle=int(principle_field.get())
rate=float(rate_field.get())
time=int(time_field.get())
CI=principle*(pow((1+rate/100),time))
compound_field.insert(10,CI)

if __name__=="__main__":
root=Tk()
root.configure(background='light green')
root.geometry("400x250")
root.title("Compound interest calculator")

label1=Label(root,text="Principle Amount(Rs): ",fg='black',bg='red')


label1.grid(row=1,column=0,padx=10,pady=10)

label2=Label(root,text="Rate(%): ",fg='black',bg='red')
label2.grid(row=2,column=0,padx=10,pady=10)

Bearys Institute of Emerging Sciences, Mangalore 20 | P a g e


IV SEMESTER

label3=Label(root,text="Time(years): ",fg='black',bg='red')
label3.grid(row=3,column=0,padx=10,pady=10)

label4=Label(root,text="Compound Interest: ",fg='black',bg='red')


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

principle_field=Entry(root)
principle_field.grid(row=1,column=1,padx=10,pady=10)

rate_field=Entry(root)
rate_field.grid(row=2,column=1,padx=10,pady=10)

time_field=Entry(root)
time_field.grid(row=3,column=1,padx=10,pady=10)

compound_field=Entry(root)
compound_field.grid(row=5,column=1,padx=10,pady=10)
button1=Button(root,text="Submit",bg="red",fg="black",command=calculate_ci)
button1.grid(row=4,column=1,pady=10)

button2=Button(root,text="clear",bg="red",fg="black",command=clear_all)
button2.grid(row=6,column=1,pady=10)
root.mainloop()

Bearys Institute of Emerging Sciences, Mangalore 21 | P a g e


IV SEMESTER

OUTPUT:

Bearys Institute of Emerging Sciences, Mangalore 22 | P a g e


IV SEMESTER

PROGRAM 4
4. Write a GUI program to implement 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=""
except:
equation.set("error")
expression=""
def clear():
global expression
expression=""
equation.set("")

if __name__=="__main__":
gui=Tk()
gui.configure(background="purple")
gui.title("Simple Calculator")
gui.geometry("300x300")
equation=StringVar()

expression_field=Entry(gui, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=70)

button1=Button(gui, text='1',fg='black',bg='red',command=lambda:press(1),height=1,width=7)

button1.grid(row=2,column=0)

button2=Button(gui, text='2',fg='black',bg='red',command=lambda:press(2),height=1,width=7)
button2.grid(row=2,column=1)

button3=Button(gui, text='3',fg='black',bg='red',command=lambda:press(3),height=1,width=7)
button3.grid(row=2,column=2)

Bearys Institute of Emerging Sciences, Mangalore 23 | P a g e


IV SEMESTER

button4=Button(gui, text='4',fg='black',bg='red',command=lambda:press(4),height=1,width=7)
button4.grid(row=3,column=0)

button5=Button(gui, text='5',fg='black',bg='red',command=lambda:press(5),height=1,width=7)
button5.grid(row=3,column=1)

button6=Button(gui, text='6',fg='black',bg='red',command=lambda:press(6),height=1,width=7)
button6.grid(row=3,column=2)

button7=Button(gui, text='7',fg='black',bg='red',command=lambda:press(7),height=1,width=7)
button7.grid(row=4,column=0)

button8=Button(gui, text='8',fg='black',bg='red',command=lambda:press(8),height=1,width=7)
button8.grid(row=4,column=1)

button9=Button(gui, text='9',fg='black',bg='red',command=lambda:press(9),height=1,width=7)
button9.grid(row=4,column=2)

button0=Button(gui, text='0',fg='black',bg='red',command=lambda:press(0),height=1,width=7)
button0.grid(row=5,column=0)

plus= Button(gui, text='+',fg='black',bg='red',command=lambda:press("+"),height=1,width=7)


plus.grid(row=2,column=3)

minus= Button(gui, text='-',fg='black',bg='red',command=lambda:press("-"),height=1,width=7)


minus.grid(row=3,column=3)

multiply= Button(gui, text='*',fg='black',bg='red',command=lambda:press("*"),height=1,width=7)


multiply.grid(row=4,column=3)

divide= Button(gui, text='/',fg='black',bg='red',command=lambda:press("/"),height=1,width=7)


divide.grid(row=5,column=3)

equal= Button(gui, text='=',fg='black',bg='red',command=equalpress,height=1,width=7)


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

clear= Button(gui, text='clear',fg='black',bg='red',command=clear,height=1,width=7)


clear.grid(row=5,column='1')

Decimal= Button(gui, text='.',fg='black',bg='red',command=lambda:press("."),height=1,width=7)


Decimal.grid(row=6,column=0)

gui.mainloop()

Bearys Institute of Emerging Sciences, Mangalore 24 | P a g e


IV SEMESTER

OUTPUT:

Bearys Institute of Emerging Sciences, Mangalore 25 | P a g e


IV SEMESTER

PROGRAM 5
5.Create a table student table (regno, name and marks in 3 subjects) using MySQL and perform
the followings a. To accept the details of students and store it in database. b. To display the
details of all the students c. Delete particular student record using regno.

import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="123456",database="student"
)
mycursor=con.cursor()
def student_exists(regno):
sql='select * from student where regno=%s'
c=con.cursor(buffered=True)
data=(regno,)
c.execute(sql,data)
r=c.rowcount
if r==1:
return True
else:
return False
def Add_student():
regno=input("enter student register number:")
if(student_exists(regno==True)):
print("student already exists \n Try AGAIN \n")
else:
name=input('Enter student name')
mark1=input("enter mark in subject 1")
mark2=input("enter mark in subject 2")
mark3=input("enter mark in subject 3")

data=(regno,name,mark1,mark2,mark3)
sql='insert into student values(%s,%s,%s,%s,%s)'

Bearys Institute of Emerging Sciences, Mangalore 26 | P a g e


IV SEMESTER

c=con.cursor()c.execute(sql,data)
con.commit()
print("Student added successfully")
def display_student():
sql='select * from student'
c=con.cursor()
c.execute(sql)
r=c.fetchall()
if r:
for i in r:
print("student Regno :",i[0])
print("student name:",i[1])
print("mark in subject 1 :",i[2])
print("mark in subject 2 :",i[2])
print("mark in subject 3 :",i[2])
print("---------------------------------------------------------------------------")
else:
print("no record exists..")
def remove_student():
regno=input("enter student register number:")
if(student_exists(regno==False)):
print("student does not exists \n Try AGAIN \n")
else:
sql='delete from student where regno=%s'
data=(regno,)
c=con.cursor()
c.execute(sql,data)
con.commit()
print(" Student Removed ..")
def menu():
print('select \n 1. to add new student \n 2. to display all student \n 3.to remove student \n 4.to exit
')
ch=int(input('Enter your choice'))
if ch==1:
Add_student()
elif ch==2:
display_student()
elif ch==3:
remove_student()
elif ch==4:import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="123456",database="student"
)
mycursor=con.cursor()
def student_exists(regno):
sql='select * from student where regno=%s'

Bearys Institute of Emerging Sciences, Mangalore 27 | P a g e


IV SEMESTER

c=con.cursor(buffered=True)

data=(regno,)
c.execute(sql,data)

r=c.rowcount
if r==1:
return True
else:
return False
def Add_student():
regno=input("enter student register number:")
if(student_exists(regno==True)):
print("student already exists \n Try AGAIN \n")
else:
name=input('Enter student name')
mark1=input("enter mark in subject 1")
mark2=input("enter mark in subject 2")
mark3=input("enter mark in subject 3")

data=(regno,name,mark1,mark2,mark3)
sql='insert into student values(%s,%s,%s,%s,%s)'
c=con.cursor()
c.execute(sql,data)
con.commit()
print("Student added successfully")

def display_student():
sql='select * from student'
c=con.cursor()
c.execute(sql)
r=c.fetchall()
if r:
for i in r:
print("student Regno :",i[0])
print("student name:",i[1])
print("mark in subject 1 :",i[2])
print("mark in subject 2 :",i[2])
print("mark in subject 3 :",i[2])
print("---------------------------------------------------------------------------")
else:

Bearys Institute of Emerging Sciences, Mangalore 28 | P a g e


IV SEMESTER

print("no record exists..")

def remove_student():
regno=input("enter student register number:")
if(student_exists(regno==False)):
print("student does not exists \n Try AGAIN \n")
else:
sql='delete from student where regno=%s'
data=(regno,)
c=con.cursor()
c.execute(sql,data)
con.commit()
print(" Student Removed ..")

def menu():
print('select \n 1. to add new student \n 2. to display all student \n 3.to remove student \n 4.to exit
')
ch=int(input('Enter your choice'))
if ch==1:
Add_student()
elif ch==2:
display_student()
elif ch==3:
remove_student()
elif ch==4:
exit()
else:
print("invalid")
menu()
menu()

output:
select 1. to add new student
2. to display all student
3.to remove student
4.to exit
Enter your choice 1
enter student register number: 1002
Enter student name John
enter mark in subject 1 65
enter mark in subject 2 78
enter mark in subject 3 55
Student added successfully select

Bearys Institute of Emerging Sciences, Mangalore 29 | P a g e


IV SEMESTER
1. to add new student
2. to display all student
3.to remove student
4.to exit
Enter your choice 2

student Regno : 1001


student name: miza
mark in subject 1 : 85
mark in subject 2 : 85
mark in subject 3 : 85
-------------------------------------------------------------------------
student Regno : 1002
student name: John
mark in subject 1 : 65
mark in subject 2 : 65
mark in subject 3 : 65
------------------------------------------------------------------------
select
1. to add new student
2. to display all student
3.to remove student
4.to exit
Enter your choice 3
enter student register number: 1002
Student Removed ..

select
1. to add new student
2. to display all student
3.to remove student
4.to exit
Enter your choice 4

DataBase:

Bearys Institute of Emerging Sciences, Mangalore 30 | P a g e


IV SEMESTER

PROGRAM 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

import mysql
import mysql.connector as mb
mb=mysql.connector.connect(host="localhost",user="root",password="123456",database="employe
e")
mycursor=mb.cursor(buffered=True)
while True:
print("1.Insert Employee data")
print("2.Display Employee by employee number")
print("3.display employee by range of salary")
print("4.exit")
ch=int(input("enter your choice"))
if ch==1:
try:
empno=input("Enter employee number ")
name=input("enter Employee name")
salary=int(input("Enter employee salary"))
if salary>0:
sql="insert into employee (empno,name,salary) values(%s,%s,%s)"
mycursor.execute(sql,(empno,name,salary))
mb.commit()
print("data are entered...")
print()

else:
print("salary should not less than oe equal to 0")
except Exception as e:

print(e)

Bearys Institute of Emerging Sciences, Mangalore 31 | P a g e


IV SEMESTER

print()
elif ch==2:
s_empno=input("Enter the emp number to be searched employee data:")
try:
sql2="""select * from employee where empno=%s"""%(s_empno)
mycursor.execute(sql2)
print()

s_result=mycursor.fetchall()
if s_result==[]:
print("no record found")
else:
print("EMPNO \t \t \t NAME\t \t \t SALARY")
print('-------------------------------------------------------------------------------------------------')
for row2 in s_result:
print(f"{row2[0]}\t\t\t{row2[1]}\t\t\t{row2[2]}")
print()
mycursor.reset()
except Exception as e:
print(e)
mycursor.reset()
print()
elif ch==3:
st_range=int(input("starting range of salary:"))
end_range=int(input("ending range of salary:"))
try:
sql3="""select * from employee where salary between %s and %s """%(st_range,end_range)
mycursor.execute(sql3)
print("EMPNO \t\t NAME \t\t SALARY")
print('---------------------------------------------------------------------------------------------------')
for row3 in mycursor.fetchall():
print(f"{row3[0]}\t\t\t\t{row3[1]}\t\t\t\t{row3[2]} ")
print()
except Exception as e:
print(e)

elif ch==4:
mycursor.reset()
mycursor.close()
mb.close()
print("My Sql connection is closed")
print("program ending")
break;
else:
print("wrong choice..")

Bearys Institute of Emerging Sciences, Mangalore 32 | P a g e


IV SEMESTER

Output:
1.Insert Employee data
2.Display Employee by employee number
3.display employee by range of salary
4.exit

enter your choice 1


Enter employee number 1004
enter Employee name John
Enter employee salary 20000
data are entered...

1.Insert Employee data


2.Display Employee by employee number
3.display employee by range of salary
4.exit
enter your choice 2
Enter the emp number to be searched employee data:1001
EMPNO NAME SALARY
-------------------------------------------------------------------------
1001 miza 15000

1.Insert Employee data


2.Display Employee by employee number
3.display employee by range of salary
4.exit
enter your choice 3
starting range of salary:10000
ending range of salary:25000
EMPNO NAME SALARY
-------------------------------------------------------------------------
1001 miza 15000
1003 mazz 20000
1004 John 20000

1.Insert Employee data


2.Display Employee by employee number
3.display employee by range of salary
4.exit
enter your choice 2 Enter the emp number to be searched employee
data:1002

Bearys Institute of Emerging Sciences, Mangalore 33 | P a g e


IV SEMESTER

EMPNO NAME SALARY


------------------------------------------------------------------------
1002 SANEEM 30000

1.Insert Employee data


2.Display Employee by employee number
3.display employee by range of salary
4.exit

DataBase:

Bearys Institute of Emerging Sciences, Mangalore 34 | P a g e


IV SEMESTER

PROGRAM 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 Particular Customer using below criteria.

import mysql.connector

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

cursor=mydb.cursor()

def create_table():

create_query="""CREATE TABLE IF NOT EXISTS electricity_bill(tariff_code varchar(5) not


null,customer_name varchar(20),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")

def insert_customer_details(cursor,tariff_code,customer_name):

query="""insert into electricity_bill(tariff_code,customer_name) values (%s,%s)"""

val=(tariff_code,customer_name)

cursor.execute(query,val)

mydb.commit()

Bearys Institute of Emerging Sciences, Mangalore 35 | P a g e


IV SEMESTER

print("Customer deatils inserted successfully")

def display_customer_details(cursor,meter_number):

query="select * from electricity_bill where meter_number=%s"

cursor.execute(query,(meter_number,))

result=cursor.fetchone()

if result:

print("customer Details:")

print("----------------------")

print("Tariff Code:",result[0])

print("Customer Name:",result[1])

print("meter number",result[2])

print("previous reading",result[3])

print("current reding",result[4])

print("---------------------------------")

else:

print("customer not found")

def update_customer_details(cursor,meter_number,previous_reading,current_reading):

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

def display_all_customer_details(cursor):

query="select * from electricity_bill"

cursor.execute(query)

results=cursor.fetchall()

if results:

print("all customers details")

print("---------------------------")

Bearys Institute of Emerging Sciences, Mangalore 36 | P a g e


IV SEMESTER

for result in results:

print("Tariff Code:",result[0])

print("Customer Name:",result[1])

print("meter number",result[2])

print("previous reading",result[3])

print("current reding",result[4])

print("---------------------------------------")

else:

print("no records found")

def delete_table(cursor):

query="drop table electricity_bill"

cursor.execute(query)

mydb.commit()

print("all records deleted successfully")

def calculate_bill_amount(cursor,meter_number):

query="select * from electricity_bill where meter_number=%s"

cursor.execute(query,(meter_number,))

result=cursor.fetchone()

if result:

print("customer Details:")

print("----------------------")

print("Tariff Code:",result[0])

print("Customer Name:",result[1])

print("meter number",result[2])

print("previous reading",result[3])

print("current reding",result[4])

if(result[3]==None and result[4]==None):

print("previous and current readings are not updated")

return

units_consumed=result[4]-result[3]

print("Units consumed:",units_consumed)

Bearys Institute of Emerging Sciences, Mangalore 37 | P a g e


IV SEMESTER

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

if(units_consumed>=101 and units_consumed<=200):

bill_amt=units_consumed*6

if(units_consumed>200):

bill_amt=units_consumed*7.5

print("Bill amount Rs:",bill_amt)

query="""update electricity_bill set units_counsumed=%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")

def main():

create_table()

Bearys Institute of Emerging Sciences, Mangalore 38 | P a g e


IV SEMESTER

while True:

print("1.Insert customer details\n 2.display customer_details by meter-number\n 3.update


customer details by meter number\n 4.display all customer details\n 5.calculate bill for customer\n
6.delete table permanently\n 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)

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 thn or equal to previous reading")

else:

break

update_customer_details(cursor,meter_number,previous_reading,current_reading)

Bearys Institute of Emerging Sciences, Mangalore 39 | P a g e


IV SEMESTER

elif choice=='4':

display_all_customer_details(cursor)

elif choice=='5':

meter_number = int(input("Enter Meter-Number of the customer: "))

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

cursor.close()

mydb.close()

if __name__ == "__main__":

main()

Output:
Table electricity_bill created successfully
1.Insert customer details
2.display customer_details by meter-number
3.update customer details by meter number
4.display all customer details
5.calculate bill for customer
6.delete table permanently
7.exit
enter your choice:1
enter customer name:raheez
enter tariff-code(LT1/LT2):LT2

Bearys Institute of Emerging Sciences, Mangalore 40 | P a g e


IV SEMESTER

Customer deatils inserted successfully


1.Insert customer details
2.display customer_details by meter-number

3.update customer details by meter number


4.display all customer details
5.calculate bill for customer
6.delete table permanently
7.exit
enter your choice:2
enter meter number of the customer:4
customer Details:
----------------------
Tariff Code: LT2
Customer Name: raheez
meter number 4
previous reading None
current reding None
---------------------------------
1.Insert customer details
2.display customer_details by meter-number
3.update customer details by meter number
4.display all customer details
5.calculate bill for customer
6.delete table permanently
7.exit
enter your choice:3
enter meter number:4
enter previous reading500
enter current reading1000
customer details updated successfully
1.Insert customer details
2.display customer_details by meter-number
3.update customer details by meter number
4.display all customer details
5.calculate bill for customer
6.delete table permanently
7.exit
enter your choice:4
all customers details
---------------------------
Tariff Code: LT1
Customer Name: saif
meter number 1
previous reading 450
current reding 500
---------------------------------------
Tariff Code: LT1
Customer Name: cummins
meter number 2
previous reading 650
current reding 750
---------------------------------------

Bearys Institute of Emerging Sciences, Mangalore 41 | P a g e


IV SEMESTER

Tariff Code: LT2


Customer Name: starc
meter number 3
previous reading 300
current reding 550
---------------------------------------
Tariff Code: LT2
Customer Name: raheez

meter number 4
previous reading 500
current reding 1000
---------------------------------------
1.Insert customer details
2.display customer_details by meter-number
3.update customer details by meter number
4.display all customer details
5.calculate bill for customer
6.delete table permanently
7.exit
enter your choice:5
Enter Meter-Number of the customer: 4
customer Details:
----------------------
Tariff Code: LT2
Customer Name: raheez
meter number 4
previous reading 500
current reding 1000
Units consumed: 500
Bill amount Rs: 3750.0
customer bill updated successfully
1.Insert customer details
2.display customer_details by meter-number
3.update customer details by meter number
4.display all customer details
5.calculate bill for customer
6.delete table permanently
7.exit

Bearys Institute of Emerging Sciences, Mangalore 42 | P a g e


IV SEMESTER

PROGRAM 8
Consider following data and draw the bar graph using matplot library.(Use CSV or Excel).Add the data
Using GUI.

Display appropriate title for axis and chart. Also show legends..

import tkinter as tk

from tkinter import ttk

from tkinter import messagebox

import pandas as pd

import matplotlib.pyplot as plt

def callback():

with open('cricket_data.csv','w') as f:

f.truncate()

with open('batsman_scores.csv','w') as file:

file.write("batsman,2017,2018,2019,2020")

batsman_entry.unbind('<Visibility>')

def add_data():

batsman=batsman_entry.get()

scores=[int(score_entry_2017.get()),(score_entry_2018.get()),

(score_entry_2019.get()),(score_entry_2020.get())]

with open('batsman_scores.csv','a') as file:

file.write(f'\n{batsman},{",".join(map(str,scores))}')

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

batsman_entry.delete(0,'end')

score_entry_2017.delete(0, 'end')

Bearys Institute of Emerging Sciences, Mangalore 43 | P a g e


IV SEMESTER

score_entry_2018.delete(0, 'end')

score_entry_2019.delete(0, 'end')

score_entry_2020.delete(0, 'end')

batsman_entry.focus_set()

def plot_graph():

data=pd.read_csv('batsman_scores.csv')

batsmen=data['batsman']

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

years=list(data.columns[1:])

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

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

Bearys Institute of Emerging Sciences, Mangalore 44 | P a g e


IV SEMESTER

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

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

Bearys Institute of Emerging Sciences, Mangalore 45 | P a g e


IV SEMESTER

Output:

batsman_scores.csv file

Bearys Institute of Emerging Sciences, Mangalore 46 | P a g e

You might also like