2015-09-10 163 views
1

我对python非常陌生,所以我对这个函数有什么问题非常困惑。基本上,我想做一个函数来检查x是否是整数,如果是,那么它应该评估它为“正”或“负”。如果没有,那么我希望它返回“不是int”作为结果。Python,基本功能混淆

下面是我试图在现在修复一段时间的功能。

def negativeIntAlert(x): 

    if x != int(x): 
    return "not int" 
    else: 
    if x >= 0: 
     return "positive" 
    else: 
     return "negative" 

我不明白为什么它不能像它应该那样工作,因为它几乎每次都给我“不是int”。我也有布尔类型的问题,如: negativeIntAlert(True),它给我“积极”,而不是“不是int”,我可以做什么使布尔=“不是整数”在这个特定的功能?

+3

'bool'是Python2(历史原因)为int的子类,你可以试试这个,而不是使用。而且你应该确定“不应该如此”的含义。 –

+4

提示:'int(True)== True == 1';) – NiziL

回答

3

你可以尝试像

def negativeIntAlert(x): 
    if not isinstance(x, int): 
     return "not int" 
    else: 
     if x >= 0: 
      return "positive" 
     else: 
      return "negative" 

更新 你想解决的布尔问题,所以使用type代替

if type(x) != int: 
     return "not int" 
+0

非常感谢!我现在开始工作了! =) – Jade

+0

不客气 – simpletron

2

由于历史的原因,布尔是从int继承,所以isinstance(True, int)会给你True,从PEP-0285

这个PEP建议引入一个新的内置类型bool, ,它带有两个常量False和True。 bool类型将是int类型的一个简单的子类型(C) ,在大多数方面,值 False和True的行为类似于0和1(对于 示例,False == 0和True == 1将是true)除repr()和 str()。概念上返回布尔型 结果的所有内置操作将更改为返回False或True,而不是0或1;例如,比较,“not”运算符和诸如 isinstance()的谓词。

因此,这将是更好:

def negativeIntAlert(x): 
    if isinstance(x, int) and not isinstance(x, bool): 
     if x >= 0: 
      return "positive" 
     else: 
      return "negative" 
    else:  
     return "not int" 
+0

非常感谢您的支持! – Jade

+0

@Jade不用客气。这是有趣的方面) – wolendranh

1

如果条件

def negativeIntAlert(x): 
    try:  
     x = int(x) 

     if x >= 0: 
      return "positive" 
     else: 
      return "negative" 
    except: 
     print ("it is no an int") 
+0

'int(4.0)'return 4所以,这不会解决这个问题 – simpletron

+0

非常感谢! – Jade