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

Project 1-Guessing Game: Valuerror won't convert to integer

When trying to catch and print a value error for my code, I get the error message instead of my desired output response. Can someone help?

This is an example link

My code in markdown as well:

import random

#Store a random number as the answer/solution
answer= random.randint(1,10)
num_guesses= 1

#Display an intro/welcome message to the player.
#def start_game():
print("Welcome to Max's guessing game. Lets have some fun.")
guess= int(input("Please choose a number between 1 and 10: "))
while guess != answer:
    num_guesses+= 1 

    try:
        guess= int(guess)

    except ValueError:
        print("Oh no thats an invalid response. Please try again: ")

    else:
        if guess <= answer:
            guess= int(input("Oops, wrong number. You need to go higher try again: "))

        else:
            guess= int(input("Oops, wrong number. You need to go lower try again: "))
    print("{} is correct! It took you {} attempts(s),".format(answer,num_guesses), "The game is now over, goodbye!")

2 Answers

Steven Parker
Steven Parker
229,744 Points

The first int conversion (on line 21) is being performed outside of the try block, so you automatically get the system error message instead of the custom one you have created with the try/except inside the loop. The same thing happens with the conversions done on lines 33 and 36.

I need it outside the try block to help establish the while loop. Should I repeat the code in the try block?

Steven Parker
Steven Parker
229,744 Points

There are several approaches you could use:

  • put the first conversion in its own try block
  • initially set "guess" to a value guaranteed not to match, so you don't need to input outside of the loop
  • put the entire program in a try block
Steven Parker
Steven Parker
229,744 Points

Implementing the second method might look like this:

guess = 99        # this starting value is guaranteed not to match so loop will run
while guess != answer:
    try:
        guess = int(input("Please choose a number between 1 and 10: "))

@steven parker. I'm still having trouble figuring out what you mean. I think I would want to go with option two because it seems like the cleanest option. However, I don't know where to begin.