Skip to main content
 首页 » 编程设计

python之关于如果 x 是 int

2025年05月04日15lvdongjie

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

无论我输入什么整数,结果总是“伙计,你需要学习如何打印数字”。 为什么第一个 if 不起作用?谢谢大家!

请您参考如下方法:

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 function next。

如果你确实想检查一个对象的类型,你会使用 isinstance:

if isinstance(object,type):