In: Computer Science
Program a math quiz on Python
Specifications:
- The program should ask the user a question and allow the student to enter the answer. If the answer is correct, a message of congratulations should be displayed. If the answer is incorrect, a message showing the correct answer should be displayed.
- the program should use three functions, one function to generate addition questions, one for subtraction questions, and one for multiplication questions.
- the program should store the questions and answers in a dictionary or list.
- the program should keep a count of the number of correct and incorrect responses.
import random as rand
# generating random question by random generation of numbers
# below is the function for addition of questions
def additionQuestions():
num1 = rand.randint(1,20)
num2 = rand.randint(1,20)
ans = num1 + num2
question = "{} + {} = ".format(num1, num2)
return [question, ans]
# below is the function for subtraction of questions
def subtractQuestions():
num1 = rand.randint(1,20)
num2 = rand.randint(1,20)
ans = num1 - num2
question = "{} - {} = ".format(num1, num2)
return [question, ans]
# below is the function for multiplication of questions
def multiplyQuestions():
num1 = rand.randint(1,20)
num2 = rand.randint(1,20)
ans = num1 * num2
question = "{} x {} = ".format(num1, num2)
return [question, ans]
correct = 0
incorrect = 0
dict = { }
for i in range(0,5):
# generationg random number from 1 to 3
# if 1 then we have to generate addition questions
# if 2 then we have to generate subtraction questions
# if 3 then we have to generate multiplication questions
randNum = rand.randint(1,3)
if randNum == 1:
dict[i] = additionQuestions()
if randNum == 2:
dict[i] = subtractQuestions()
if randNum == 3:
dict[i] = multiplyQuestions()
# retrieving questions and answers
question = dict[i][0]
answer = dict[i][1]
# reading users answer and validating users answer
try:
userAnswer = int(input(question))
except:
incorrect += 1
print("Invalid Answer")
print("Correct Answer : ", answer)
print("--------------------------------")
continue
if userAnswer == answer:
correct += 1
print("Congratulations")
else:
incorrect += 1
print("Incorrect Answer")
print("Correct Answer : ",answer)
print("--------------------------------")
# printing the report of result
print("------------ Report ------------")
print("Correct Answers : ",correct)
print("Incorrect Answers : ",incorrect)
print("Total Answers : ",(correct+incorrect))
Code Screenshot:
Output: