本文详解如何用 python 编写一个简洁、可运行的“猜球位置”小游戏——通过打乱含 `'o'` 的三元素列表,让用户输入索引猜测 `'o'` 所在位置,并即时反馈结果,同时支持重复游玩。重点解决变量作用域与函数嵌套导致的常见报错问题。
原始代码的核心问题在于嵌套函数中对局部变量(如 guess 和 choice)的赋值未声明 nonlocal,且外层函数未正确返回或传递值,导致 UnboundLocalError 或逻辑失效。例如:
✅ 推荐方案是扁平化结构:取消嵌套函数,使用单一主循环控制流程,配合全局常量(如 LIST)和清晰的输入/判断逻辑。以下是优化后的完整可运行代码:
from random import shuffle
# 使用大写常量名强调其不变性(约定俗成)
LIST = ['', 'O', ''] # 注意:答案是 'O'(字母O),不是数字0(原文答案中误写为 '0',已修正)
while True:
shuffle(LIST) # 每轮重新打乱列表
print("? The ball is hidden under one of these positions: [0, 1, 2]")
# 安全输入处理:捕获非数字输入
try:
guess = int(input("Select the position (0, 1, or 2): "))
if guess not in [0, 1, 2]:
print("⚠️ Invalid input! Please enter 0, 1, or 2.")
continue
except ValueError:
print("⚠️ Please enter a valid number.")
continue
# 判断结果
if LIST[guess] == 'O':
print("✅ Correct choice! You found the ball!")
else:
print("❌ Wrong choice. Better luck next time!")
# 显示当前布局(增强反馈)
print(f"Current layout: {LIST}")
# 询问是否继续
while True:
choice = input("Play again? Press '0' to continue, '1' to quit: ").strip()
if choice == '0':
break # 退出内层循环,继续外层 while
elif
choice == '1':
print("? Thanks for playing!")
exit() # 或 break + 外层加标记,此处用 exit 更直观
else:
print("⚠️ Please enter '0' or '1'.")? 关键改进说明:
? 小贴士:若需保留函数式风格,可将各环节拆分为独立顶层函数(如 get_user_guess(), check_result(guess, board), ask_play_again()),但务必确保参数传入与返回值明确——函数不应依赖或修改外部可变状态,这是避免作用域混乱的根本原则。