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 trialMaximilian Hill
Python Development Techdegree Graduate 7,661 PointsProject 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
231,261 PointsThe 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.
Maximilian Hill
Python Development Techdegree Graduate 7,661 Points@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.
Maximilian Hill
Python Development Techdegree Graduate 7,661 PointsMaximilian Hill
Python Development Techdegree Graduate 7,661 PointsI need it outside the try block to help establish the while loop. Should I repeat the code in the try block?
Steven Parker
231,261 PointsSteven Parker
231,261 PointsThere are several approaches you could use:
Steven Parker
231,261 PointsSteven Parker
231,261 PointsImplementing the second method might look like this: