Ex 35 - Study Drills solutions?

I just finished Example 35, and I was trying to tackle the best way to fix the gold count.

The gold_room has 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 how int() works for clues.

I was looking at Stack Exchange and found a solution, and I’m curious how it measures up to @zedshaw’s solution here:

The solution I discovered is using “try…except”:

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

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

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

My solution seems to work fine, but in the larger picture is there an advantage to one or the other?

I solved it the exact same way. I think it is good practice. @zedshaw recently mentioned a lot the isdigit() function. With it you can do something like this:

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

The isdigit() string-Method will check if a string (everything with double or singel quotes around it "", '') will consist of only numbers. If yes it will return True if not False:

number = "4"
number.isdigit()
>>> True
not_number = "one"
not_number.isdigit()
>>> False

I think both methods are fine. The advantage debends on the problem. I think to know about try except is very good, because later on you will use it a lot to make sure your programs will run seamlesly without crashing all the time.

1 Like

I’d use them both together as one (try, except) is ensuring the if-statement is handled well in case the user does some weirdness or you script a bug, whereas the other is about validating the input variable type is a number 0-9.

If you just used the latter, and the user input ‘2’, which is a digit, but not handled by the if-statement, the method would throw and exception.

1 Like