Python,基本函数混乱

2024-04-27 03:46:35 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

出于历史原因,布尔值从int继承,因此isinstance(True, int)将从PEP-0285得到True

This PEP proposes the introduction of a new built-in type, bool, with two constants, False and True. The bool type would be a straightforward subtype (in C) of the int type, and the values False and True would behave like 0 and 1 in most respects (for example, False==0 and True==1 would be true) except repr() and str(). All built-in operations that conceptually return a Boolean result will be changed to return False or True instead of 0 or 1; for example, comparisons, the "not" operator, and predicates like 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"

你可以用if条件来代替

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

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

你可以试试

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"

相关问题 更多 >