[go: up one dir, main page]

0% found this document useful (0 votes)
98 views50 pages

12th Practical File For Print - 23-24

The document contains 10 programs that demonstrate working with functions and file handling in Python. The programs cover: 1. Defining functions to perform arithmetic operations and calling them to calculate results 2. A menu-driven program using functions to calculate area of shapes like circles, squares, rectangles 3. A random number generator function that simulates rolling a dice 4. Functions demonstrating cursor positioning when reading/writing to a text file 5. Counting the number of words in a text file 6. Reading a text file and displaying each word separated by a delimiter 7. Copying lines of a text file that do not contain a specific character to a new file 8. Counting the total lines
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views50 pages

12th Practical File For Print - 23-24

The document contains 10 programs that demonstrate working with functions and file handling in Python. The programs cover: 1. Defining functions to perform arithmetic operations and calling them to calculate results 2. A menu-driven program using functions to calculate area of shapes like circles, squares, rectangles 3. A random number generator function that simulates rolling a dice 4. Functions demonstrating cursor positioning when reading/writing to a text file 5. Counting the number of words in a text file 6. Reading a text file and displaying each word separated by a delimiter 7. Copying lines of a text file that do not contain a specific character to a new file 8. Counting the total lines
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

1

Part 1 working with functions

Arithmetic Operations using function

Program 1 :- Write a program using function that receives two number and return
the result of all the arithmetic operations(+,-,*,/,%) .

Source Code:-

# Arithmetic operations using python function


def add():
result = val1 + val2
return result
def sub():
result = val1 - val2
return result
def mul():
result = val1 * val2
return result
def div():
result = val1 / val2
return result
def f_div():
result = val1 // val2
return result
def mod():
result = val1 % val2
return result

result = 0
print("**** Arithmetic operations using python function ****")
val1 = float(input("Enter the first value :"))
val2 = float(input("Enter the second value :"))
op = input("Enter any one of the operator (+,-,*,/,//,%)")
if op == "+":
res = add()
elif op == "-":
res = sub()
elif op == "*":
res = mul()
elif op == "/":
if val2 == 0:
print("Please enter a value other than 0")
else:
res = div()

1
2

elif op == "//":
res = f_div()
elif op == "%":
res = mod()
else:
print("Invalid option")
print("The result is :",res)

Output:

Menu driven program to calculate area


Program 2 :- Write a menu driven program to calculate : Area of circle [A=πr2] Area
of square [A=a*a] Area of rectangle [A=l*b]

Source Code:-

# Menu driven program using python function


def circle(r):
return 3.14*r*r
def square(a):
return a*a
def ractangle(l,b):
return l*b

while 1:
print("="*50)
print("***Menu driven program using python function***")
print("1 To calculate Area of circle [A=πr2]")

2
3

print("2 To calculate Area of square [A=a*a]")


print("3 To calculate Area of rectangle [A=l*b]")
print("="*50)
n=int(input("Enter your Choice(1,2,3): "))
if n==1:
r=float(input("Enter the radius:-"))
area=circle(r)
print("Area of Circle:=",area)
elif n==2:
s=float(input("Enter the side length:-"))
area=square(s)
print("Area of square:=",area)
elif n==3:
l=float(input("Enter the value of l:-"))
b=float(input("Enter the value of b:-"))
area=ractangle(l,b)
print("Area of ractangle:=",area)
else:
print("Your choice is Wrong")
ch=input("Y/N : ")
if ch=='n' or ch=='N':
break

Output:

3
4

Random number generator

Program 3 :- Write a random number generator that generates random numbers


between 1 and 6 (simulates a dice).

Source Code:-

# random number generator


# that generates random numbers between 1 and 6
# (simulates a dice)
import random
def roll():
min = 1

max = 6
roll_again = "y"
while roll_again == "y" or roll_again == "Y":
print("Rolling the dice...")
val = random.randint (min, max)
print("You get... :", val)
roll_again = input("Roll the dice again? (y/n)...")
print(" Random number generator")
print(" -----------------------")
roll()

Output:

4
5

Part 2 Data file handling

Cursor position

Program 4 :- Write a program to know the cursor position and print the text
according to the below-given specifications:
a. Print the initial position
b. Move the cursor to 4th position
c. Display next 5 characters
d. Move cursor to next 10 characters
e. Print the current cursor position
f. Print next 10 characters from current position

Source Code:-

#seek() and tell() functions


print("Know the cursor position using seek() and tell()\n")
f = open("intro.txt","r")
print("Cusror initial position.")
print(f.tell())
f.seek(4,0)
print("Displaying values from 5th position.")
print(f.read(5))
f.seek(10,0)
print(f.tell())
print("Print cursor's current postion")
print(f.seek(7,0))
print("Displaying next 10 characters from cursor's current postion.")
print(f.read(10))

# seek(7,0)
##0: sets the reference point at the beginning of the file
##1: sets the reference point at the current file position
##2: sets the reference point at the end of the file

5
6

Output:

Count number of words in a file

Program 5 :- Write a program to count number of words in a file.

Source Code:-

# program to count number of words in a file


fin=open("intro.txt",'r')
str=fin.read()
L=str.split()
count_words=0
print(" *** Counting number of words in a file *** \n")
print("Content of file:-",str)
for i in L:
count_words=count_words+1
print("Total no.of Words:-",count_words)

6
7

Output:

Display file content line by line with each word separated by “ # ”

Program 6: Program to read and display file content line by line with each word
separated by “ # ”

Source Code:-

# Program to read and display file content


# line by line with each word separated by “#”
f = open("intro.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()

7
8

Output:

Copy to another file

Program 7:- Write a program to copy all the lines that not contain the character `a' in
a file and write it to another file.

Source Code:-

# copy all the lines


# that not contain the character `a' in a file
f1 = open("d:intro.txt")
f2 = open("d:file2copy.txt","w")

for line in f1:


if 'a' not in line:
f2.write(line)

8
9

print("File copied")
f1.close()
f2.close()

Output:

Count characters in text file

Program 8:- Write a program to count a total number of lines and count the total
number of lines starting with 'A', 'B', and 'C' from the file intro.txt.

Source Code:-

def starting_with():
with open("intro.txt","r") as f1:
data=f1.readlines()
cnt_lines=0
cnt_A=0
cnt_B=0
cnt_C=0
for lines in data:
cnt_lines+=1
if lines[0]=='A':
cnt_A+=1
if lines[0]=='B':
cnt_B+=1
if lines[0]=='C':
cnt_C+=1
print("""
Reading the text file to display\n""")

9
10

print("Total Number of lines are:",cnt_lines)


print("Total Number of lines starting with A are:",cnt_A)
print("Total Number of lines starting with B are:",cnt_B)
print("Total Number of lines starting with C are:",cnt_C)
starting_with()

Output:

Binary file – Store and Search

Program 9:- Program to create binary file to store Rollno and Name, Search any
Rollno and display name if Rollno found otherwise “Rollno not found” .

Source Code:-

# Write & Search a record in binary file


import pickle
student = []
f = open('student.dat','ab')
ans ='y'
while ans.lower() == 'y':
roll = int(input("Enter roll number:"))
name = input("Enter name:")
student.append([roll,name])
ans = input("Add more?(y)")
pickle.dump(student,f)
f.close()
print()
f = open('student.dat','rb')
student = []
while True:
try:

10
11

student=pickle.load(f)
except EOFError:
break
ans ='y'
while ans.lower() =='y':
found = False
print("Searching a record in binary file")
print("---------------------------------")
r = int(input("Enter roll number to search:"))
for s in student:
if s[0] == r:
print("Name is :",s[1])
found = True
ans = 'n'
break
if not found:
print("Sorry,roll number not found")
ans = input("Search more(y)?:")
f.close()

Output:

11
12

Binary file – Store and Update

Program 10:- Program to create binary file to store Rollno,Name and Marks and
update marks of entered Rollno.

Source Code:-

# Write & update a record in binary file


import pickle
student = []
f = open('student.dat','ab')
ans ='y'
while ans.lower() == 'y':
roll = int(input("Enter roll number:"))
name = input("Enter name:")
student.append([roll,name])
ans = input("Add more?(y)")
pickle.dump(student,f)
f.close()
print()

f = open('student.dat','rb')
student = []
while True:
try:
student=pickle.load(f)
except EOFError:
break
ans ='y'
while ans.lower() =='y':
found = False
print("Updating a record in the binary file")
print("------------------------------------")
r = int(input("Enter roll number to search:"))
for s in student:
if s[0] == r:
replace = input("Enter new name to update: ")
s[1] = replace
print("Record Updated")
print("--------------")
print("Roll Number : ", s[0])
print("Name : ", s[1])
print()
found = True
ans = 'n'

12
13

break
if not found:
print("Sorry,roll number not found\n")
ans = input("Search more(y)?:")
f.close()

Output:

Binary file – Display records based on condition

Program 11:- Write a program to write data into binary file marks.dat and display
the records of students who scored more than 95 marks.

Source Code:-

# Write & search binary file with a criteria


import pickle
def search_95plus():
f = open("marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
if s[2]>95:
cnt+=1

13
14

print("Record:",cnt)
print("RollNO:",s[0])
print("Name:",s[1])
print("Marks:",s[2])
except Exception:
f.close()

def add_rec():
f = open("marks.dat","ab")
x = True
while x:
rn=int(input("Enter the rollno:"))
sname=input("Enter the name:")
marks=int(input("Enter the marks:"))
rec=[]
data=[rn,sname,marks]
rec.append(data)
pickle.dump(rec,f)

ch=input("Wnat more records?(y/n):")


if ch.lower() == 'n':
x = False
f.close()
while True:
print("""
1. Write into binary file
2. search_95plus()
3. Exit """)
choice = int(input("Enter your choice: "))
if choice == 1:
add_rec()
elif choice == 2:
search_95plus()
elif choice == 3:
break
else:
print("Invalid choice")

14
15

Output:

CSV file – Write and Search

Program 12 :- Write a program to perform write and search operations with .csv file.

Source Code:-

#write and search csv file


import csv
with open('myfile.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number:- "))
name=input("Enter Employee Name:- ")
salary=int(input("Enter Employee Salary:-"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##\n")

ans=input("Add More ?")

ans='y'
while ans=='y':
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
found=False
e = int(input("Enter Employee Number to search :"))

15
16

for row in myreader:


if len(row)!=0:
if int(row[0])==e:
print("============================")
print(" Search Result ")
print(" ------------- ")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True

if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (y)")

Output:

CSV file – Create and Update

Program 13 :- Create a CSV file by entering user-id and password, and update the
password for given user- id.

Source Code:-

#write, search & update csv file


import csv
with open("accounts.csv", "w", newline = '') as obj:

16
17

fileobj = csv.writer(obj,delimiter=',')
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue

# Displaying all the records in the file


with open("accounts.csv", "r") as obj:
file = csv.reader(obj)
print("\n Contents of the file\n")
for row in file:
print(row)

ans ='y'
while ans:
with open("accounts.csv", "r") as obj:
file = csv.reader(obj)
print("Search and Update a record")
print("--------------------------")
search = input("Enter the user id to be searched\n")
found = "false"
for row in file:
if row[0] == search:
print("Account id found!")
update = input("Enter new password to replace: ")
row[1] = update
print("Updated password for account id ", row[0], " is ", row[1])
found = "true"
break
if found == "false":
print("Account id ", row[0], " is not found")
ans = input("Update more records ? (y)")

17
18

Output:

Part 3 Data Structure

Stack Implementation

Program 14 :- Write a menu-driven python program to implement stack operation.

Source Code:-

# menu driven program to implement stack operation


def main_menu():
while True:
print()
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))
print()
if ch==1:
el = int(input("Enter the value to push an element:"))
push(s,el)

elif ch==2:

18
19

e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
elif ch==3:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False
def push(stk,e):
stk.append(e)
top = len(stk)-1
def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
def peek(stk):

19
20

if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
#main program begins
s=[]
main_menu()

Output:

20
21

Stack for employee details

Program 15 :- Write a program to implement a stack for the employee details


(empno, name).

Source Code:-

# program to implement a stack for the employee details (empno, name)


def isEmpty():
global stk
if stk==[]:
print("Stack is empty!!!")
else:
None

def push():
global stk
global top
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
top=len(stk)-1

def display():
global stk
global top
if top==-1:
isEmpty()
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])

def pop_ele():
global stk
global top
if top==-1:
isEmpty()
else:
e = stk.pop()
print("Element popped:",e)
top=top-1

def main_menu():

21
22

while True:
print("\n Stack Implementing for the employee details")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice:"))
print()
if ch==1:
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
elif ch==4:
break
else:
print("Invalid Choice")
#main program begins
stk=[]
top=-1
main_menu()

22
23

Output:

23
24

Part 4 SQL Queries

Part B: 5 sets of SQL queries using one/two tables

Queries Set 1 (Database Fetching records)


[1] Consider the following MOVIE table and write the SQL queries based on it.

Production Business
Movie_ID MovieName Type ReleaseDate
Cost Cost

The Kashmir Files Action 2022/01/26 1245000 1300000


M001
M002 Attack Action 2022/01/28 1120000 1250000

M003 Looop Lapeta Thriller 2022/02/01 250000 300000

M004 Badhai Do Drama 2022/02/04 720000 68000

Shabaash
M005 Biography 2022/02/04 1000000 800000
Mithu

M006 Gehraiyaan Romance 2022/02/11 150000 120000

1. Display all information from movie.


2. Display the type of movies.

3. Display movieid, moviename, total_eraning by showing the business done


by the movies. Claculate the business done by movie using the sum of
productioncost and businesscost.

4. Display movieid, moviename and productioncost for all movies


with productioncost greater thatn 150000 and less than
1000000.

5. Display the movie of type action and romance.

6. Display the list of movies which are going to release in February,


2022.

24
25

Output:
[1] select * from movie;

2. select distinct from a movie;

3. select movieid, moviename, productioncost + businesscost “total earning” from


movie;

25
26

4. select movie_id,moviename, productioncost from movie where product is >150000


and <1000000;

5. select moviename from movie where type =‟action‟ or type=‟romance‟;

6. select moviename from moview where month(releasedate)=2;

26
27

Queries Set 2 (Based on Functions)


1. Write a query to display cube of 5.

2. Write a query to display the number 563.854741 rounding off to the next
hundred.

3. Write a query to display “put” from the word “Computer”.

4. Write a query to display today‟s date into DD.MM.YYYY format.

5. Write a query to display „DIA‟ from the word “MEDIA”.

6. Write a query to display moviename – type from the table movie.

7. Write a query to display first four digits of productioncost.

8. Write a query to display last four digits of businesscost.


9. Write a query to display weekday of release dates.

10. Write a query to display dayname on which movies are going to be released.

27
28

Output:
[1] select pow(5,3);

[2] select round(563.854741,-2);

[2] select round(563.854741,-2);

[3] select mid(“Computer”,4,3);

28
29

[4] select concat(day(now()),concat(„.‟,month(now()),concat(„.‟,year(now())))) “Date”;

[5] select right(“Media”,3);

[6] select concat(moviename,concat(„ – „,type)) from movie;

[7] select left(productioncost,4) from movie;

29
30

[8] select right(businesscost,4) from movie;

[9] select weekday(releasedate) from movie;

[10] select dayname(releasedate) from movie;

30
31

Queries Set 3 (DDL Commands)

Suppose your school management has decided to conduct cricket matches


between students of Class XI and Class XII. Students of each class are asked to
join any one of the four teams – Team Titan, Team Rockers, Team Magnet and
Team Hurricane. During summer vacations, various matches will be conducted
between these teams. Help your sports teacher to do the following:

1. Create a database “Sports”.


2. Create a table “TEAM” with following considerations:

It should have a column TeamID for storing an integer value between 1 to 9,


which refers to unique identification of a team.

Each TeamID should have its associated name (TeamName), which should
be a string of length not less than 10 characters.

Using table level constraint, make TeamID as the primary key.


Show the structure of the table TEAM using a SQL statement.

As per the preferences of the students four teams were formed as given
below. Insert these four rows in TEAM table:

Row 1: (1, Tehlka)

Row 2: (2, Toofan)

Row 3: (3, Aandhi)


Row 3: (4, Shailab)

Show the contents of the table TEAM using a DML statement.

3. Now create another table MATCH_DETAILS and insert data as shown below.
Choose appropriate data types and constraints for each attribute.
SecondTeam
MatchID MatchDate FirstTeamID Second FirstTeam
TeamID Score Score

M1 2021/12/20 1 2 107 93

M2 2021/12/21 3 4 156 158

M3 2021/12/22 1 3 86 81

M4 2021/12/23 2 4 65 67

M5 2021/12/24 1 4 52 88

M6 2021/12/25 2 3 97 68

31
32

Output:
[1] create database sports

[2] Creating table with the given specification create


table team (teamid int(1),
teamname varchar(10),
primary key(teamid));
Showing the structure of table using SQL statement: desc team;

Inserting data:
mqsql> insert into team
values(1,'Tehlka');

Show the content of table – team:

32
33

select * from team;

[3] Creating another table:

create table match_details


-> (matchid varchar(2) primary key,
-> matchdate date,
-> firstteamid int(1) references team(teamid),
-> secondteamid int(1) references team(teamid),
-> firstteamscore int(3),
-> secondteamscore int(3));

33
34

Queries set 4 (Based on Two Tables)

1. Display the matchid, teamid, teamscore whoscored more than 70 in first ining along
with team name.

2. Display matchid, teamname and secondteamscore between 100 to 160.

3. Display matchid, teamnames along with matchdates.

4. Display unique team names

5. Display matchid and matchdate played by Anadhi and Shailab.

[1] select match_details.matchid, match_details.firstteamid,


team.teamname,match_details.firstteamscore from match_details, team where
match_details.firstteamid=team.teamid and match_details.firstteamscore>70;

[2] select matchid, teamname, secondteamscore from match_details, team where


match_details.secondteamid=team.teamid and match_details.secondteamscore between
100 and 160;

34
35

[3] select matchid,teamname,firstteamid,secondteamid,matchdate from

match_details, team where match_details.firstteamid=team.teamid;

[4] select distinct(teamname) from match_details, team where


match_details.firstteamid=team.teamid;

[5] select matchid,matchdate from match_details, team where


match_details.firstteamid=team.teamid and team.teamname in
(„Aandhi‟,‟Shailab‟);

35
36

Queries Set 5 (Group by , Order By)


Consider the following table stock table to answer the queries:

itemno item dcode qty unitprice stockdate

S005 Ballpen 102 100 10 2018/04/22

S003 Gel Pen 101 150 15 2018/03/18

S002 Pencil 102 125 5 2018/02/25

S006 Eraser 101 200 3 2018/01/12

S001 Sharpner 103 210 5 2018/06/11

S004 Compass 102 60 35 2018/05/10

S009 A4 Papers 102 160 5 2018/07/17

1. Display all the items in the ascending order of stockdate.

2. Display maximum price of items for each dealer individually as per


dcode from stock.

3. Display all the items in descending orders of itemnames.

4. Display average price of items for each dealer individually as per


dcode from stock which average price is more than 5.

5. Display the sum of quantity for each dcode.

[1] select * from stock order by stockdate;

36
37

[2] select dcode, max(unitprice) from stock group by code;

[3] select * from stock order by item desc;

[4] select dcode,avg(unitprice) from stock group by dcode having


avg(unitprice)>5;

[5] select dcode, sum(qty) from stock group by dcode;

37
38

Part 5 Python Database connectivity

Write a menu-driven program to store data into a MySQL database named shop
and table customer as following:

1. Add customer details

2. Search customer details

3. Update customer details

4. Display all customer details

5. Delete customer details

38
39

Add Records

Write a program to integrate SQL with python by importing the mysql


module and to add records of customer details.

Source Code:-

import mysql.connector as ms

db=ms.connect(host="localhost",user="root",password="0000")
cn=db.cursor()
cn.execute("create database if not exists shop")
cn.execute("use shop")
cn.execute("create table if not exists customer(cid int, cname varchar(20), city
varchar(20), bill_amt int, cat varchar(20))")
db.commit()

def insert_rec():
try:
while True:
cid=int(input("Enter customer id:"))
cname=input("Enter name:")
city=input("Enter city:")
bill_amt=float(input("Enter bill amount:"))
cat=input("Enter category:")
cn.execute("insert into customer
values({},'{}','{}',{},'{}')".format(cid,cname,city,bill_amt,cat))
db.commit()
print("Inserted rows successfully\n")
ch=input("Want more records? Press (N/n) to stop entry:")
if ch in 'Nn':
break
except Exception as e:
print("Error", e)
insert_rec()

39
40

Output:

Search Records

Write a program to integrate SQL with python by importing the mysql


module and to search customer ID in table “customer” and display record,
if customer ID not found display appropriate message.

Source Code:-

import mysql.connector as ms

db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")

def search_rec():
try:
id=int(input("Enter customer id to search:"))

40
41

query = "select * from customer where cid = {}".format(id)


cn.execute(query)
data=cn.fetchall()
if cn.rowcount == 0:
print("Sorry! Customer ID not found")
else:
for row in data:
print("Name : ", row[1])
print("City : ", row[2])
print("Bill Amount : ", row[3])
print("Category : ", row[4])
print("Name : ", row[5])
except:
pass

search_rec()

Output:

41
42

Update Records

Write a program to integrate SQL with python by importing the mysql


module and to update customer record of entered customer ID.

Source Code:-

import mysql.connector as ms

db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")

def update_rec():
try:
id=int(input("Enter customer id to update:"))
query = "select * from customer where cid = {}".format(id)
cn.execute(query)
data=cn.fetchall()
for i in data:
ci=i[0]
cna=i[1]
ct=i[2]
b=i[3]
c=i[4]
if id==ci:
ch_cname=input("Want to update Name, Press 'Y':")
if ch_cname.lower()=='y':
cname=input("Enter new name:")
else:
cname=cna
ch_city=input("Want to update city, Press 'Y':")
if ch_city.lower()=='y':
city=input("Enter new city:")
else:
city=ct
ch=input("Want to update bill amount, Press 'Y':")
if ch.lower()=='y':
bill_amt=float(input("Enter new bill amount:"))
else:

42
43

bill_amt=b
ch_cat=input("Want to update Category, Press 'Y':")
if ch_cat.lower()=='y':
cat=input("Enter new category:")
else:
cat=c
cn.execute("update customer set cname='{}', city='{}',
bill_amt={},cat='{}'where cid={}".format(cname,city,bill_amt,cat,id))
db.commit()
print("Updated successfully\n")
break
else:
print("Record Not Found...\n")
except Exception as e:
print("Error",e)

update_rec()

Output:

43
44

Display Records

Write a program to integrate SQL with python by importing the mysql


module and to display all the records of table “customer” .

Source Code:-

import mysql.connector as ms

db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")

def view_rec():
try:
cn.execute("select * from customer")
data=cn.fetchall()
cnt=0
for i in data:
cnt=cnt+1
print("Record:",cnt)
print('*'*25)
print("Customer ID:",i[0])
print("Customer Name:",i[1])
print("City:",i[2])
print("Bill Amount:",i[3])
print("Category:",i[4])
print('*'*25)
except Exception as e:
print("Error",e)

view_rec()

44
45

Output:

Delete Records

Write a program to integrate SQL with python by importing the mysql


module and to delete record of entered customer ID.

Source Code:-

import mysql.connector as ms

db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")

45
46

def delete_rec():
try:

cid=int(input("Enter rollno to delete:"))


cn.execute("delete from customer where cid={}".format(cid))
db.commit()
print("Deleted successfully\n")
except Exception as e:
print("Error",e)

delete_rec()

Output:

****** End of Practical File******

46
47

Alter Table

Write a program in python to add new column “contact_no ” of data type


varchar(length=10) in “customer” table already created in Mysql.

Source Code:-

import mysql.connector as ms

db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")

def alter_table():
try:
col_name=input("Enter column name to add: ")
col_type=input("Enter column data type: ")
query = "alter table customer add " + col_name +" "+ col_type
cn.execute(query)
db.commit()
print("\nAlterted table successfully")
print("New Column added\n")
except Exception as e:
print("Error",e)

alter_table()

Output:

47
48

48
49

49
50

50

You might also like