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 trialGalen McAllister
Courses Plus Student 982 PointsValue Error will not display the letter I typed, but the number I typed previously
To clear that question up, here is what my console displays:
Guess a number between 1 and 10: 4
My number is lower than 4
Guess a number between 1 and 10: h
4 isn't a number!
Instead of saying h isn't a number, it uses the number that I typed previously (4).
Here is what my code looks like:
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("{} isn't a number!".format(guess))
Any thoughts?
1 Answer
Steven Parker
231,271 PointsYou set "guess" by converting the input into a number. When you type "h" that conversion fails, which is what switches the flow into the "except" block. But "guess" was never reassigned because of the failure, and "int" would never pass the "h" through anyway.
You can fix this by storing the input as a string into a variable before you convert it, and then converting that into a number. Should it fail, the error message can use the string variable instead of the number variable to report what was typed.
henry hui
2,698 Pointshenry hui
2,698 PointsI tried to fix it and here is what my code looks like:
try:
----guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
----guess2 = str(input("Guess a number between 1 and 10: "))
----print("{} isn't a number!".format(guess2))
However, it asked me twice every time once i input a string, do you know how can i fix this too? Thanks!
Guess a number between 1 and 10: h
Guess a number between 1 and 10: h
h isn't a number!
Guess a number between 1 and 10: dfgf
Guess a number between 1 and 10: fdgf
fdgf isn't a number!
Guess a number between 1 and 10: fgdfgd
Guess a number between 1 and 10: gdfgdfg
gdfgdfg isn't a number!