如何在Python中限制输入尝试次数?测验代码现无限循环求排查
测验程序无限循环问题分析及修复
原代码核心问题
循环条件完全错误
原代码用while guess == answer:作为循环条件,这意味着只要用户第一次猜对,就会进入无限循环——因为guess和answer都是函数传入的固定值,循环条件永远为真,会反复打印"正确答案",无法退出。尝试次数逻辑混乱
- attempt初始值设为3,后续却执行
attempt +=1,完全搞反了计数方向,应该从0或1开始累加尝试次数,直到达到3次上限。 - 判断
if attempt < 2的逻辑错误,实际应该是当尝试次数未达上限时提示重试。
- attempt初始值设为3,后续却执行
缺少重试输入逻辑
函数仅接收外部传入的一次猜测值,没有在循环内重新获取用户的新输入,根本实现不了"多次尝试答题"的需求。
修复后的代码
score = 0 print('Hello, and welcome to The Game Show') def check_questions(question, answer): global score attempt = 0 while attempt < 3: guess = input(question) # 统一格式避免类型/大小写/空格导致的判断错误 if str(guess).strip().lower() == str(answer).strip().lower(): print('That is the correct answer.') score += 1 break else: attempt += 1 if attempt < 3: print('That is not the correct answer. Please try again.') if attempt == 3: print(f'The correct answer is {answer}.') check_questions('Where was Hitler born?\n', 'Austria') check_questions('How many sides does a triangle have?\n', 3) check_questions('What is h2O?\n', 'water') check_questions('What was Germany called before WW2?\n', 'Weimar Republic') 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}.')
修复说明
- 将题目传入函数,在函数内部循环获取用户猜测,真正实现多次尝试逻辑。
- 统一将猜测和答案转为字符串并格式化,避免因输入大小写、空格或类型不匹配导致的判断错误。
- 尝试次数从0开始累加,达到3次时退出循环并显示正确答案。
- 猜对后直接break退出循环,避免无效执行。
内容的提问来源于stack exchange,提问作者Mr.Bunberry66
相关产品推荐
相关产品推荐

