This is my code which is a quiz for children. What I need help on is, after the code asks the user for its class, it should validates whether the input is valid or not straight away instead of doing it in the end and displaying the message "Sorry, we can not save your data as the class you entered is not valid." I've tried moving the whole if, elif, and else statements to straight after:
users_class = int(input("Which class are you in? (1,2 or 3)"))
But that doesn't help. Any help will be appreciated :)
import time
import random
import math
import operator as op
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
username=input("What is your name?")
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
users_class = int(input("Which class are you in? (1,2 or 3)"))
input("Press Enter to Start...")
start = time.time()
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
end = time.time()
etime = end - start
timeTaken = round(etime)
print ("You completed the quiz in {} seconds.".format(timeTaken))
if users_class == 1:
with open("class1.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 2:
with open("class2.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 3:
with open("class3.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
else:
print("Sorry, we can not save your data as the class you entered is not valid.")