0

I'm struggling with the extra credit of excercise 35 from the book "Learn Python the hard way". Based on the advise provided in previous comments (learn python the hard way exercise 35 help) I tried two options:

from sys import exit

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

    next_move = raw_input("> ")
    if isinstance(next_move, int):
        how_much = int(next_move)
    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!")

My issue is that the line: if isinstance... is never passed! It is always skipped. I always get as a result Man, learn to type a number (even if I type in a number).

I do succeed with the code below:

next_move = raw_input("> ")
char = list(str(next_move))
for v in char:
    if v in str(range(0, 10)) and v != " " and v != ",":
        how_much = int(next_move)
    else:
        dead("Man, learn to type a number.")

However, I would like to understand why the first option does not work :(

Community
  • 1
  • 1
Vito
  • 33
  • 1
  • 1
  • 5
  • 2
    The raw input is a string, how could it ever be an instance of integer? It's not true, that's why it doesn't pass. Your second solution is just horrible, frankly - even `v in '0123456789'` would have been preferable. – jonrsharpe Jun 18 '16 at 21:01
  • Being an integer and being a string with only numbers are two different things. – gre_gor Jun 18 '16 at 21:05

1 Answers1

0

Raw input is going to be a string, so it's normal for your test to fail. A more pythonic approach is:

next_move = raw_input("> ")
try:
    how_much = int(next_move)
except ValueError:
    dead("Man, learn to type a number.")
kardaj
  • 1,897
  • 19
  • 19