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

I'm having two problems with my ValueError in my number game.

My first problem is if I type a letter as my very first guess it throws a ValueError.

My second problem is when I play my number game and I type a letter instead of a number the computer responds with the number that I typed previously and the message instead of the letter I just typed. So, if I guess '2' on my first guess and then 'g' on my second, it will print "2 is not a number!" I think my two problems are related, but I'm not sure where I'm going wrong and I would be really grateful for any help.
Thanks
Here's my whole code:

import random

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

    while len(guesses) < 5:
        # safely make an int
        try:
            # get a number guess from the player
            guess = int(input("Guess a number between 1 and 10: "))
        # print hit/miss
        except ValueError:
            print("{} isn't a number!".format(guess))
        else:
            # compare guess to secret number
            if guess == secret_num:
                print("You got it! My secret number was {}.".format(secret_num))
                break
            # too high message
            elif guess < secret_num:
                print("My number is higher than {}!".format(guess))
            # too low message
            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
    play_again = input("Do you want to play again? Y/n ")
    if play_again.lower() != 'n':
        game()
    else:
        print("BYE.")
game()

2 Answers

When I ran your code, I had an UnboundLocalError for your guess when I entered a letter because the guess variable was never assigned if int() failed and your ValueError couldn't use the guess variable. Other than that I couldn't reproduce your errors. Once I assigned the guess variable outside of the Try block it worked fine. Here's my only revision:

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

Thank you.

Thanks. I mistakenly typed that I had a ValueError. I was getting an UnboundLocalError. I tried entering your bit of code into mine but now it won't accept any letters at all. Do you have any suggestions on how I can fix this? Thanks for your time.

Hi. I got that bit of code working. I think I had an indent problem. Thanks for your help.

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! I'm going to take an educated guess and say that you've probably been working with this video. Take a look at the Teacher's Notes associated. This bug is intentional.

When I run your code, I receive an UnboundLocalError if I put in a letter for the first guess. And here's why that's happening. You are trying to assign an int to guess, but when that fails (ie you entered the letter "f"), the assignment never occurs. In your error handling, you then try and format the string with the value of guess, but again, that assignment never happened. It failed. At this point, guess is undefined.

However, when you first enter a number, then the assignment does happen, but only for that number. The next time you enter a letter, it will throw the value error and the string is formatted with the current value of guess. Because the reassignment never happened, guess contains the last value held when the assignment was successful.

Hope this helps! :sparkles:

Thank you for your help! Now I understand what the error is and why it's happening. I still don't understand how to fix it, but thanks for clearing up that I hadn't done anything wrong with my coding. Thanks so much for your time.