Search code examples
pythonraw-input

raw_input in Python


I am going through a tutorial on Python. I am not sure what the following block of code means.

choice = raw_input("> ")
if "0" in choice or "1" in choice:
    how_much = int(choice)

I understand that I am to key in an input of a certain number of Gold. But what does "0" and "1" mean? Is there a better way to do it? Thank you!

The entire code is here.

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

    choice = raw_input("> ")
    if "0" in choice or "1" in choice:
        how_much = int(choice)
    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!")

Solution

  • The word in is an operator in Python. It tests if its left argument is contained within its right hand argument. With strings (which both "0" and choice are), it does a substring check.

    So, "0" in choice tests to see if the choice string contains one or more zeros. The same thing is done for "1". So, the test "0" in choice or "1" in choice tests if there is either a "0" or a "1" in the user's input.

    That's a fairly silly test. It will reject inputs like "23" and attempt to convert nonsense like "foo0baz" to an integer (and fail with an exception).

    A better test is str.isdigit, which tests if all the characters in a string are decimal digits (0-9):

    if choice.isdigit():
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")
    

    This idiom, of testing inputs ahead of time, is known as "Look Before You Leap" (LBYL) in Python circles. It's very common in languages like C that don't have good exception handling.

    An alternative approach is to simply try the conversion, and then catch any exception that is raised if the input was not valid:

    try:
        how_much = int(choice)
    except ValueError: # user did not enter a valid integer
        dead("Man, learn to type a number.")
    

    This style of programming is known as "Easier to Ask Forgiveness than Permission" (EAFP) and is often more popular in Python programming than LBYL, as our exceptions are fast and easy to use.

    Whether LBYL or EAFP is better in a given situation is a matter of judgement. Sometimes one style is clearly shorter or easier to understand than the other, but a lot of the time either one can work. Python programmers tend to prefer EAFP whenever it is not obviously worse then LBYL, but there's not a hard rule. It's important to know how to program with both idioms.