全局变量失效触发NameError:'lives'未定义,石头剪刀布游戏求助
解决石头剪刀布游戏的全局变量与循环问题
你的问题出在两个核心点:
- 程序启动后先执行
while lives > 0循环,但此时lives还未定义——lives = 3写在play()函数内部,只有调用该函数时才会执行这行代码,所以第一次进入循环直接触发NameError。 - 就算能绕过报错,每次调用
play()都会把lives重置为3,生命值系统根本无法正常实现增减逻辑。
修正后的代码如下:
import random # 全局变量初始化放在函数外部,确保程序启动时就存在定义 lives = 3 def play(): global lives # 声明要修改全局作用域的lives变量 player = input("Choose 'r' for rock, 'p' for paper, 's' for scissor or 'q' to quit: ") choices = ['r', 'p', 's', 'q'] if player in choices: if player == 'q': exit() computer = random.choice(['r', 'p', 's']) print(f'Computer chose {computer}') if player == computer: return f"It's a tie! You still have {lives} lives" if is_win(player, computer): lives += 1 print('+1 life') return f'You now have {lives} lives' lives -= 1 print('-1 life') return f'You now have {lives} lives' else: print('Invalid input. Please enter a valid value') return play() def is_win(user, opponent): if (user == 'r' and opponent == 's') or (user == 's' and opponent == 'p') or (user == 'p' and opponent == 'r'): return True while lives > 0: print(play()) else: print('You have 0 lives left. GAME OVER')
关键修改说明:
- 将
lives = 3移到函数外部,保证程序启动时变量已存在,循环能正常进行条件判断。 play()函数内仅保留global lives声明,不再重新赋值3,这样每次调用函数时会直接修改全局的生命值,不会重置进度。- 输入错误时递归调用
play(),不会影响当前生命值,仅重新获取有效输入。
内容的提问来源于stack exchange,提问作者Coding Noob
相关产品推荐
相关产品推荐

