Having looked at How do you check in python whether a string contains only numbers? , I am aware that string.isdigit() is an effective way to test if a string contains only digits and nothing else. I am using Python 2.7.
However, when I try to use it in the following code, my program crashes with an "invalid literal for int() with base 10" error when I input any mix of numbers and non-numbers, e.g. "fsd7sfd" or similar. (The code works fine with either number-only strings or alpha-only strings.)
I don't understand how this is happening, since as far as I can tell, the assignment of "how_much = int(choice)" should never happen unless the string only contains digits in the first place, when choice.isdigit() is True.
Can someone help me understand what I'm missing?
As a side note, that "print "test"" line doesn't seem to get processed before the error either, which adds to my confusion.
(I'm trying to improve the "gold_room()" function from https://learnpythonthehardway.org/book/ex35.html , the rest of the code is there for reference.)
Error:
This room is full of gold. How much do you take?
> sdfgsd8sd
Traceback (most recent call last):
File "ex35.py", line 79, in <module>
start()
File "ex35.py", line 71, in start
bear_room()
File "ex35.py", line 36, in bear_room
gold_room()
File "ex35.py", line 9, in gold_room
how_much = int(choice)
ValueError: invalid literal for int() with base 10: 'sdfgsd8sd'
Code:
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
print "test"
if choice.isdigit() == False:
dead("Man, learn to type a number.")
else:
how_much = int(choice)
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")