Global variable not working NameError: name 'lives' is not defined

Question:

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

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')
Asked By: Coding Noob

||

Answers:

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
.....
Answered By: Talha Tayyab

As its is showed here, you need to define the lives variable outside of the function and so define the variable as global. In this link have more situations where this concept is applied.

Answered By: amkawai
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.