Python开发高低选择输入系统出现IndentationError缩进错误如何调试
错误原因
- 你遇到的
IndentationError: unindent does not match any outer indentation level是Python典型的缩进匹配错误:Python要求同一代码块(比如while循环内部)的代码必须保持一致的缩进量,你原有代码中while True下的first = input()行缩进了2个空格,但后续的print(random.randint(1, 2))和break行仅缩进了1个空格,层级不匹配导致报错。 - 除了缩进问题外,原有代码缺少用户输入校验、选择和随机结果的匹配逻辑,无法完成「高低选择判断」的需求。
修复方案
最小改动:仅修复缩进(保留原有代码逻辑)
如果不需要加判断逻辑,只要把print和break行的缩进调整到和input行一致即可:
import random print("Hello Welcome to the up down game!") while True: first = input("[1]Low or [2]High. Which one?\n") print(random.randint(1, 2)) break
完整功能实现:补充高低选择匹配逻辑
如果要实现完整的游戏功能,可以参考下方代码:
import random print("Hello Welcome to the up down game!") while True: first = input("[1]Low or [2]High. Which one?\n") # 校验输入合法性 if first not in ["1", "2"]: print("输入无效,请输入1或2") continue # 生成随机结果 random_res = random.randint(1, 2) print(f"随机生成结果为:{random_res}") # 判断结果 if first == str(random_res): print("恭喜你猜对了!") else: print("很遗憾猜错了") break
内容的提问来源于stack exchange,提问作者nebula234
相关产品推荐
相关产品推荐

