我是python的初学者,我编写了一个测验程序,如果给出的答案有误,如何在测验中重复一个问题?我还想给用户一个选项,使其跳到与答案相同的文本框中的下一个问题。
这是我当前的源代码:
score = 0
q1 = input("What is the square root of 64?: ")
if q1 == ("8"):
print("Correct!")
score = score + 1
if q1 == ("skip"):
break
else:
print("Incorrect.")
print("")
q2 = input("Who was president during the year 1970?: ")
if q2 == ("Richard Nixon") or q2 == ("richard nixon"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q3 = input("How many stars are on the American flag?: ")
if q3 == ("50"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q4 = input("In the US, which state has the largest population?: ")
if q4 == ("California") or q4 == ("california"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q5 = input("Who discovered the Americas in 1492?: ")
if q5 == ("Christopher Columbus") or q5 == ("christopher columbus"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
if score == 0:
print("Your score is 0. Better luck next time.")
if score == 1:
print("Your score is 1. Better luck next time.")
if score == 2:
print("Your score is 2. Better luck next time.")
if score == 3:
print("Your score is 3. Not bad. Try again soon!")
if score == 4:
print("Your score is 4. Not bad. Try again soon!")
if score == 5:
print("Your score is 5. Awesome! You rock!")
答案 0 :(得分:2)
您将要使用函数来调用相同的代码以显示问题。
要进行跳过,您可以让程序检测到一个特殊的答案(在下面的示例中为“跳过”),并使用该答案识别何时跳到下一个问题。
这是一个例子:
QUESTIONS = {'question1' : 'answer', 'question2': 'answer'}
score = 0
def ask_question(question, answer):
global score
while True:
response = input(question + "\n")
if response == 'skip':
return
elif response == answer:
score += 1
break
def question_loop():
for question, answer in QUESTIONS.items():
ask_question(question, answer)
def print_results():
#print results here
pass
question_loop()
print_results()