In LPTHW, Study Drill 5 for exercise 35 asks:
The gold_room has a weird way of getting you to type a number...Can you make it better than just checking if "1" or "0" are in the number? Look at how
int()
works for clues.
Here's the relevant gold_room code:
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!")
I tried using a list of numbers 0 through 9. Not exactly a "better" way, but I couldn't think of much else:
next = raw_input("> ")
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if next in numbers:
how_much = int(next)
As with "0" and "1" in the original code, I'd hoped each digit would function as a keyword. Unfortunately it didn't work for any number above 9.
I've searched for other solutions and found people using .isdigit()
, try:
and except ValueError:
to solve the problem, but the book hasn't covered those yet, so I'd like to avoid using them. I'm looking for any other suggestions, especially something dealing with int()
as the author mentioned. Thanks.
[edit]: This has been marked as a duplicate. It's not a duplicate. Read my responses and the question carefully; there are caveats. The answer that was linked uses try
and other things I'm trying to avoid because they haven't been covered in the book yet.