如何让if语句校验for循环每次迭代输入,实现猜数字5次猜测机会功能
代码调整方案
你原有代码的核心问题是for循环变量误用了已经生成的computer_choice,会直接覆盖随机生成的正确值,调整后的完整实现如下:
import random # 先校验最高值输入合法性 while True: max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ") if max_value.isdigit() and int(max_value) >= 1: max_value = int(max_value) break print("请输入大于等于1的有效整数!") computer_choice = random.randint(1, max_value) # 循环5次对应5次猜测机会,循环变量用attempt计数,不覆盖正确值 for attempt in range(5): # 每次迭代先做输入有效性校验 while True: user_input = input(f"What number between 1 and {max_value} do you choose? ") # 校验是否为整数 if not user_input.isdigit(): print("输入无效,请输入整数!") continue user_choice = int(user_input) # 校验是否在合法范围 if user_choice < 1 or user_choice > max_value: print(f"输入超出范围,请输入1到{max_value}之间的整数!") continue # 校验通过跳出校验循环 break # 猜测逻辑 if user_choice == computer_choice: print("恭喜你猜对了!Thank you for playing.") # 猜对直接终止循环 break elif user_choice > computer_choice: print("你猜的数字太大了!", end=" ") else: print("你猜的数字太小了!", end=" ") # 提示剩余次数 print(f"你还有{4 - attempt}次机会") # for循环正常结束(没有被break打断)说明5次都没猜对 else: print(f"很遗憾,5次机会已经耗尽,你失败了。正确数字是{computer_choice}")
调整说明
- 修复了for循环变量覆盖
computer_choice的错误,用attempt作为计数变量,满足强制使用for循环、共5次猜测机会的需求 - 每次迭代新增双层if校验:先判断用户输入是否为合法整数,再判断是否在1到最大值的区间内,校验不通过要求重新输入,不消耗猜测次数
- 增加猜测结果提示,猜对直接终止循环,5次耗尽触发for的else分支判定失败
内容的提问来源于stack exchange,提问作者LeCoderGhost1
相关产品推荐
相关产品推荐

