Python,基本函数混淆
我对python非常陌生,所以我对函数的错误感到非常困惑。基本上,我想做一个函数来检查x是否是整数,如果是,那么它应该计算为“正”或“负”。如果不是,那么我希望它作为结果返回“not int” 下面是我现在尝试来回修复的函数Python,基本函数混淆,python,python-2.7,Python,Python 2.7,我对python非常陌生,所以我对函数的错误感到非常困惑。基本上,我想做一个函数来检查x是否是整数,如果是,那么它应该计算为“正”或“负”。如果不是,那么我希望它作为结果返回“not int” 下面是我现在尝试来回修复的函数 def negativeIntAlert(x): if x != int(x): return "not int" else: if x >= 0: return "positive" else: ret
def negativeIntAlert(x):
if x != int(x):
return "not int"
else:
if x >= 0:
return "positive"
else:
return "negative"
我不明白为什么它不能正常工作,因为它几乎每次都给我“notint”。我也有布尔类型的问题,例如:
negativeIntAlert(True),它给我的是“正数”而不是“not int”,在这个特定函数中,我能做些什么使Boolean=“not 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"
你可以试试类似的东西
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"
由于历史原因,布尔值是从int继承的,因此
isinstance(True,int)
将从以下位置为您提供True
:
本政治公众人物建议引入一种新的内置类型bool,
有两个常量,False和True。布尔类型将是一个
int类型的直截了当的子类型(在C中),以及
False和True在大多数方面的行为类似于0和1(对于
例如,除了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"
由于历史原因,布尔值是从int继承的,因此
isinstance(True,int)
将从以下位置为您提供True
:
本政治公众人物建议引入一种新的内置类型bool,
有两个常量,False和True。布尔类型将是一个
int类型的直截了当的子类型(在C中),以及
False和True在大多数方面的行为类似于0和1(对于
例如,除了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"
您可以使用if条件来尝试此操作
def negativeIntAlert(x):
try:
x = int(x)
if x >= 0:
return "positive"
else:
return "negative"
except:
print ("it is no an int")
您可以使用if条件来尝试此操作
def negativeIntAlert(x):
try:
x = int(x)
if x >= 0:
return "positive"
else:
return "negative"
except:
print ("it is no an int")
bool
是Python2中int的子类(历史原因)。您应该精确地说明“工作方式不正常”的含义。提示:int(True)==True==1
;)bool
是Python2中int的子类(历史原因)。您应该精确地说明“工作方式不正常”的含义。提示:int(True)==True==1
;)非常感谢您的支持!非常感谢您的支持int(4.0)
return4所以,这不会解决这个问题int(4.0)
return4所以,这不会解决这个问题