【发布时间】:2015-01-25 18:09:10
【问题描述】:
这是我的代码,是针对儿童的测验。我需要帮助的是,在代码向用户询问其类之后,它应该立即验证输入是否有效,而不是最终执行并显示消息 “抱歉,由于您输入的课程无效,我们无法保存您的数据。” 我尝试将整个 if、elif 和 else 语句移到后面:
users_class = int(input("Which class are you in? (1,2 or 3)"))
但这无济于事。任何帮助将不胜感激:)
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.")
【问题讨论】:
-
有效是指 1、2 还是 3 还是整数?另外,当您将 if 移到输入之后会发生什么(不)?
-
它必须是 1,2 或 3。我收到此错误 - “NameError: name 'correct_answers' is not defined”
-
然后将 correct_answers 和 timeTaken 也移到 if 之前。
-
我试过了。但问题仍然被问到。如果此人输入无效值,我希望它结束
-
但是
Sorry, we can not save your data as the class you entered is not valid.消息是否出现在问题之前?
标签: python validation