无法准确运行此代码。
检查值是否大于或等于或小于下一个值时。如果值不是整数,则不确定如何使其打印未知
def check(x, y):
if x == y:
return 'equal'
if a > b:
return 'greater than'
if x < y:
return 'less than'
#how can I add a line of code to return 'NA" if is not an int:
return "NA"
check(5, 5)
check('r', 5)
感谢指导。
您可以使用isinstance
函数来检查一个值是否是某个类型的实例(这将考虑类层次结构(。
def check(x, y):
if not isinstance(x, int) or not isinstance(y, int):
return "NA"
if x == y:
return 'equal'
if a > b:
return 'greater than'
if x < y:
return 'less than'
如果你想检查int或float,你可以使用这个条件:
if not isinstance(x, (int, float,)) or not isinstance(y, (int, float,)):
...
您可以使用isinstance
检查传递的参数是否为int。下面的示例代码。
def check(x, y):
if isinstance(x, int) and isinstance(y,int):
if x == y:
return 'equal'
if x > y:
return 'greater than'
if x < y:
return 'less than'
return("NA")
print(check(5,5))
print(check('r',5))