简体   繁体   English

全局变量不工作 NameError: name 'lives' is not defined

[英]Global variable not working NameError: name 'lives' is not defined

I am new to coding and I am trying to build a simple rock-paper-scissor game.我是编码新手,我正在尝试构建一个简单的剪刀石头布游戏。

While trying to implement lives in the game I cannot seem to be able to loop while lives > 0. Although I tried to make the lives variable global to be able to use it outside the function it does not seem to work.在尝试在游戏中实现生命时,我似乎无法在生命 > 0 时循环。虽然我试图将lives变量设置为全局变量以便能够在 function 之外使用它,但它似乎不起作用。 Instead I get an error like this when I run the program:相反,当我运行程序时出现这样的错误:

NameError: name 'lives' is not defined NameError: 名称 'lives' 未定义

Maybe my understanding of global variables is wrong.也许我对全局变量的理解是错误的。 Any help would be much appreciated.任何帮助将非常感激。 Thank you in advance.先感谢您。

Here is my code这是我的代码

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

Put your lives outside the function def play()把你的lives放在 function 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
.....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM