Cs Practicals

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 54

Assignment 1: Write a python program using function to pass list to a

function and double the odd values and half even values of a list and display
elements of list after changing.
def splitevenodd(A):
evenlist=[]
oddlist=[]
for i in A:
if(i%2==0):
evenlist.append(i//2)
else:
oddlist.append(i*i)
print("Even List:",evenlist)
print("Odd List:",oddlist)
A=list()
n=int(input("Enter the size of the List::"))
print("Enter the Elements of LIst::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
splitevenodd()
Output:
Assignment 2: Write a Python program input n numbers in tuple and count
how many even and odd numbers are entered.
l=[]
S=int(input("Please Enter the Total Number of
Elements :"))
for i in range(S):
value = int(input("Please enter the %d Element of
list1:"%i))
l.append(value)
numbers=tuple(l)
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Numbers of even numbers:",count_even)
print("Numbers of odd numbers:",count_odd)
Output:
#Assignment3: Write a menu driven program in python to delete the name of a
student from the dictionary and to search the phone no of a student-by-student
name. Create menu as below:
******MENU******
1.Delete from dictionary
2.Search Phone number using name from Dictionary
3.Exit
phonebook = dict()
while True:
print("******MENU******\n")
print("1: Delete from Dictionary")
print("2: Search Phone number using name from Dictionary")
print("3: Exit\n")
ch = int(input("Enter your choice: "))
if ch == 1:
n = int(input("Enter total number of friends: "))
i = 1
while i <= n:
a = input("Enter name: ")
b = int(input("Enter phone number: "))
phonebook[a] = b
i += 1
print(phonebook)
print("-------------------------------")

name = input("Enter the name to delete:")


del phonebook[name]
k = phonebook.keys()
print("Phonebook Information")
print("------------------------------")
print("Name", "\t", "Phone Number")
for i in k:
print("i", "\t", "phonebook[i]")
if ch == 2:
name = input("Enter the name to search: ")
f = 0
for i in phonebook.keys():
if i == name:
print(f"\nPhone Number={phonebook[i]}\n")
f = 1
if f == 0:
print("Given name does not exist")
if ch == 3:
break

Output:
#Assignment 4: Write a menu driven program to do following
MENU
1: Reverse String
2: Check whether string is palindrome
3: Make half string in Uppercase
4: Exit
Output:
#Assignment 5: Write a program to read a list of n integers (positive as well
as negative). Create two new lists, one having all positive numbers with sum
and the other having all negative numbers with sum from the given list.
list1=[ ]
plist1=[ ]
nlist1=[ ]
sum=0
sum1=0
n=int(input("how many elements u want in list:"))
for i in range(0,n):
a=int(input("enter item in list:"))
list1.append(a)
print("original list is :",list1)
for i in range(0,n):
if list[i]<0:
nlist1.append(list1[i])
sum=sum+list1[i]
else:
list1.append(list1[i])
sim1=sum1+list1[i]
print("positive list is;',plist1)
print("sum pf +ve numbers:',sum1)
print("negative list is;',nlist1)
print("sum of -ve numbers:',sum)
Output:
#Assignment 6: Write a Python program to remove duplicates from a list.
a = []
n = int(input("how many elements do you want in list: "))
for i in range(0, n):
n1 = int(input("enter item in list"))
a.append(n1)
print("original list is: ", a)
print("list after removing duplicate elements: ")
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
Output:
#Assignment 7: Write a menu driven program to generate random numbers
given in a specific range and to display calendar after giving month and year.
import random
import calendar
while True:
print("********MENU********\n")
print("1:Random number generators")
print("2:Calender of a month")
print("3:Exit\n")
ch = int(input("enter your choice:"))
if ch == 1:
num = 10
start = 20
end = 40
res = []
for j in range(num):
res.append(random.randint(start, end))
print(res)
if ch == 2:
yy = int(input("enter year:"))
mm = int(input("enter month:"))
print(calendar.month(yy, mm))
if ch == 3:
break
Output:
#Assignment 8:
Write a python program to read and displays file content line by line with each
word separated by #.

file = input("Enter the file:")


f = open(file, "r")
item = []
for line in f:
words = line.split()
for i in words:
item.append(i)
print("#".join(item))

Output:
#Assignment 9: Write a python program Read a text file and display the
number of vowels/consonants/uppercase/lowercase alphabets in the file.

Output:
#Assignment 10: Write a python code that accepts a filename and copies all
lines that do not start with a lowercase letter from the first file into the second.

fin = open('oldfile.txt', 'r')


fout = open('newbie.txt', 'w')
text = fin.readlines()

for line in text:


if line[0].isalpha() and line[0] not in
'abcdefghijklmnopqrstuvwxyz':
fout.write(line)

fin.close()
fout.close()

Output:
#Assignment 11: Write a python program to remove all the lines that contain
the character ‘a’ in a file and write it to another file.
file = open("file.txt", "w")
file.write("Harry Potter")
file.write(
"There is a difference in all harry potter books \n We can
see it as harry grows \n the books were written by J.K
Rowling"
)
file.close()
file = open("file.txt", "r")
docx = open("docx.txt", "w")
len = docx.readlines()
for i in len:
if "a" in i:
i = i.replace("a", "")
file.write(i)
file.close()
docx.close()
Output:
#Assignment 12: Write a python program to create a binary file with name and roll
number. search for a given roll number and display name, if not found display
appropriate message.

Output:
Enter roll number: 24
Enter Name: Himanshu Deep
Wish to enter more record(Y/N): Y
Enter roll number:15
Enter Name: Satyam
Wish to enter more record(Y/N): N
Enter roll no. to be searched:24
Name Himanshu Deep
#Assignment 13: Write a python program to create a binary file with roll
number, name and marks. Input a roll number and update name and marks.
import pickle

while True:

rollno = int(input("Enter roll number:"))

name = input("Enter Name:")

marks = int(input("Enter Marks:"))

rec = {"Rollno": rollno, "Name": name, "Marks": marks}

# Writing the Dictionary

f = open("student1.dat", "ab")

pickle.dump(rec, f)

ch = input("Wish to enter more record (Y/N):")

if ch == "N" or ch == "n":

break

f.close()

f = open("student1.dat", "rb+")

found = 0

r = int(input("Enter roll no to search :"))

try:

while True:

rec = pickle.load(f)

if rec["Rollno"] == r:

print("Current name is:", rec["Name"])

print("Current Marks are:", rec["Marks"])

rec["Name"] = input("Enter new name:")

rec["Marks"] = int(input("Enter newmarks:"))

found = 1

break

except EOFError:

print("End of file")

if found == 1:
f.seek(0)

pickle.dump(rec, f)

print("Record updated")

f.close()

Output:
Assignment 14: Write a menu driven python program to create a CSV
file by entering dept-id, name and city, read and search the record for
given dept-id.
MENU
1. Create csv
2. Search
3.Exit

import csv
while True:
print("***MENU***\n")
print("1: create csv file")
print("2: Search as per id")
print("3: Exit")
ch = int(input("Enter choice: "))

if ch == 1:
f = open("dept.csv", "a")
mywriter = csv.writer(f, delimiter=",")
ans = "y"
while ans.lower() == "y":
rno = int(input("Enter dept no.: "))
name = input("Enter dept name: ")
clas = input("Enter city: ")
mywriter.writerow([rno, name, clas])
print("## Data Saved ##")
ans = input("Add More?: ")
f.close()

if ch == 2:
print("Search a Record")
print("=========================")
f = open(
"dept.csv", "r", newline="\r\n"
) # Remove new line character from output
r = input("Enter DEPT no. you want to searc: ")
s = csv.reader(f)
for rec in s:
if rec[0] == r:
print("Dept no.=", rec[0])
print("Dept name=", rec[1])
print("city", rec[2])
f.close()
if ch == 3:
break
Output:
Assignment 15: .Write a Menu
driven program in python to count spaces, digits, words and lines from
text file try.txt

while True:
print("***MENU***\n")
print("1: count spaces")
print("2: count digits")
print("3: count words")
print("4: count lines")
print("5: exit")
ch = int(input("Enter your choice: "))
if ch == 1:
F1 = open("abc.txt", "r")
c = 0
F = F1.read()
for letter in F:
if letter.isspace():
c = c + 1
print("No. of spaces are: ", c)
F1.close()
if ch == 2:
F1 = open("abc.txt", "r")
c = 0
F = F1.read()
for letter in F:
if letter.isdigit():
c = c + 1
print("No. of digits are: ", c)
F1.close()
if ch == 3:
F1 = open("abc.txt", "r")
linesList = F1.readlines()
c = 0
for line in linesList:
wordsList = line.split()
print(wordsList)
c += len(wordsList)
print("The Number of words in this file are: ",
c)
F1.close()
if ch == 4:
c = 0
F1 = open("abc.txt", "r")
data = F1.readlines()
print(data)
for line in data:
c += 1
print("Number of lines: ", c)
F1.close()
if ch == 5:
break
Assignment 16: Write a python program using the function PUSH (Arr),
where Arr is a list of numbers. From this list push all numbers divisible by
5 into a stack implemented by using a list. Display the stack if it has at
least one element, otherwise display appropriate error messages.

def isEmpty(Arr):
if len(Arr) == 0:
return True
else:
return False
def push(Arr, item):
if item % 5 == 0:
Arr.append(item)
top = len(Arr) - 1
def show(Arr):
if isEmpty(Arr):
print("No item found")
else:
t = len(Arr) - 1
print("(TOP)", end="")
while t >= 0:
print(Arr[t], "<==", end="")
t = t - 1
print()
Arr = []
top = None
while True:
print("******STACK IMPLEMENTATION USING LIST******")
print("1:PUSH")
print("2:Show")
print("0:Exist")
ch = int(input("Enter choice:"))
if ch == 1:
val = int(input("Enter no to push:"))
push(Arr, val)
elif ch == 2:
show(Arr)
elif ch == 0:
print("Bye")
break
Output:
Assignment 17: Write a python program using function POP(Arr),
where Arr is a stack implemented by a list of numbers. The function
returns the value deleted from the stack.

def isEmpty(Arr):
if len(Arr)==0:
return True
else:
return False

def push(Arr,item):
Arr.append(item)
top=len(Arr)-1

def pop(Arr):
if isEmpty(Arr):
return 'Underflow'
else:
val = Arr.pop()
if len(Arr)==0:
top = None
else:
top=len(Arr)-1
return val

def show(Arr):
if isEmpty(Arr):
print('no item found')
else:
t = len(Arr)-1
print('(TOP)',end="")
while t>=0:
print(Arr[t],'<==',end='')
t=t-1
print()

Arr=[]
top = None
while True:
print("******** STACK IMPLEMENTATION USING
LIST********")
print('1:PUSH')
print('2:POP')
print('3:SHOW')
print('0:EXIT')
ch=int(input("Enter choice: "))

if ch==1:
val=int(input("Enter no to push: "))
push(Arr,val)
elif ch==2:

val=pop(Arr)
if val=='Underflow':
print('Stack is empty: ')
else:
print("\nDeleted item is: ",val)

elif ch==3:
show(Arr)
elif ch==0:
print('Bye')
break
Output:
Assignment 18:
Consider the table FLIGHT given below. Write commands in SQL for
Table: PRODUCTS
FLCOD START DESTINATIO NO_STOPS NO_FLIGHTS
E N
IC101 DELHI AGARTALA 1 5
IC102 MUMBAI SIKKIM 1 3
IC103 DELHI JAIPUR 0 7
IC105 KANPUR CHENNAI 2 2
IC107 MUMBAI KANPUR 0 4
IC431 INDORE CHENNAI 3 2
IC121 DELHI AHEMDABAD 2 6

● Display details of all flights starting from Delhi.


● Display details of flights that have more than 4 number of flights
operating.
● Display flight codes, starting place, destination, number of flights in
descending order of number of flights.
● Add a column “Remarks” in given table FLIGHT.
● Remove all records which have less than one stop from FLIGHT.
ANSWERS:

● Select * from FLIGHT where start=”DELHI” ;


● Select * from FLIGHT where NO_FLIGHTS>4;
● Select flcode, start, destination, no_flights from
FLIGHT order by NO_FLIGHTS desc;
● Alter table flight add remarks varchar(20);
● Delete from FLIGHT where NO_STOP<1;
Assignment 19:
CONSIDER FOLLOWING SQL TABLE AND GIVE ANSWERS
TABLE: FLIGHTS

FL_NO STARTING ENDING NO_FLIGHTS NO STOPS

IC301 MUMBAI DELHI 8 0

IC799 BANGALORE DELHI 2 1

MC101 INDORE MUMBAI 3 0

IC302 DELHI MUMBAI 8 0

AM812 KANPUR BANGALORE 3 1

IC899 MUMBAI KOCHI 1 4

AM501 DELHI TRIVANDRUM 1 5

MU499 MUMBAI MADRAS 3 3

IC701 DELHI AHMEDABAD 4 0

TABLE: FARES

FL_NO AIRLINES FARE TAX

IC701 Indian Airlines 6500 10

MU499 Sahara 9400 5

AM501 Jet Airways 13450 8

IC899 Indian Airlines 8300 4

IC302 Indian Airlines 4300 10

IC799 Indian Airlines 10500 10


(i) Display FL_NO and NO_FLIGHTS from “KANPUR” to “BANGALORE” from the table
FLIGHTS.
-> SELECT FL_NO, NO_FLIGHTS FROM FLIGHTS WHERE
STARTING=’KANPUR’ AND ENDING=’BANGALORE’;
(ii) ARRANGE THE CONTENTS OF THE TABLE FLIGHTS IN THE ASCENDING ORDER OF FL_NO.
-> SELECT * FROM FLIGHTS ORDER BY FL _NO;
(iii) DISPLAY THE MINIMUM FARE “INDIAN AIRLINES” IS OFFERING FROM THE TABLE FARES.
->SELECT MIN(FARE) FROM FARES WHERE AIRLINES ‘INDIAN
AIRLINES’;
(iv) DISPLAY THE FLIGHT NUMBERS OF NON-STOP FLIGHTS.
->SELECT FL_NO FROM FLIGHTS WHERE NO STOPS NOT EQUAL TO 0;
(v) DISPLAY THE AVERAGE FARE FOR EACH AIRLINE.
-> SELECT AVG(FARE) FROM FARES GROUP BY AIRLINES;
(vi) DISPLAY THE STARTING POINT AND DESTINATION OF FLIGHTS WITH DESCENDING
ORDER OF THE TAX PAID FOR THEM.
->SELECT STARTING, ENDING FROM FLIGHTS WHERE
FLIGHTS.FL_NO=FARES.FL NO ORDER BY TAX DESC
(vii) INCREASE THE FARE OF FLIGHTS GOING TO BANGALORE BY 5%.
-> UPDATE FARES SET FARE= FARE+(FARE* 0.05) WHERE
ENDING=’BANGALORE’ AND FLIGHTS.FL_NO=FARES.FL_NO;
(viii) GIVE DISCOUNT TO THE FLIGHTS BY DECCAN AIRLINES BY 2%.
-> UPDATE FARES SET FARE=FARE-(FARE *0.02) WHERE
AIRLINE=’DECCAN AIRLINES’
(ix) DELETE ALL THE FLIGHTS GOING TO AHMEDABAD.
-> DELETE FROM FLIGHTS WHERE ENDING LIKE=’AHMEDABAD’
Assignment 20:
Write sql queries for 1 to 5 which are based on the table: PRODUCTS AND
SUPPLIERS
Table: PRODUCTS
PID PNAME QTY PRICE COMPANY SUPCODE
101 DIGITAL CAMERA 120 1200 RENIX S01
14X 0
102 DIGITAL PAD 11i 100 2200 DIGI POP S02
0
104 PEN DRIVE 16 GB 500 1100 STOREKING S01
106 LED SCREEN 32 70 2800 DISPEXPERTS S02
0
105 CAR GPS SYSTEM 60 1200 MOVEON S03
0

Table: SUPPLIERS
SUPCODE SNAME CITY
S01 GET ALL INC KOLKATA
S03 EASY MARKET CORP DELHI
S02 DIGI BUSY GROUP CHENNAI

● To arrange and display all the records of table products on the basis of product name
in the ascending order.
● To display product name and price of all those products whose price is in the range
of 10000 and 15000(both values inclusive)
● TO display the price, products name and quantity (i.e,qty) of those products which
are having quantity more than 100.
● To display the names of those suppliers who are either from DELHI or from
CHENNAI.
● TO display the maximum and minimum price of products.

ANSWERS:

● Select * from products order by Pname ;


● select Pname, price from products where price between
10000 and 15000;
● select price, pname, quantity from products WHERE
quantity > 100;
● SELECT SNAME FROM SUPPLIERS WHERE CITY=”DELHI” OR
CITY=”CHENNAI”.
● SELECT MAX(PRICE),MIN(PRICE) FROM PRODUCTS;
Assignment 21:
Write sql queries for 1 to 5 which are based on the table: EMPLOYEES AND
EMPSALARY
Table: EMPLOYEES
EMPID FIRSTNAME LASTNAME ADDRESS CITY
010 George Smith 83 First Street Howard
105 Mary Jones 842VineAve Losantville

152 Sam Tones 33 Elm st Paris


215 Sarah Ackerman 440 U.S. 110 Upton
244 Manila Sengupta 24 FriendsStreet New Delhi
300 Robert Samuel 9 Fifth Cross Washington
335 Henry Williams 12 Moore Street Boston
400 Rachel Lee 121 Harrison New York

441 Peter Thompsons 11 Red road Paris

Table: EMPSALARY
EMPID SALARY BENIFITS DESIGNATION
010 75000 15000 Manager
105 65000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
441 28000 7500 Salesman

1. To display Firstname, Lastname, Address and City of the employees living in Paris
from the table EMPLOYEES.
2. To display the content of EMPLOYEES table in descending order of FIRSTNAME.
3. To display the Firstname, Lastname and Total Salary of all the managers from the
table where total salary is calculated as salary + Benefits.
4. To display the maximum salary among Managers and Clerks from table EMPSALARY
5. To display all records from both the table by using natural join
ANSWER:
1. SELECT FIRSTNAME, LASTNAME, ADDRESS, CITY FROM EMPLOYEES
WHERE CITY=”PARIS”;

2. SELECT * FROM EMPLOYEES ORDER BY FIRSTNAME DESC;

3. SELECT FIRSTNAME, LASTNAME ,SALARY+BENEFITS AS


TOTAL_SALARY FROM EMPLOYEES, EMPSALARY WHERE
DISGNATION=”MANAGER” AND EMPLOYEES.EMPID=EMPSALARY.EMPID;

4. SELECT DESIGNATION MAX(SALARY) FROM EMPSALARY WHERE


DESIGNATION=”MANAGER” OR DESIGNATION=”CLERK”;

5. SELECT E.*,M.* FROM EMPLOYEES E NATURAL JOIN EMPSALARY M;


Assignment 22:
Write sql queries for 1 to 5 which are based on the table: DEVELOPER AND
HOUSE.
DEVELOPER
DCOD DNAM
E E
1 Rahul
2 Manis
h
3 Faizan

HOUSE
HI LOCATION QUANTIT UNIT_PRIC DCOD
D Y E E
H Raipur 10 500000 1
1
H Bilaspur 20 300000 2
2
H Bargarh 15 200000 3
3
H Ambikapu 25 250000 2
4 r
H Raipur 25 280000 2
5
H Bilaspur 20 240000 1
6

i. Show details of Raipur location house whose unit_price equal 300000


-> SELECT*FROM HOUSE WHERE LOCATION=’RAIPUR’ AND
UNIT_PRICE =30000;
ii. Show location, gross amount of houses whose decode is 2
-> SELECT LOCATION, QUANTITY*UNIT_PRICE AS” GROSS AMOUNT”
FROM HOUSE WHERE DCODE=2;
iii. ShowHID ,location of all houses in decreasing order of unit_prices
SELECT HID ,LOCATION FROM HOUSE ORDER BY UNIT_PRICE
DESC;
iv. Show average unit_price of each location...
-> SELECT LOCATION,AVG(UNIT_PRICE)FROM HOUSE,DEVELOPER
v. To show location and corresponding dname whose unit_price is equal
250000
-> SELECT LOCATION,DNAME FROM HOUSE,DEVELOPER WHERE
HOUSE.DCODE=DEVELOPER.DCODE AND UNIT_PRICE=250000;
Assignment 23: Integrate MySQL with Python by importing the MySQL
module and add records of students and display all the records.

import os
import platform
import mysql.connector

mydb=mydb.connector.connect(host='localhost',
user='root', passwd='123',database='student')
print(mydb
mycursor=mydb.cursor()

def stulnert():
L=[]
roll=int(input('ENTER THE ROLL NUMBER:'))
L.append(roll)
name-input('ENTER THE NAME:')
L.append(name)
age=int(input('ENTER THE AGE OF STUDENT:'))
L.appent(age)
clas=input('ENTER THE CLASS:')
L.append(clas)
stud=(L)
sql='insert into stud(roll,name,age,clas) values
(%s,%s,%s,%S)'
mycursor.execute(sql,stud)
mydb.commit()

def stuview():
mycursor.excute('select * from stud')
myrus=mycursor.fetchall()
for x in myrus:
print(x)

def MenuSet(): #Funtion for the student management


systum
print('Enter 1: To add student')
print ('Enter 2: To view students')
userInput=int(input('Please select an option:'))
#Will take input from user
if (userInput==1):
stuInsert()
if (userInput==2):
stuview()
Menuset()

def runAgain():
runagn=input('\n Want to run again Y/N:')
while(runagn.lower()=="y"):
if (platform.system()=="Windows")
print(os.system('clas'))
else:
print(os.system("clear"))
MenuSet()

def runAgain():
runagn=input('\n Want to run again Y/N:')
while(runagn.lower()=="y"):
if (platform.system()=="Windows")
print(os.system('clas'))
else:
print(os.system("clear"))
MenuSet()
runagn=input('\n Wnat to run again Y/N:')
runagn()
Assignment 24: Integrate MySQL with Python by importing the MySQL
module to search using roll no, name, age, class and if present in table
display the record, if not display appropriate method.
import mysql.connector
import os
import platform

mydb = mysql.connector.connect(
host="localhost", user="root", passwd="123",
database="student"
)
cursor = mydb.cursor()
def stuview():
print("Select the search criteria: ")
print("1. Roll")
print("2. Name")
print("3. Age")
print("4. Class")
print("5. All")
ch = int(input("Enter the choice: "))
if ch == 1:
s = int(input("Enter the roll no: "))
cursor.execute(f"select * from stud where
roll={s}")
elif ch == 2:
s = input("Enter Name: ")
cursor.execute(f'select * from stud where
name="{s}"')
elif ch == 3:
s = int(input("Enter Age: "))
cursor.execute(f"select * from stud where age={s}")
elif ch == 4:
s = int(input("Enter the class"))
cursor.execute(f"select * from stud where class =
{s}")
elif ch == 5:
cursor.execute("select * from stud")
res = cursor.fetchall()
print("The Students details are as follows: ")
print("(Roll,Name,Age,Class)")
for x in res:
print(x)

def menuSet():
print("Enter 1: To Search Student")
userInput = int(input("Please Select an above
option: "))
if userInput == 1:
stuview()
runAgain()

def runAgain():
runAgn = input("\nWant to run agin y/n: ")
if runAgn.lower() == "y":
print(platform.system())
if platform.system() == "Windows":
print(os.system("cls"))
menuSet()
else:
print(os.system("clear"))
menuSet()
menuSet()
Assignment 25: Integrate SQL with Python by importing the MySQL module to
search a student using roll no, delete the record.
import mysql.connector
import os
import platform

print(os.system("apple"))
mydb = mysql.connector.connect(
host="localhost", user="root", passwd="password",
database="mayank"
)
cursor = mydb.cursor()

def removeStu():
roll = int(input("Enter the roll no to ev deleted: "))
cursor.execute(f"delete from stud where roll={roll}")
print("RECORD DELETED!!!")
mydb.commit()

def stuview():
print("Select the search criteria: ")
print("1. Roll")
print("2. Name")
print("3. Age")
print("4. Class")
print("5. All")
ch = int(input("Enter the choice: "))
if ch == 1:
s = int(input("Enter the roll no: "))
cursor.execute(f"select * from stud where roll={s}")
elif ch == 2:
s = input("Enter Name: ")
cursor.execute(f'select * from stud where name="{s}"')
elif ch == 3:
s = int(input("Enter Age: "))
cursor.execute(f"select * form stud where age={s}")
elif ch == 4:
s = int(input("Enter the class"))
cursor.execute(f"select * from stud where class =
{s}")
elif ch == 5:
cursor.execute("select * from stud")
res = cursor.fetchall()
print("The Students details are as follows: ")
print("(Roll,Name,Age,Class)")
for x in res:
print(x)

def menuSet():
print("Enter 1: To Search Student")
print("Enter 2: To Delete Student")
userInput = int(input("Please Select an above option: "))
if userInput == 1:
stuview()
if userInput == 2:
removeStu()

def runAgain():
runAgn = input("\nWant to run agin y/n: ")
if runAgn.lower() == "y":
print(platform.system())
if platform.system() == "Windows":
print(os.system("cls"))
else:
print(os.system("clear"))
menuSet()
runAgn = input("\nWant to run agin y/n: ")

menuSet()
runAgain()
Assignment 26: Integrate SQL with Python by importing the MySQL
module to search a student using roll no, update the record.
import mysql.connector as mycon
cn = mycon.connect(
host="localhost", user="root", passwd="root",
database="student", charset="utf8"
)
cur = cn.cursor()
print("Welcome to studen Details Updation screen...")

print("*********************EDIT STUDENT
DETAILS************************")
ro = int(input("Enter Student's roll number to edit: "))
query = "select * from stud where roll=" + str(ro)
cur.execute(query)
results = cur.fetchall()
if cur.rowcount <= 0:
print("\n## SORRY! NO MATCHING DETAILS AVILABLE ##")
else:
print("********************************************")
print("%5s" % "ROLLNO.", "%15s" % "NAME", "%12s" % "AGE",
"%10s" % "CLASS")
print("********************************************")
for row in results:
print("%5s" % row[0], "%15s" % row[1], "%12s" %
row[2], "%10s" % row[3])
print("-" * 50)
ans = input("Are you sure to update? (y/n): ")
if ans == "y" or "Y":
d = input("Enter new name to update(enter old value if
not to update): ")
s = int(input("Enter new age to update (enter old
value if not to update): "))
query = f"update stud set name={d}, age={str(s)} where
roll={str(ro)}"
cur.execute(query)
cn.commit()
print("\n## RECORD UPDATED ##")

You might also like