2

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.

Saju
  • 31
  • 3
  • 1
    `Winner` is not available in the scope of the function. You either need to pass `Winner` into the the functions as an argument, or make it `global` – G. Anderson Jan 03 '22 at 23:46

3 Answers3

1

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

Spooky
  • 1,752
  • 21
  • 37
1

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()
Robin Sage
  • 969
  • 1
  • 8
  • 24
  • Sorry, quick question. (I apologize if there is an obvious answer). In the above, you used a try and except statement, I was just curious whether or not you always use those statements when it involves user inputs. – Saju Jan 04 '22 at 00:32
  • 1
    It is always a good idea to sanitize user input it because that's how you get errors, bugs, and even hacks. For example, if you are expecting an integer, but the user enters anything but, it will break the code. Similarly, it's also for the same reasons, it is a good idea to handle errors. – Robin Sage Jan 04 '22 at 00:36
  • Just a question (no worries if you can't answer it) But how did you learn how to code? I am currently in high school and trying to self-learn, and while I try my best to do as many projects and tutorials as I can, I feel like I can't break past the beginner level of coding. Do you have any tips? – Saju Jan 04 '22 at 00:40
  • Self taught. I think what you're doing is correct, but like anything else, it's the amount of time you spend doing it that makes a difference. Ever heard of the 10,000-hour rule? It says that for you to get very good a something, you need to spend at least 10,000 doing it in a meaningful way, like serious practice. It's what the greats do. For example, Micheal Jordan. While everyone else would go to practice and then go home, he'd stay after hours shooting hoops by himself. Again and again. So, bottom line is practice. Get comfortable with a topic before you move on to the next. – Robin Sage Jan 04 '22 at 00:47
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/240695/discussion-between-saju-and-robin-sage). – Saju Jan 04 '22 at 00:48
0

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:

arshovon
  • 13,270
  • 9
  • 51
  • 69