Python Python Basics (2015) Number Game App Number Game Refinement

Galen McAllister
PRO
Galen McAllister
Pro Student 982 Points

Value 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
Steven Parker
171,227 Points

You 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
henry hui
2,698 Points

I 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!