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!")
2 Answers 2
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.
8 Comments
isdigit, you'd test it in an if like in your original code (if choice.isdigit():). The try/except style of programming is common in Python, and is known as "Easier to Ask Forgiveness than Permission" (EAFP). Using an if to test input before using it is a different programming style, known as "Look Before You Leap" (LBYL). LBYL style is more common in other programing languages (like C) where exceptions either don't exist or are much slower than regular code. Sometimes LBYL is the best style in Python too, though EAFP is usually preferred.choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
In this code, the first line of code evaluates the right side of the = sign, namely, take an input from the user while displaying the text >. Once that input has been taken, store in a variable called choice.
Then, this line if "0" in choice or "1" in choice uses something called membership which just means that it tests to see if a certain string or a number or any other object is present in a given object. In this case, since raw_input always returns a string regardless of the person's entering a number or a list, if you have to check whether the number is in the string or not, then rather than doing 0 in choice, you do '0' in choice which just says, "is there a '0' in the input given by the user?" If yes, then it converts the input given by the user to an integer and then assigns it to a variable called, 'how_much'.
Furthermore, if you are looking to get only an integer from the user and then see if it is 0 or 1, I recommend you doing something like this:
choice = int(raw_input("> "))
if choice == 0 or choice == 1:
how_much = choice
This code ensures that the user will input an integer rather than alphabets; if the user does input a string (not all numbers), then the code with raise an error. This is because in the first line of code, int(raw_input("> ")), you tell the Python interpreter to convert the input given to an integer, but Python can't convert inputs like wefj6 or wedf or 324# to integer as they are not pure numbers, so it will raise an error.
gold_roomhas a weird way of getting you to type a number. What are all the bugs in this way of doing it? Can you make it better than what I've written? Look at howint()works for clues."