Python简易猜数字游戏中While循环无法终止问题求助
猜数字函数循环异常修复
原始代码
# guess the number you chooses def number_guess_you(): import random bound = int(input('What is your number between? 1 - ? ')) valid_bound = isinstance(bound, int) and bound>1 while valid_bound==False: bound = int(input(''' \nPLEASE SELECT AN INTEGER GREATER THAN 1 \rWhat is your number between? 1 - ? ''')) valid_bound = isinstance(bound, int) and bound>1 low = 1 high = bound feedback = ' ' while feedback != 'c': if low != high: guess = random.randint(low, high) else: guess = low feedback = input(f' Is {guess} too high (1) too low (L) or correct (C)? ') if feedback == 'h': high = guess - 1 elif feedback == 'l': low = guess + 1 print(f'Yay, computer guessed your number, {guess}, correctly!')
问题原因
循环持续运行、high/low值不更新的核心问题是输入匹配不对应:
- 提示文字里写错了输入标识,把代表“过高”的
(H)写成了(1),属于笔误; - 代码里判断的是小写的
'h'/'l'/'c',但提示引导用户输入大写的L/C,用户输入大写时根本匹配不上条件,自然不会更新范围,循环也就停不下来。
修复后的代码
# 猜你心里想的数字 def number_guess_you(): import random # 处理边界输入,确保输入有效整数且大于1 while True: try: bound = int(input('你的数字范围是1到多少? ')) if bound > 1: break print("请输入大于1的整数!") except ValueError: print("请输入有效的整数!") low = 1 high = bound feedback = '' while feedback != 'c': # 生成猜测数字 guess = random.randint(low, high) if low != high else low # 获取用户反馈并统一转为小写,兼容大小写输入 feedback = input(f'我猜的{guess}是高了(H)、低了(L)还是对了(C)? ').strip().lower() # 根据反馈更新范围,同时处理无效输入 if feedback == 'h': high = guess - 1 elif feedback == 'l': low = guess + 1 elif feedback != 'c': print("请输入H/L/C其中一个!") print(f'耶!我猜对了,你的数字是{guess}!')
关键修改点
- 修正提示笔误,把
(1)改为(H),避免误导用户; - 对用户输入做小写转换,不管输入大写还是小写都能匹配判断条件;
- 优化边界输入逻辑,用
try-except捕获非整数输入,流程更简洁; - 增加无效输入提示,引导用户输入正确内容;
- 移除冗余的
isinstance判断,因为int()转换成功后必然是整数,失败会触发异常。
内容的提问来源于stack exchange,提问作者Bobbi Halsell
相关产品推荐
相关产品推荐

