vankee
vankee

Reputation: 93

About if x is int

from sys import exit

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

    next = raw_input("> ")
    if  next is int:
        if next < 50:
            print "Nice, you're not greedy, you win!"
            exit(0)
        else:
             dead("You greedy bastard!")
    else:
        print "Man,you need to learn how to print a number!"
def dead(why):
    print why, "Good job!"
    exit(0)

gold_room()

whatever integer I input,always turns out that"Man,you need to learn how to print a number". Why the first if doesn't work? Thank you guys!

Upvotes: 1

Views: 572

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

raw_input returns a string, you can use str.isdigit to check if a string contains only digits but it will fail for negative numbers:

nxt = raw_input("> ")
if nxt.isdigit(): # str.isdigit
    if int(nxt) < 50:

The best way to do what you want is to use a try/except

while True:
    nxt = raw_input("> ")
    try: 
        nxt = int(nxt) 
        break # break if we got valid input that can be cat
    except ValueError: # else we get here and print our message and go back to start again
        print("Man,you need to learn how to print a number!")
        continue
if nxt < 50: # if we get here we got valid input from the potentially greedy  b!*!*!*d!"
   print("Nice, you're not greedy, you win!")
   return 
dead("You greedy b!*!*!*d!") # we don't need an else as if previous statement in True we will have exited the function

So in your function:

def gold_room():
    print "This room is full of gold.  How much do you take?"
    while True:
        nxt = raw_input("> ")
        try:
            nxt = int(nxt)
            break
        except ValueError:
            print("Man,you need to learn how to print a number!")
            continue
    if nxt < 50:
        print("Nice, you're not greedy, you win!")
        return       
    dead("You greedy b!*!*!*d!")

I would not use next as a variable name as it shadows the builtin function python function next.

If you did ever want to check the type of an object you would use isinstance:

if isinstance(object,type):

Upvotes: 4

jhulme
jhulme

Reputation: 110

Can also use try excepts for this

try:
    if int(next) < 50:
        ...
    else:
        ...
except ValueError as e:
    #handle error

This attempts to cast the string to an integer if it can't be done i.e. not a number then it will enter the exception block

Upvotes: 0

Rob Falck
Rob Falck

Reputation: 2704

raw_input returns a string.

xin = raw_input("> ")
try:
    x = int(xin)
except ValueError:
    print "xin is not an int"

Upvotes: 2

Related Questions