关于if是否为int

时间:2015-02-20 14:15:06

标签: python

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()

无论我输入什么整数,总是证明“男人,你需要学习如何打印数字”。 为什么第一个如果不起作用?谢谢你们!

3 个答案:

答案 0 :(得分:4)

raw_input返回一个字符串,你可以使用str.isdigit检查一个字符串是否只包含数字但是对于负数会失败:

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

做你想做的事的最好方法是使用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

所以在你的功能中:

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!")

我不会将next用作变量名,因为它会影响内置函数python函数。

如果您确实想要检查您将使用的实例的类型:

if isinstance(object,type):

答案 1 :(得分:2)

raw_input返回一个字符串。

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

答案 2 :(得分:0)

也可以使用try excepts for this

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

如果无法完成,则尝试将字符串转换为整数,即不是数字,然后它将进入异常块