0% found this document useful (0 votes)
5 views

cs

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

cs

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Inde

S.NO x Topic Signature

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.

The project has been carried out in accordance


with the guidelines set by the school and fulfills
the requirements of the curriculum. The
dedication and effort put in by the student are
commendable.

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.

I am deeply thankful for his encouragement and


mentorship, which played a vital role in the success
of my project. This accomplishment would not have
been possible without his expertise and dedication.
Source
Code
#Importing The Module
import mysql.connector
import sys
import random

#========================================
=========================================
===================================

#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
#=========================================
==========================================
=================================

#Get subject name from user input.


def get_subject_nm(typ):
print("\n\n" + '='*20 + " SUBJECTS AVAILABLE " +
'='*20)
subjects = ["CS", "PHYSICS", "CHEMISTRY",
"MATHS", "ENGLISH"]

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

subject = get_subject_nm("ADD QUESTION")


questions = []
print('\nMaximum character length for a question is
600.')

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

more = input('Add more questions? (Y/y to


continue): ')
if more.lower() != 'y':
break

qry = 'INSERT INTO QUIZ VALUES (%s, %s, %s, %s,


%s, %s, %s, %s)'
cur.executemany(qry, questions)
mycon.commit()
print('Questions added successfully!')

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

name = input("Enter your name: ")


us=int(input("Enter User ID (only integer)"))

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)

print("\nQuiz has started!\n")


score = 0

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.")
#==========================================
===========================================
===============================

# Start the application


main()
Sample
Outputs
To add questions
To show all questions
To delete a question
To Enter Quiz
To view scores
To Exit
SQL TABLES

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/

You might also like