Question

So I've just completed Exercise 35 on Learn Python the Hard Way http://learnpythonthehardway.org/book/ex35.html

The function below is from that exercise. I realize that it's flawed by only checking if "next" is a "0" or a "1" rather than any number (by using .isdigit() or similar), this results in an error for any input greater than 1 but less than 10.

However an input of 10 or greater it seems to work fine. For example if I enter "13" which is obviously not "0" or "1" this statement "if "0" in next or "1" in next:" returns true, how can this be?

def gold_room(): print "This room is full of gold. How much do you take?"

next = raw_input("> ")
if "0" in next or "1" in next:
    how_much = int(next)
else:
    dead("Man, learn to type a number.")

if how_much < 50:
    print "Nice, you're not greedy, you win!"
    exit(0)
else:
    dead("You greedy bastard!")
Was it helpful?

Solution 2

You're doing a string comparison. The "1" character is in "13", so this evaluates to TRUE. You seem to be thinking if int(next) == 1, which is a numerical comparison and should behave as you describe.

OTHER TIPS

raw_input() returns a string. The expression '0' in string or '1' in string does two substring searches. '1' in '9999' would evaluate to False so numbers >= 10 can fail that test as well.

The exercise is trying to tell you that you need to check the string returned by raw_input() is in legal numeric notation and get an int value from it with:

try:
    how_much = int(next)
except ValueError:
    dead("Man, learn to type a number.")

NOTE: memorizing what exceptions may be raised by which kind of operations is an important topic when learning Python. Most tutorials don't stress this enough. Beginners would want to memorized that:

  • int('x') would raise ValueError
  • {}['KEY'] would raise KeyError
  • [][0] would raise IndexError

when writing any Python code that converts a string to a number, or uses lists or dictionaries.

next is a string which is being treated as a collection of characters. The first character of "13" is "1"; the expression "1" in "13" is true.

I get syntax error on the following code for the gold_room function. Zed challenges us to alter the base code but my attempts to add particular outcomes breaks the program. The problem arises at "if how_much == 68:" ...

def gold_room():
    print "This room is full of gold.  How much do you take?"

    choice = raw_input("> ")
    if choice.isdigit():
        how_much = int(choice)
    else:
        dead("Man, learn to type a number. But you can't, because you're dead.")

    if how_much == 68:
        print "Awwwww yea, you crazy."
    elif how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("You greedy bastard!")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top