我是 python 的新手,所以我对这个函数有什么问题感到非常困惑。基本上,我想创建一个函数来检查 x 是否为整数,如果是,那么它应该将其评估为“正”或“负”。如果不是,那么我希望它作为结果返回“not int”。
这是我尝试来回修复了一段时间的函数。
def negativeIntAlert(x):
if x != int(x):
return "not int"
else:
if x >= 0:
return "positive"
else:
return "negative"
我不明白为什么它不能正常工作,因为它几乎每次都给我“not int”。我也有 bool 类型的问题,例如: negativeIntAlert(True),它给了我“positive”而不是“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"
更新
您想解决 bool 问题,所以请改用 type
if type(x) != int:
return "not int"
关于Python,基本函数混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32501869/