Local Assignment Error in Number Guessing Game

Viewed 57

I keep receiving the following error when running the code

UnboundLocalError: local variable 'winner' referenced before assignment    

The following is my code

# Create a Number Guessing Game 

humannum = int(input("Enter a number from 1 - 10> "))

computernum = random.randint(1,10)

Winner = False 

def winner(): # How to allow the user to try again 
    while Winner != True:
        print("Your answer was not correct, please try again")
        print(humannum)

def calculator(): # This is to calculate, who wins the game
    if humannum == computernum:
        print(f'The computer number was {computernum}')
        print(f'Your number was {humannum}')
        print("")
        print("Therefore You have won ! ")
        winner = True        
    elif humannum <= computernum:
        print("Your number was larger than the computer")
        winner()
    elif humannum >= computernum:
        print("Your number was larger than the computers")
        winner()

calculator()

I am not sure why this is happening when I believe I have my variable winner referenced above me calling it which is below in the calculator function.

3 Answers

In the calculator() method you wrote winner = True, not Winner. The issue is the variable names do not exactly match.

I refactored your code, removed extra functions and added a guess counter so that the user knows how many attempts are left.

import random

num = random.randint(1,10)
def num_guess():
    attempts = 3
    while attempts > 0:
        attempts -= 1
        try:
            userGuess = int(input("Enter a number between 1 and 10: "))
        except ValueError:
            print("Invalid input. Try again.")
            continue
        if attempts > 0:
            if userGuess == num:
                print("You guessed the number!!")
                break
            elif userGuess < num:
                print(f"The number is too low.\nYou have {attempts} attempts left.")
            elif userGuess > num:
                print(f"The number is too high.\nYou have {attempts} attempts left.")
        else:
            print("You did not guess the number.\Thanks for playing!")
num_guess()

To use a global variable inside a function, we need to declare it using global.

Modified code:

import random

# Create a Number Guessing Game

humannum = int(input("Enter a number from 1 - 10> "))

computernum = random.randint(1, 10)

Winner = False


def reply_game():  # How to allow the user to try again
    global Winner, humannum
    while Winner != True:
        print("Your answer was not correct, please try again")
        humannum = int(input("Enter a number from 1 - 10> "))
        calculator()


def calculator():  # This is to calculate, who wins the game
    global humannum, computernum, Winner
    if humannum == computernum:
        print(f'The computer number was {computernum}')
        print(f'Your number was {humannum}')
        print("")
        print("Therefore You have won ! ")
        Winner = True
    elif humannum <= computernum:
        print("Your number was smaller than the computer")
        reply_game()
    elif humannum > computernum:
        print("Your number was larger than the computers")
        reply_game()


calculator()

Output:

Enter a number from 1 - 10> >? 3
Your number was smaller than the computer
Your answer was not correct, please try again
Enter a number from 1 - 10> >? 4
Your number was smaller than the computer
Your answer was not correct, please try again
Enter a number from 1 - 10> >? 6
The computer number was 6
Your number was 6
Therefore You have won ! 

References:

Related