CS Project
CS Project
STD:- 12th
2
CERTIFICATE
3
Sr. Practical Pg. Date Sign
No. No.
1 Write a python program using a function to 8
print factorial number series from n to m
numbers.
2 Write a python program to accept 10
username "Admin" as default argument
and password 123 entered by user to allow
login into the system.
3 Write a python program to demonstrate the 12
concept of variable length argument to
calculate product and power of the first 10
numbers.
4 Create a text file "intro.txt" in python and 14
ask the user to write a single line text by
user input.
5 Write a program to count a total number of 16
lines and count the total number of lines
starting with 'A', 'B', and 'C' from the file
dfh.txt.
6 Write a program to replace all spaces from 18
text with – (dash) from the file intro.txt.
7 Write a program to know the cursor 20
position and print the text according to
below-given specifications:
1. Print the initial position
2. Move the cursor to 4th position
3. Display next 5 characters
4. Move the cursor to the next 10
characters
4
5. Print the current cursor position
6. Print next 10 characters from the current
cursor position.
8 Create a binary file client.dat to hold 22
records like ClientID, Client name, and
Address using the list. Write functions to
write data, read them, and print on the
screen.
9 Write a program to store customer data 24
into a binary file cust.dat using a dictionary
and print them on screen after reading
them. The customer data contains ID as
key, and name, city as values.
10 Write a program to create a binary file 27
sales.dat and write a menu driven program
to do the following:
Insert record
Search Record
Update Record
Display record
Exit
11 Write a function to write data into binary 29
file marks.dat and display the records of
students who scored more than 95 marks.
12 Read a CSV file top5.csv and print the 31
contents in a proper format. The data for
top5.csv file are as following:
5
13 Read a CSV file students.csv and print 33
them with tab delimiter. Ignore first row
header to print in tabular form.
14 Write records of customer into result.csv. 36
The fields are as following:
6
19 Write a menu driven program for Queue 59
Implementation with the following
options:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Exit
20 SQL 1 66
21 SQL 2 70
22 SQL 3 76
23 SQL 4 83
24 SQL 5 88
25 MySQL & PYTHON INTERFACE: Quiz 92
Application
7
PROGRAM-1
‘‘‘Write a python using a function to print factorial number series
from n to m numbers.’’’
INPUT:-
def facto():
n=int(input("Enter the number:"))
f=1
for i in range(1,n+1):
f*=i
print(f, end=" ")
facto()
8
OUTPUT:-
9
PROGRAM-2
‘‘‘Write a python program to accept username "Admin" as default
argument and password 123 entered by user to allow login into the
system.’’’
INPUT:-
def user_pass(password,username="Admin"):
if password=='123':
print("You have logged into system")
else:
print("Password is incorrect!!!!!!")
password=input("Enter the password:")
user_pass(password)
10
OUTPUT:-
11
PROGRAM-3
‘‘‘Write a python program to demonstrate the concept of variable
length argument to calculate product and sum of the first 10
numbers.’’’
INPUT:-
def sum10(*n):
total=0
for i in n:
total=total + i
print("Sum of first 10 Numbers:",total)
sum10(1,2,3,4,5,6,7,8,9,10)
print()
def product10(*n):
pr=1
for i in n:
pr=pr * i
print("Product of first 10 Numbers:",pr)
product10(1,2,3,4,5,6,7,8,9,10)
12
OUTPUT:-
13
PROGRAM-4
‘‘‘Create a text file "intro.txt" in python and ask the user to write a
single line text by user input.’’’
INPUT:-
def program4():
f = open(r"C:\Users\Rajes\Documents \intro.txt","w")
text=input("Enter the text: ")
f.write(text)
f.close()
program4()
14
OUTPUT:-
15
PROGRAM-5
‘‘‘ 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
myfile.txt’’’
INPUT:-
def program5():
with open(r"C:/Users/rajes/.spyder-py3/temp.py","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("Total Number of lines are:",cnt_lines)
print("Total Number of lines strating with A are:",cnt_A)
print("Total Number of lines strating with B are:",cnt_B)
print("Total Number of lines strating with C are:",cnt_C)
program5()
16
OUTPUT:-
17
PROGRAM-6
‘‘‘Write a program to replace all spaces from text with - (dash)
from the file MyFile.txt.’’’
INPUT:-
def program6():
with open(r"C:/Users/rajes/.spyder-py3/temp.py","r") as f1:
data = f1.read()
data=data.replace(' ','-')
with open("intro.txt","w") as f1:
f1.write(data)
with open("intro.txt","r") as f1:
print(f1.read())
program6()
18
OUTPUT:-
19
PROGRAM-7
‘‘‘Write a program to know the cursor position and print the text
according to below-given specifications:
a. Print the initial position
b. Move the cursor to 4th position
c. Display next 5 characters
d. Move the cursor to the next 10 characters
e. Print the current cursor position
f. Print next 10 characters from the current cursor position’’’
INPUT:-
def program7():
f = open(r"C:/Users/rajes/.spyder-py3/temp.py","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))
program7()
20
OUTPUT:-
21
PROGRAM-8
‘‘‘Create a binary file client.dat to hold records like ClientID,
Client name, and Address using the dictionary. Write functions to
write data, read them, and print on the screen.’’’
INPUT:-
import pickle
rec={}
def file_create():
f=open(r"C:\Users\Rajes\Documents\client.dat","wb")
cno = int(input("Enter Client ID:"))
cname = input("Enter Client Name:")
address = input("Enter Address:")
rec={cno:[cname,address]}
pickle.dump(rec,f)
print()
def read_data():
f = open(r"C:\Users\Rajes\Documents\client.dat","rb")
print("Data stored in File. .. ")
print()
rec=pickle.load(f)
for i in rec:
print(rec[i])
file_create()
read_data()
22
OUTPUT:-
23
PROGRAM-9
‘‘‘Write a function to write data into binary file marks.dat and
display the records of students who scored more than 95 marks.’’’
INPUT:-
import pickle
def search_95plus():
f = open(r"C:\Users\Rajes\Documents\marks.dat","wb")
while True:
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("Want more records?Yes: ")
if ch.lower() not in 'yes':
break
f.close()
f = open(r"C:\Users\Rajes\Documents\marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
24
if s[2]>95:
cnt+=1
print("Record:",cnt)
print("RollNO:",s[0])
print("Name:",s[1])
print("Marks:",s[2])
except Exception:
f.close()
search_95plus()
25
OUTPUT:-
26
PROGRAM-10
‘‘‘Write a function to count records from the binary file
marks.dat’’’
INPUT:-
import pickle
def count_records():
f = open(r"C:\Users\Rajes\Documents\marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
cnt+=1
except Exception:
f.close()
print("The file has ", cnt, " records.")
count_records()
27
OUTPUT:-
28
PROGRAM-11
‘‘‘Read a CSV file top5.csv and print the contents in a proper
format. The data for top5.csv file are as following: ’’’
INPUT:-
from csv import reader
def pro11():
with open(r"C:\Users\Rajes\Documents\top5.csv","r") as f:
d = reader(f)
data=list(d)
for i in data:
print(i)
pro11()
29
OUTPUT:-
30
PROGRAM-12
‘‘‘Read a CSV file top5.csv and print them with tab delimiter.
Ignore first row header to print in tabular form.’’’
INPUT:-
from csv import reader
def pro12():
f = open(r"C:\Users\Rajes\Documents\top5.csv","r")
dt = reader(f,delimiter=',')
headr_row=next(dt)
data = list(dt)
f.close()
for i in data:
for j in i:
print(j,"\t",end=" ")
print()
pro12()
31
OUTPUT:-
32
PROGRAM-13
‘‘‘Write records of students into result.csv .The fields are as
following: ’’’
INPUT:-
from csv import writer
def pro13():
f = open(r"C:\Users\Rajes\Documents\result.csv","w",newline='\n')
dt = writer(f)
dt.writerow(['Student_ID','StudentName','Score'])
f.close()
f = open(r"C:\Users\Rajes\Documents\result.csv","a",newline='\n')
while True:
st_id= int(input("Enter Student ID:"))
st_name = input("Enter Student name:")
st_score = input("Enter score:")
dt = writer(f)
dt.writerow([st_id,st_name,st_score])
ch=input("Want to insert More records?(y or Y):")
ch=ch.lower()
if ch !='y':
break
print("Record has been added.")
f.close()
pro13()
33
OUTPUT:-
34
35
PROGRAM-14
‘‘‘Count the number of records and column names present in the
CSV file. Concepts used :-
1. Skip first row using next() method
2. line_num properties used to count the no. of rows’’’
INPUT:-
import csv
def pro14():
fields = []
rows = []
with open(r"C:\Users\Rajes\Documents\result1.csv", newline='') as f:
data = csv.reader(f)
fields = next(data)
print('Field names are:')
for field in fields:
print(field, "\t")
print()
print("Data of CSV File:")
for i in data:
print('\t'.join(i))
print("\nTotal no. of rows: %d"%(data.line_num))
pro14()
36
OUTPUT:-
37
PROGRAM-15
‘‘‘Write a program to create a binary file sales.dat and write a
menu driven program to do the following:
1. Insert record
2. Search Record
3. Update Record
4. Display record
5. Exit’’’
INPUT:-
import pickle
import os
def main_menu():
print("1. Insert a record")
print("2. Search a record")
print("3. Update a record")
print("4. Display a record")
print("5. Delete a record")
print("6. Exit")
ch = int(input("Enter your choice:"))
if ch==1:
insert_rec()
elif ch==2:
search_rec()
elif ch==3:
update_rec()
38
elif ch==4:
display_rec()
elif ch==5:
delete_rec()
elif ch==6:
print("Have a nice day!")
else:
print("Invalid Choice.")
def insert_rec():
f = open(r"C:\Users\Rajes\Documents\sales.dat","ab")
c = 'yes'
while True:
sales_id=int(input("Enter ID:"))
name=input("Enter Name:")
city=input("Enter City:")
d = {"SalesId":sales_id,"Name":name,"City":city}
pickle.dump(d,f)
print("Record Inserted.")
#print("Want to insert more records, Type yes:")
c = input("Want to insert more records, Type yes:")
c = c.lower()
if c not in 'yes':
break
main_menu()
f.close()
39
def display_rec():
f = open(r"C:\Users\Rajes\Documents\sales.dat","rb")
try:
while True:
d = pickle.load(f)
print(d)
except Exception:
f.close()
main_menu()
def search_rec():
f = open(r"C:\Users\Rajes\Documents\sales.dat","rb")
s=int(input("Enter id to search:"))
f1 = 0
try:
while True:
d = pickle.load(f)
if d["SalesId"]==s:
f1=1
print(d)
break
except Exception:
f.close()
if f1==0:
print("Record not found...")
else:
40
print("Record found...")
main_menu()
def update_rec():
f1 = open(r"C:\Users\Rajes\Documents\sales.dat","rb")
f2 = open(r"C:\Users\Rajes\Documents\temp.dat","wb")
s=int(input("Enter id to update:"))
try:
while True:
d = pickle.load(f1)
if d["SalesId"]==s:
d["Name"]=input("Enter Name:")
d["City"]=input("Enter City:")
pickle.dump(d,f2)
except EOFError:
print("Record Updated.")
f1.close()
f2.close()
os.remove(r"C:\Users\Rajes\Documents\sales.dat")
os.rename(rs"C:\Users\Rajes\Documents\sales.dat")
main_menu()
def delete_rec():
f1 = open(r"C:\Users\Rajes\Documents\sales.dat","rb")
f2 = open(r"C:\Users\Rajes\Documents\temp.dat","wb")
s=int(input("Enter id to delete:"))
try:
41
while True:
d = pickle.load(f1)
if d["SalesId"]!=s:
pickle.dump(d,f2)
except EOFError:
print("Record Deleted.")
f1.close()
f2.close()
os.remove(r"C:\Users\Rajes\Documents\sales.dat")
os.rename(r"C:\Users\Rajes\Documents\temp.dat",r"C:\Users\Rajes\Documents\sales.dat")
main_menu()
main_menu()
42
OUTPUT:-
43
44
PROGRAM-16
‘‘‘ Read a text file and display the number of vowels / consonants /
uppercase / lowercase characters in the file.’’’
INPUT:-
def cnt():
f=open(r"C:\Users\Rajes\Documents\MyFile.txt", "r")
cont=f.read()
print(cont)
v=0
cons=0
l_c_l=0
u_c_l=0
for ch in cont:
if (ch.islower()):
l_c_l+=1
elif(ch.isupper()):
u_c_l+=1
ch=ch.lower()
if( ch in ['a','e','i','o','u']):
v+=1
elif (ch in ['b','c','d','f','g',
'h','j','k','l','m',
'n','p','q','r','s',
't','v','w','x','y','z']):
cons+=1
45
f.close()
46
OUTPUT:-
47
PROGRAM-17
‘‘‘Create a binary file with name and roll number. Search for a
given roll number and display the name, if not found display
appropriate message.’’’
INPUT:-
import pickle
import sys
dict={}
def write_in_file():
file=open(r"C:\Users\Rajes\Documents\stud2.dat","ab") #a-
append,b-binary
no=int(input("ENTER NO OF STUDENTS: "))
for i in range(no):
print("Enter details of student ", i+1)
dict["roll"]=int(input("Enter roll number: "))
dict["name"]=input("enter the name: ")
pickle.dump(dict,file) #dump-to write in student file
file.close()
def display():
#read from file and display
file=open(r"C:\Users\Rajes\Documents\stud2.dat","rb") #r-read,b-
binary
try:
while True:
stud=pickle.load(file) #write to the file
48
print(stud)
except EOFError:
pass
file.close()
def search():
file=open(r"C:\Users\Rajes\Documents\stud2.dat","rb") #r-read,b-
binary
r=int(input("enter the rollno to search: "))
found=0
try:
while True:
data=pickle.load(file) #read from file
if data["roll"]==r:
print("The rollno =",r," record found")
print(data)
found=1
break
except EOFError:
pass
if found==0:
print("The rollno =",r," record is not found")
file.close()
49
#main program
while True:
print("MENU \n 1-Write in a file \n 2-display ")
print(" 3-search\n 4-exit \n")
ch=int(input("Enter your choice = "))
if ch==1:
write_in_file()
input("Press any key to continue. ... ")
if ch==2:
display()
input("Press any key to continue .... ")
if ch==3:
search()
input("Press any key to continue. ... ")
if ch==4:
print(" Thank you ")
break
sys.exit()
50
OUTPUT:-
51
PROGRAM-18
‘‘‘Write a menu driven program for Stack Implementation with the
following options:
1. Push
2. Pop
3. Peek
4. Display
5. Exit.’’’
INPUT:-
Stack = []
top = None
def isEmpty(stk):
if stk == []:
return True
else:
return False
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top = len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack empty")
else:
top = len(stk)-1
print(stk[top],"<--top")
for a in range(top-1, -1, -1):
print(stk[a])
while True:
print(" --STACK OPERATIONS-- ")
print("1. Push")
53
print("2. Pop")
print("3. Peek")
print("4. Display stack")
print("5. Exit")
elif ch == 2:
item = Pop(Stack)
if item == "Underflow":
print("Underflow! Stack is empty!")
else:
print("Popped item is",item)
input("Press any key to continue. .. ")
elif ch == 3:
item = Peek(Stack)
if item == "Underflow":
print("Underflow! Stack is empty!")
else:
print("Topmost item is",item)
54
input("Press any key to continue. .. ")
elif ch == 4:
Display(Stack)
input("Press any key to continue. .. ")
elif ch == 5:
break
else:
print("Invalid choice!")
input("Press any key to continue. .. ")
print("\n")
55
OUTPUT:-
56
57
58
PROGRAM-19
‘‘‘ Write a menu driven program for Queue Implementation with
the following options:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Exit.’’’
INPUT:-
Queue = []
front= None
rear = None
def isEmpty(Que):
if Que == []:
return True
else:
return False
def Enqueue(Que, item):
Que.append(item)
if len(Que) == 1:
front = rear = 0
else:
rear = len(Que)-1
def Dequeue(Que):
if isEmpty(Que):
59
return "Underflow!"
else:
item = Que.pop(0)
if len(Que) == 0:
front = rear = None
return item
def Peek(Que):
if isEmpty(Que):
return "Underflow!"
else:
front = 0
return Que[front]
def Display(Que):
if len(Que) == 0:
print("Queue is empty")
elif len(Que) == 1:
print(Que[0],"<==front,rear")
else:
front = 0
rear = len(Que)-1
print(Que[front],"<--front")
for a in range(1,rear):
print(Que[a])
print(Que[rear],"<--rear")
60
while True:
print("--THIS IS QUEUE IMPLEMENTATION--")
print("1. ENQUEUE")
print("2. DEQUEUE")
print("3. Peek")
print("4. Display Queue")
print("5. Exit")
ch = int(input("Enter your choice(1-5):"))
if ch == 1:
item = int(input("Enter item:"))
Enqueue(Queue,item)
input("Press any key to continue. .. ")
elif ch == 2:
item = Dequeue(Queue)
if item == "Underflow!":
print("Underflow! Queue is empty!")
else:
print("Dequeue-ed item is:",item)
input("Press any key to continue. .. ")
elif ch == 3:
item = Peek(Queue)
if item == "Underflow":
print("Queue is empty!")
61
else:
print("Frontmost item is:",item)
input("Press any key to continue. .. ")
elif ch == 4:
Display(Queue)
input("Press any key to continue. .. ")
elif ch == 5:
break
else:
print("Invalid Choice")
input("Press any key to continue ... ")
print("\n")
62
OUTPUT:-
63
64
65
PROGRAM-20
‘‘‘ Create Table Employee with constraints and use of DML
commands, create table Employee with following fields and
constraints
Eno int Primary key
Ename varchar(20) Not Null
Sal decimal(10,2) can be >=5000 and <=100000
Comm decimal(10,2)
Deptno int can be MGR, CLERK, FIN, MKT
DOJ date default 2000-10-10 ’’’
66
Q1. Create the records where Job is CLERK.
INPUT
OUTPUT
OUTPUT
67
Q3. Update the Job of Empno 1 to MKT.
INPUT
OUTPUT
OUTPUT
68
Q5. Display all the records.
OUTPUT
69
PROGRAM-21
‘‘‘ Create Table Member and use of DDL (ALTER) command
with its clauses
Create table Member
Mid varchar(5)
Fname varchar(10)
ContractDuration char(1) ’’’
OUTPUT
70
Q2. Add not null to Fname column.
INPUT
OUTPUT
OUTPUT
71
Q4. Change the size of Fname column to varchar(20).
INPUT
OUTPUT
OUTPUT
72
Q6. Change the name of ContractDuration to Condur.
INPUT
OUTPUT
OUTPUT
73
Q8. Specify the default value of Condur to 1.
INPUT
OUTPUT
OUTPUT
74
Q10. Drop the Primary key of the table.
INPUT
OUTPUT
75
PROGRAM-22
‘‘‘ Create Table GYM and select statement with different
operators, Consider the following table named "GYM" with
details about Fitness products being sold in the store.
Table Name: GYM
76
Q2. Display the Names of all the products where Unit price less is
than Rs.20000.00
Q3. Display details of all the products where Unit price is in the
range 20000 to 30000.
77
Q5. Add a new row for product with the details:
"P107" Vibro Exerciser", 23000, Manufacturer: Null.
INPUT
OUTPUT
Q6. Change the Unit Price data of all the rows by applying a 10%
discount reduction on all the products.
INPUT
OUTPUT
78
Q7. Display details of all products with Manufacturer name starting
with "A".
79
Q10. Display the Name and Price where Manufacturer is Null.
Q11. Display the Name and Price where Manufacturer is Not Null.
80
Q13. Display Manufacturer, whose Name not starting with "A"
alphabet.
Q14. Display the Name and Price where Manufacturer is Not Null.
81
Q16. Display the report in following format for all the records:
Example
Product Name: Cross trainer is manufactured by Avon Fitness and
it costs Rs. 25000/-from gym.
82
PROGRAM-23
‘‘‘Create Table Emp and Dept with constraints,Insert
Records,retrieve data using two tables. Create tables with following
constraints
Table Emp
Empno int Primary key
Ename
Deptno int foreign key
Sal
Table Dept
Deptno int primary key
Dname
Location
Write a query to:’’’
83
Q1. Display the cartesian product.
mysql> select * from Emp, Dept;
84
Q3. Display Ename,Dname and Dno .
mysql> select ename,dname,emp.deptno from emp,dept
-> where emp.deptno=dept.deptno;
85
Q6. Display Ename,Dno,Location where Sal is between 1000 and
40000. Arrange SAL in ascending order.
mysql> select ename,location,emp.deptno from emp,dept
-> where emp.deptno=dept.deptno and sal>=1000 and sal<=40000
-> ORDER BY sal;
Q8. Display all details from both the tables using natural join.
mysql> select * from emp natural join dept;
86
Q9. Create an index on column Ename.
mysql> create index INDEX1 on emp(ename);
Q12. Create a new table Employee from the existing table Emp .
mysql> create table employee as
-> select empno,ename,deptno,sal
-> from emp;
87
PROGRAM-24
‘‘‘Create Table Shoes, insert records, process Group by having
aggregate functions. Write SQL query for the following: use column
alias for the expression’’’
88
Q2. Display type and total quantity of each type of shoes. Arrange it
by total quantity in descending order.
mysql> select Type, Qty from SHOES
-> GROUP BY type
->order by Qty desc;
Q3. Display type and total quantity of each type of shoes and
display only those type where total qty is more than 1500.
mysql> select Type, SUM(Qty) from SHOES
-> group by type
->having SUM(Qty)>1500;
Q4. Display type and total quantity of each type of shoes and
display only those type where average margin greater than 2.
mysql> select Type, SUM(Qty) as "Total Qty" from SHOES
-> group by type
-> having AVG(margin)>2;
89
Q5. Display type and total quantity of each type of shoes where size
is not equal to 6, and display only those type where total quantity
greater than 1500.
mysql> select Type, SUM(Qty) as "Total Qty" from SHOES
-> where size!=6
-> group by type
-> having Sum(Qty)>1500;
Q6. Display the type, size, total count from shoes for each type and
with that each size.(group by multiple columns).
mysql> select Type, Size, Count(*) from SHOES
-> group by Type ,Size;
Q7. Display the total stock value(cost*qty) of each type of shoes and
arrange it in ascending order of Total value.
mysql> select Type, Cost*Qty as "Stock Value" from SHOES
-> group by type
-> order by Cost*Qty;
90
Q8. Display the count of total number of different types of shoes
available in shoes table.
mysql> select Count(*) as "Count", Type from SHOES
-> group by type;
91
PROGRAM-25
‘‘‘MYSQL and PYTHON Interface:Quiz Application
Note: Use Python to write all sql commands
Use Python to do the following:
1. Connect Python and MYSQL
2. Create database Quiz
3. Activate it
4. Show all the databases
5. Show all the tables in database
6. Create table Question with following fields and constraint
Qno int Primary key
Ques varchar(100) not null
Type varchar(20) can be GK, Maths, CS
Opt1 varchar(30) not null
Opt2 varchar(30) not null
Opt3 varchar(30) not null
Opt4 varchar(30) not null
Ans varchar(30)
7. Show all the tables
8. Create a menu and accept user choice
1. Add
2. Display
If user enters 1 then do the following:
Add(): To Add questions in the program. Ask user how many questions to
enter. And insert records
If user enters 2 then do the following:
92
Display(): Display all the data in the question table Parameterdisplay() :
accept qno from user and display qno ,question and answer for the entered
qno
Parameterdisplay() : accept type from user and display qno ,question and
answer for the type entered.
Update() accept qno from user and update the question, options, ans
Delete(): accept the qno and delete the records
Play(): ask the user ,number of questions Randomly select questions from
the question table and accept answer from user.
Display : correct/incorrect(correct answer)
At the end display total score
Exit() : To exit the program Call the functions.’’’
INPUT:-
import mysql.connector as msq
import random as r
try:
conn=msq.connect(host='localhost',user='root',password='mh01bh9766')
v=conn.cursor()
v.execute('create database if not exists quiz;')
v.execute('use quiz;')
v.execute('''create table if not exists question
(qno int primary key,
ques varchar(100) not null,
type varchar(20),
opt1 varchar(30) not null,
opt2 varchar(30) not null,
opt3 varchar(30) not null,
opt4 varchar(30) not null,
93
ans varchar(30));''')
except:
print('Error')
def enter():
try:
conn=msq.connect(host='localhost',user='root',password='mh01bh9766')
v=conn.cursor()
v.execute('use quiz;')
v.execute('select count(qno) from question;')
for i in v:
qn=i[0]+1
q=input('Enter a question: ')
t=input('Enter type: ')
o1=input('Enter option: ')
o2=input('Enter option: ')
o3=input('Enter option: ')
o4=input('Enter option: ')
ans=int(input('Enter option no which is correct: '))
if ans==1:
ans=o1
elif ans==2:
ans=o2
elif ans==3:
ans=o3
elif ans==4:
ans=o4
y='''insert into question value(%s,%s,%s,%s,%s,%s,%s,%s)'''
94
val=(qn,q,t,o1,o2,o3,o4,ans)
v.execute(y,val)
conn.commit()
v.execute('select * from question;')
print('Qno Ques Type Opt1 Opt2 Opt3 Opt4 Ans')
for i in v:
print(i)
except:
print('Error')
def disp():
try:
conn=msq.connect(host='localhost',user='root',password='mh01bh9766')
v=conn.cursor()
v.execute('use quiz;')
v.execute('select * from question;')
print('Qno Ques Type Opt1 Opt2 Opt3 Opt4 Ans')
for i in v:
print(i)
except:
print('Error')
def pla():
try:
conn=msq.connect(host='localhost',user='root',password='mh01bh9766')
v=conn.cursor()
v.execute('use quiz;')
v.execute('select count(qno) from question;')
95
for i in v:
lq=i[0]
qs=r.randint(1,lq)
v.execute('''Select * from question where qno='''+str(qs))
for i in v:
y=i
print('Q.',y[1],)
for j in range(4):
print(y[j+3])
a=int(input('Enter the answer no.: '))
if y[a+2]==y[-1]:
print('Right Answer')
else:
print('Wrong answer')
except:
print('Error')
print('Hello and welcome to the quiz. What would you like to
do?? \n1.Add\n2.Display \n3.Play')
k=int(input('What would you like to do: '))
while k!=0:
if k==1:
enter()
elif k==2:
disp()
elif k==3:
pla()
k=int(input('What would you like to do: '))
96
OUTPUT:-
Hello and welcome to the quiz. What would you like to do??
1.Add
2.Display
3.Play