Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. Instead I get an error like this when I run the program:

NameError: name ‘lives’ is not defined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Put your lives outside the 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
.....
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading