1

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!")
Community
  • 1
  • 1
C R
  • 25
  • 1
  • 6
  • This code does not run. If I add the missing `:`s, it gives me the expected 'dead' message when I type "fsd7sds". – AShelly Apr 14 '17 at 21:13
  • This code works fine for me with the addition of those colons. And since `choice.isdigit()` returns a boolean: your `else` will never run. – TemporalWolf Apr 14 '17 at 21:18
  • Thanks AShelly, you are right, I did forget my colons. That said, this code actually does run without them, surprisingly enough, and gives the same behavior once I add them in. =\ – C R Apr 14 '17 at 21:20
  • Your environment is wrong then... how are you running it? have you overwritten `isdigit()`? This [repl.it](https://repl.it/HKEt/0) shows it works – TemporalWolf Apr 14 '17 at 21:23
  • TemporalWolf: I actually just realized you are right. I was running a previous version of the wrong script without realizing it, which explains a lot; rather embarrassing, and a good lesson to double-check my console inputs while testing. I will mark this as closed, my code seems to work now that I'm running the right code...sorry for my dumb error, and thanks everyone for your help! – C R Apr 14 '17 at 21:28
  • 1
    @CR No worries, the question was well written. Goodluck! – TemporalWolf Apr 14 '17 at 21:30
  • Just noting here that I updated my question's code slightly after AShelly pointed out my syntax errors. It works now, it helps a lot to run the correct script in the first place! – C R Apr 14 '17 at 21:38
  • FWIW, the SO Python Chat room regulars [do not recommend LPTHW](http://sopython.com/wiki/LPTHW_Complaints). If it's working for you, that's great, but please be aware that there are several problems with this book. Also be aware that Python 2 will reach its End Of Life in 2020, so you really ought to be learning Python 3, unless you _need_ Python 2 to work on legacy code. – PM 2Ring Apr 15 '17 at 05:58
  • 1
    @PM-2Ring Thanks for the warning, I will look at those other examples listed and bear those critiques in mind. – C R Apr 18 '17 at 02:35

2 Answers2

1

I am unsure why this is failing, but in my guess the more pythonic way of doing this is via a try except statement to catch a value error:

try:
    #The following will fail with an non-numeric input
    how_much = int(choice)
except ValueError:
    dead('Man, learn to type a number.')
#Note that the else statement is not necessary as it will never execute anyway
Abid Hasan
  • 648
  • 4
  • 10
  • Thanks; my actual problem proved to be unrelated to the code I was attempting to test in the end, but this is a helpful improvement over what I was doing regardless. =) – C R Apr 14 '17 at 21:33
0

you need to make dead function in your script

def dead(message):
    print(message)
choice = raw_input("> ")
print "test"
if choice.isdigit() == False:
    dead("Man learn to type a number")