比Python更强大

时间:2020-10-14 00:23:05

标签: python

无法正确运行此代码。

在检查值是否大于或等于下一个值时。如果值不是int,则不确定如何使它打印未知。

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)

感谢指导。

2 个答案:

答案 0 :(得分:1)

您可以使用isinstance function来检查值是否是某种类型的实例(考虑了类层次结构)

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 浮点数,则可以改用以下条件:

if not isinstance(x, (int, float,)) or not isinstance(y, (int, float,)):
    ...

答案 1 :(得分:0)

您可以使用isinstance来检查传递的参数是否为整数。下面的示例代码。

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))