Python Python Basics (2015) Number Game App Number Game Refinement

Bruno Correia
Bruno Correia
1,812 Points

Getting error if input is not valid

Hi community!

I have followed the video and out of curiosity tried all the possibilities once the script was complete. It turns out I'm getting an "UnboudLocalError" if my initial input is not valid (if it's a letter, for example).

Now I know we have written the try and except to avoid exactly that but I'm almost sure my code looks exactly like what is shown in the video and it still doesn't work. Could it be that Kenneth's code will throw the same exceptions as well or is it something with my code?

The console shows:

"Traceback (most recent call last):
File "number_game.py", line 36, in <module>
game()
File "number_game.py", line 17, in game
print("{} isn't a number!".format(guess))
UnboundLocalError: local variable 'guess' referenced bef ore assignment "

My code looks like this:

import random

def game():
    # generate random number between 1 and 10
    secret_num = random.randint(1, 10)
    guesses = []

    while len(guesses) < 5:
        try:
            # get a number guess from the player
            guess = int(input("Guess a number between 1 and 10: "))
        except ValueError:
            print("{} isn't a number!".format(guess))
        else:
            # compare to secret number
            if guess == secret_num:
                print("You got it! My number was {}".format(secret_num))
                break
            elif guess < secret_num:
                print("Higher!")
            else:
                print("Lower!")
            guesses.append(guess)
    else:
        print("You didn't get it! My number was {}.".format(secret_num))
    play_again = input("Do you want to play again? Y/n ")
    if play_again.lower() != 'n':
        game()
    else:
        print("Bye!")

game()

Thank you so much in advance!

4 Answers

Christian Mangeng
Christian Mangeng
15,963 Points

Hi Bruno,

the error occurs because "guess" in your case is only defined if the try statement succeeds. This is because you defined it inside the try clause. You could define guess outside of the try/except clause and then just check for guess = int(guess) inside try

Bruno Correia
Bruno Correia
1,812 Points

Thank you Christian, that does make sense! I have tried how you suggested and it's working! :)

I still don't get it can you please specify the code?

Kevin Akpomuje
Kevin Akpomuje
1,357 Points

I have the same error as Bruno (the original poster) and I tried to follow your advice Christian. But unfortunatly, it doesn't work for me. Can you please check my code and tell me what I did wrong? Thanks in advance.

Error message:

Welcome to the world's greatest number guessing game: RN
In Beginner's Mode you have five tries to find the correct number
Guess a number between 1 and 10: a
Traceback (most recent call last):
File "number_game.py", line 51, in <module>
game()
File "number_game.py", line 20, in game
guess = int(input("Guess a number between 1 and 10: "))
ValueError: invalid literal for int() with base 10: 'a

My code looks like this:

'''python

# To-Do 09.07.2017
    import random
    def game():
        # generate a random number between 1 and 10
        secret_num = random.randint(1, 10)

# Introduce the player to game
print("Welcome to the world's greatest number guessing game: RN")
print("In Beginner's Mode you have five tries to find the correct number")

max_guess = []

while len(max_guess) < 5:
    guess = int(input("Guess a number between 1 and 10: "))
    try:
        # get number the form user and check if its an integer!
        guess = int(guess)
    except ValueError:
        print("Not {}! Please, only use numbers between 1 - 10".format(guess))
        continue
    else:    
        # compare guess to secret number
        if guess == secret_num:
            print("You got it! My number was {}".format(secret_num))
            break

        # print hit/miss
        elif guess > secret_num:
            print("{} is too high, try a lower number".format(guess))
        else:
            print("{} is too low, try a high number".format(guess))

        # increase number of wrong guesses
        max_guess.append(guess)

# print this when user didn't get the number at all!) 
else:
    print("You didn't guess my number: {}! Better luck next time".format(secret_num))
play_again = input("Do you want to play again? Enter Y/n to continue: ")
if play_again.lower() != 'n':
    game()
else:
    print("Thank you for playing RN the world's greatest number guessing game!")  

game()

 # End of code

'''

Ismail KOÇ
Ismail KOÇ
1,748 Points

Hi Kevin i solved your problem

#Before

while len(max_guess) < 5:
    guess = int(input("Guess a number between 1 and 10: "))
    try:
        # get number the form user and check if its an integer!
        guess = int(guess)
    except ValueError:
        print("Not {}! Please, only use numbers between 1 - 10".format(guess))
        continue

#and Now


while len(max_guess) < 5:
    user_input =  input("Guess a number between 1 and 10: ")
    try:
        # get number the form user and check if its an integer!
        guess = int(user_input)
    except ValueError:
        print("Not {}! Please, only use numbers between 1 - 10".format(user_input))
        continue

we could not use guess variable because guess variable broken and not available for print

Kevin Akpomuje
Kevin Akpomuje
1,357 Points

Thanks a whole bunch Ismail !

Ismail KOÇ
Ismail KOÇ
1,748 Points

Nothing, can you upvote my answer?

Kevin Akpomuje
Kevin Akpomuje
1,357 Points

Sorry, I just read your post Ismail. I don't know how to upvote your answer :(

Ismail KOÇ
Ismail KOÇ
1,748 Points

You can see number right of another comment (without yours) and if you click a symbol(looks likes this : ^) (top of the number) you can upvote a comment