【问题标题】:Global variable not working NameError: name 'lives' is not defined全局变量不工作 NameError: name \'lives\' is not defined
【发布时间】:2023-01-08 02:40:43
【问题描述】:

我是编码新手,我正在尝试构建一个简单的剪刀石头布游戏。

在尝试在游戏中实现生命时,我似乎无法在生命 > 0 时循环。尽管我试图将 lives 变量设置为全局变量以便能够在函数外使用它,但它似乎不起作用。相反,当我运行程序时出现这样的错误:

NameError: 名称 'lives' 未定义

也许我对全局变量的理解是错误的。任何帮助将非常感激。先感谢您。

这是我的代码

import random

def play():
    player = input("Choose 'r' for rock, 'p' for paper, 's' for scissor or 'q' to quit: ")
    choices = ['r', 'p', 's', 'q']
    global lives
    lives = 3

    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')

【问题讨论】:

  • global lives 表示从全局范围获取变量lives。在调用global lives 之前,您没有定义lives 变量,因此它会给您一个错误。另请注意,全局变量是considered bad

标签: python global-variables


【解决方案1】:

把你的lives放在函数def play()外面

import random
lives = 3
def play():
    player = input("Choose 'r' for rock, 'p' for paper, 's' for scissor or 'q' to quit: ")
    choices = ['r', 'p', 's', 'q']
    global lives
.....

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2019-01-05
    • 2013-04-09
    • 1970-01-01
    • 2023-03-13
    • 2020-11-07
    • 2017-01-09
    • 2017-06-14
    相关资源
    最近更新 更多