Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

number game error when not entering a number

Hi folks,

i've done the number game in python. Everything works fine until i tried to enter a non number. According to our code, a message of any non number should be printed out as it isn't a number. But i get the following error:

Guess a number between 1 and 10: a
Traceback (most recent call last):
File "number_game.py", line 15, in game
guess = int(input("Guess a number between 1 and 10: "))
ValueError: invalid literal for int() with base 10: 'a'

During handling of the above exception, another exception occurred:

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

The code is as following:

import random

# too high message
# too low message
# play again

def game():
    # generate a 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 guess to secret number
            if guess == secret_num:
                print("You got it! My number was {}".format(secret_num))
                break
            elif guess < secret_num:
                print("My number is higher than {}.".format(guess))
            else:
                print("My number is lower than {}.".format(guess))
            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()

I wonder where the issue lies?

Cheers, Tuan

2 Answers

Hi there Tuan, since you haven't pasted all of your code, I have pasted your try and except block int IDLE and came up for a solution to what i can see. try replacing your try and except block with this:

guess = input("Guess a number between 1 and 10: ")
try:
    int(guess)
except ValueError:
        print("{} isn't a number!".format(guess))

else:
    if guess == secret_num:
        print("You got it! My number was {}".format(secret_num))
        break
    elif guess < secret_num:
        print("My number is higher than {}.".format(guess))
    else:
        print("My number is lower than {}.".format(guess))
    guesses.append(guess)

If this does not work, please paste all of your code and I will have another look to see what is wrong.

Edit:

Hey, I've had another look at your code and spotted some errors. I've replaced your try and except block with the one i did above but there was one more error which I will point out. Below, I have corrected your game :)

import random

# too high message
# too low message
# play again

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

    while len(guesses) < 5:
        guess = input("Guess a number between 1 and 10: ")
        try:
            int(guess)
        except ValueError:
                print("{} isn't a number!".format(guess))

        else:
            guess = int(guess) #you missed out this. The try block does 
                               #not actually do what you write in it
                               #it just checks if what you wrote in it raises an error or not
            if guess == secret_num:
                print("You got it! My number was {}".format(secret_num))
                break
            elif guess < secret_num:
                print("My number is higher than {}.".format(guess))
            else:
                print("My number is lower than {}.".format(guess))
            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()

Enjoy your game! :)

Thanks, Haider

Thanks a lot for your quick feedback.

Cheers, Tuan.

Hi Ali, thanks for your review. I did post all my code but somehow the forum only formatted a part of it. I'll give your suggestion a try. Thanks a lot.

Cheers, Tuan

Hi Tuan, I've re-formatted your code and will have another look at it :)

Look above, I've edited my answer. Enjoy.