[英]How do I limit input attempts in python?
我试图限制我正在做的测验中的尝试,但不小心创建了一个无限循环。 我在这里做错了什么?
score = 0
print('Hello, and welcome to The Game Show')
def check_questions(guess, answer):
global score
still_guessing = True
attempt = 3
while guess == answer:
print('That is the correct answer.')
score += 1
still_guessing = False
else:
if attempt < 2:
print('That is not the correct answer. Please try again.')
attempt += 1
if attempt == 3:
print('The correct answer is ' + str(answer) + '.')
guess_1 = input('Where was Hitler born?\n')
check_questions(guess_1, 'Austria')
guess_2 = int(input('How many sides does a triangle have?\n'))
check_questions(guess_2, 3)
guess_3 = input('What is h2O?\n')
check_questions(guess_3, 'water')
guess_4 = input('What was Germany called before WW2?\n')
check_questions(guess_4, 'Weimar Republic')
guess_5 = int(input('What is the minimum age required to be the U.S president?\n'))
check_questions(guess_5, 35)
print('Thank you for taking the quiz. Your score is ' + str(score) + '.')
这是你应该如何处理它。 将问题和答案都传递给 function,以便它可以处理循环。 让它返回这个问题的分数。
score = 0
print('Hello, and welcome to The Game Show')
def check_questions(question, answer):
global score
for attempt in range(3):
guess = input(question)
if guess == answer:
print('That is the correct answer.')
return 1
print('That is not the correct answer.')
if attempt < 2:
print('Please try again.')
print('The correct answer is ' + str(answer) + '.')
return 0
score += check_questions('Where was Hitler born?\n', 'Austria')
score += check_questions('How many sides does a triangle have?\n', '3')
score += check_questions('What is H2O?\n', 'water')
score += check_questions('What was Germany called before WW2?\n', 'Weimar Republic')
score += check_questions('What is the minimum age required to be the U.S president?\n', '35')
print(f"Thank you for taking the quiz. Your score is {score}.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.