如何让用户在测试中有机会得到正确的python答案?
最简单的方法是使用for
循环,如果它们正确,则使用break
,如果它们从未正确,则可能使用else
。例如:
for tries in range(2):
print("n", "QUESTION 3:", "n", "Which level of government is responsible for Tourism?")
print(" a) Municipal", "n", "b) Fedral", "n", "c) Provincial", "n", "d) All", "n", "e) Legislative")
answer3 = input("Make your choice: ")
if answer3 == "d" or answer3 == "D" :
print("Correct!")
break
else:
print("False!")
else:
print("Out of chances!")
如果您不想每次都重印问题,只需将print
调用移动到for
之前。
链接教程部分(以及接下来的三个部分)更详细地解释了这一切。
def nTries(isCorrect, n = 2):
answer = input("Make your choice: ")
if isCorrect(answer):
print("Correct")
elif n == 1:
print("Out of tries, and incorrect")
else:
print("Incorrect")
nTries(isCorrect, n - 1)
像这样设置
print("n", "QUESTION 3:", "n", "Which level of government is responsible for Tourism?")
print(" a) Municipal", "n", "b) Fedral", "n", "c) Provincial", "n", "d) All", "n", "e) Legislative")
nTries(lambda d: d.lower() == 'd')