Professional Documents
Culture Documents
Final Python Record
Final Python Record
Final Python Record
INDEX
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 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.
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.
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.
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']
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")
OUTPUT:
CALCULATE SHAPE AREA
ENTER A SHAPE TO FIND ITS AREA : rectangle
ENTER THE LENGTH :25
ENTER THE BREADTH :40
AREA OF RECTANGLE = 1000
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
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}
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")
OUTPUT:
ENTER A SENTENCE FOR STRING_1: Hello sir
ENTER A SENTENCE FOR STRING_2: Hellu sur
THE TWO STRINGS ENTERED ARE NOT EQUAL
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()
OUTPUT:
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()
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.
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)
OUTPUT:
Rollno Student_Name Total Marks
0 101 Akhil 450
1 102 Basu 480
2 103 charlie 430
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')
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
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.
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} ")
savAc=SavingsAccount()
while True:
print("--------------------------")
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
--------------------------
1:Deposit Amount
2:Withdraw Amount
3:Get Balance
4:Update Interest
5:Exit
Enter your choice: 4
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.
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")
label2=Label(root,text="Rate(%): ",fg='black',bg='red')
label2.grid(row=2,column=0,padx=10,pady=10)
label3=Label(root,text="Time(years): ",fg='black',bg='red')
label3.grid(row=3,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()
OUTPUT:
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)
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)
gui.mainloop()
OUTPUT:
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)'
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'
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:
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
select
1. to add new student
2. to display all student
3.to remove student
4.to exit
Enter your choice 4
DataBase:
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)
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..")
Output:
1.Insert Employee data
2.Display Employee by employee number
3.display employee by range of salary
4.exit
DataBase:
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():
cursor.execute(create_query)
mydb.commit()
def insert_customer_details(cursor,tariff_code,customer_name):
val=(tariff_code,customer_name)
cursor.execute(query,val)
mydb.commit()
def display_customer_details(cursor,meter_number):
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:
def update_customer_details(cursor,meter_number,previous_reading,current_reading):
val=(previous_reading,current_reading,meter_number)
cursor.execute(query,val)
mydb.commit()
def display_all_customer_details(cursor):
cursor.execute(query)
results=cursor.fetchall()
if results:
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:
def delete_table(cursor):
cursor.execute(query)
mydb.commit()
def calculate_bill_amount(cursor,meter_number):
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])
return
units_consumed=result[4]-result[3]
print("Units consumed:",units_consumed)
if(result[0]=='LT1'):
bill_amt=units_consumed*2
bill_amt=units_consumed*3.5
bill_amt=units_consumed*4.5
if(units_consumed>200):
bill_amt=units_consumed*5
elif(result[0]==LT2):
bill_amt=units_consumed*3.5
bill_amt=units_consumed*5
bill_amt=units_consumed*6
if(units_consumed>200):
bill_amt=units_consumed*7.5
val=(units_consumed,bill_amt,meter_number)
cursor.execute(query,val)
mydb.commit()
else:
def main():
create_table()
while True:
if choice=='1':
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:
elif choice=='2':
display_customer_details(cursor,meter_number)
elif choice=='3':
while True:
if(current_reading<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':
calculate_bill_amount(cursor,meter_number)
if(ans=='y'):
delete_table(cursor)
break
else:
continue
break
else:
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
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
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
import pandas as pd
def callback():
with open('cricket_data.csv','w') as f:
f.truncate()
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())]
file.write(f'\n{batsman},{",".join(map(str,scores))}')
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()
def plot_graph():
data=pd.read_csv('batsman_scores.csv')
batsmen=data['batsman']
years=list(data.columns[1:])
# Plotting
fig,ax = plt.subplots()
label=batsmen[i])
ax.set_xticklabels(years)
ax.legend()
plt.show()
root = tk.Tk()
root.title("Batsman Scores")
batsman_entry = ttk.Entry(root)
batsman_entry.bind('<Visibility>', callback())
score_entry_2017 = ttk.Entry(root)
#score_entry_2017.insert(0, "0")
score_entry_2018 = ttk.Entry(root)
score_entry_2019 = ttk.Entry(root)
score_entry_2020 = ttk.Entry(root)
root.mainloop()
Output:
batsman_scores.csv file