cs
cs
1. Certificate
2. Acknowledgement
3. Source Code
4. Sample Outputs
5. Bibliography
Certificate
Certifica
te
This is to certify that Kartik Shaklana of Class
12F, has successfully completed the project
under the guidance of Mr. Sanjeev Sharma,
Computer Science teacher, during the
academic year 2024-2025.
Mr.Sanjeev Sharma
PGT Computer Science
Mount Carmel School
Anand Niketan
Acknowledge
ment
I would like to express my heartfelt gratitude to Mr.
Sanjeev Sharma, my Computer Science teacher, for
his valuable guidance and constant support
throughout the completion of my project. His
suggestions and insights have been instrumental in
helping me understand the critical aspects of the
project.
#========================================
=========================================
===================================
#Checking Connection
def chk_connection():
try:
return mysql.connector.connect(user='root',
host='localhost', password='123', database='QUIZ')
except mysql.connector.Error:
print('\nCONNECTION FAILED WITH DATABASE!
WE ARE SORRY FOR THE INCONVENIENCE')
return False
#=========================================
==========================================
=================================
for i in range(len(subjects)):
print(str(i) + ". " + subjects[i])
while True:
try:
sub_code = int(input('\nEnter subject code
to ' + typ + ': '))
if 0 <= sub_code < len(subjects):
return subjects[sub_code]
else:
print('Invalid code! Please enter a correct
subject code.')
except ValueError:
print('Only numbers are expected!')
#Insert multiple questions into the database.
def insert_many_ques():
try:
mycon = mysql.connector.connect(user='root',
host='localhost', password='123', database='QUIZ')
cur = mycon.cursor()
cur.execute('SELECT MAX(QID) FROM QUIZ')
max_qid = cur.fetchone()[0] or 0
new_qid = max_qid + 1
while True:
ques = input('Enter Question: ')
if len(ques) > 600:
print('Question length exceeds 600 characters!
Please reduce the size.')
continue
op1 = input('Enter Option A: ')
op2 = input('Enter Option B: ')
op3 = input('Enter Option C: ')
op4 = input('Enter Option D: ')
correct = input('Enter Correct Option [A-D]: ').
upper()
questions.append((new_qid, ques, op1, op2, op3,
op4, correct, subject))
new_qid += 1
cur.close()
mycon.close()
except mysql.connector.Error :
print("Disconnected")
#Display all questions from the database
def show_all():
try:
mycon = mysql.connector.connect(user='root',
host='localhost', password='123', database='QUIZ')
cur = mycon.cursor()
qry = "SELECT * FROM QUIZ"
cur.execute(qry)
rows = cur.fetchall()
if rows:
for row in rows:
print("QID: " + str(row[0]) + "\n"
+"Question: " + row[1] + "\n" +"Option A: " + row[2]
+ "\n" +"Option B: " + row[3] + "\n" +"Option C: " +
row[4] + "\n" +"Option D: " + row[5] + "\n" +"Correct
Answer: " + row[6] + "\n" +"Subject: " + row[7] + "\n"
+"-"*60)
print('-' * 170)
else:
print("No records found.")
cur.close()
mycon.close()
except mysql.connector.Error :
print("Disconnected")
#Delete a Question
def delete_ques():
try:
mycon = mysql.connector.connect(user='root',
host='localhost', password='123', database='QUIZ')
cur = mycon.cursor()
qid = int(input('Enter QID of the question to delete: '))
qry = "SELECT * FROM QUIZ WHERE QID = %s"
cur.execute(qry, (qid,))
row = cur.fetchone()
if row:
print("\nDeleting the following question:")
print("QID: " + str(row[0]) + "\n" + "Question: " +
row[1] + "\n")
confirm = input("Confirm deletion (Y/y): ")
if confirm.lower() == 'y':
cur.execute("DELETE FROM QUIZ WHERE
QID = %s", (qid,))
mycon.commit()
print("Question deleted.")
else:
print("Deletion cancelled.")
else:
print("No question found with QID = " + str(qid))
cur.close()
mycon.close()
except mysql.connector.Error :
print("Disconnected")
#Add a Question
def admin_menu(mycon):
while True:
print('\n' + '='*60)
print("ADMIN SECTION")
print("1. Add Question")
print("2. Show All Questions")
print("3. Delete Question")
print("4. Return to Main Menu")
try:
choice = int(input("Enter your choice: "))
if choice == 1:
insert_many_ques()
elif choice == 2:
show_all()
elif choice == 3:
delete_ques()
elif choice == 4:
main()
else:
print("Invalid choice.")
except ValueError:
print("Please enter a valid number.")
#Take Quiz
def take_quiz(mycon):
try:
cur = mycon.cursor()
subject = get_subject_nm("TAKE QUIZ")
cur.execute("SELECT * FROM QUIZ WHERE
subject = %s", (subject,))
questions = cur.fetchall()
if not questions:
print("\nNo questions available for this
subject. Please try again later.")
return
while True:
try:
num_questions = int(input("Enter the
number of questions to attempt: "))
num_questions = min(len(questions),
num_questions)
if num_questions <= 0:
raise ValueError("Number of questions
must be positive.")
break
except ValueError as e:
print("Invalid input: {}. Please enter a valid
number.".format(e))
selected_questions =
random.sample(questions, num_questions)
for q in selected_questions:
print("Q: " + q[1])
print("A: " + q[2] + "\nB: " + q[3] + " \nC: " +
q[4] + " \n D: " + q[5])
answer = input("Your answer (A, B, C, D):
").upper()
if answer == q[6]:
print("Correct!")
score += 1
else:
print("Wrong! The correct answer was: " +
q[6])
print("\nQuiz ended. Your score is " + str(score) + "/"
+ str(num_questions))
cur.execute("INSERT INTO SCORES VALUES (%s,
%s, %s, %s)", (us,name, score, subject))
mycon.commit()
print("Your score has been recorded.")
cur.close()
except mysql.connector.Error :
print("Disconnected")
# Function to show all scores
def show_scores(mycon):
try:
cur = mycon.cursor()
cur.execute("SELECT * FROM SCORES ORDER BY
user_id DESC")
rows = cur.fetchall()
if rows:
print("[User ID,Name,Score,Sunject]")
print(rows)
print('-' * 100)
else:
print("No scores found.")
cur.close()
except mysql.connector.Error :
print("Disconnected")
# Main menu
def main():
mycon = chk_connection()
if not mycon:
sys.exit()
while True:
print('\n' + '='*60)
print("MAIN MENU")
print("1. Admin Section")
print("2. Enter Quiz")
print("3. View Scores")
print("4. Exit")
try:
choice = int(input("Enter your choice: "))
if choice == 1:
admin_menu(mycon)
elif choice == 2:
take_quiz(mycon)
elif choice == 3:
show_scores(mycon)
elif choice == 4:
print("Exiting... Thank you!")
mycon.close()
sys.exit()
else:
print("Invalid choice.")
except ValueError:
print("Please enter a valid number.")
#==========================================
===========================================
===============================
1.Tables in database
2. Table to store
Question
3. Table to store
Scores
Bibliograph
y
Computer Science with Python
(Sumita Arrora)
www.wikepedia.com
https://kvcoders.in/