【问题标题】:Comparing less than greather than in Python [duplicate]在Python中比较小于大于[重复]
【发布时间】:2020-10-14 08:35:24
【问题描述】:

无法准确运行此代码。

当检查值是否大于或等于或小于下一个值时。如果值不是 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)

感谢指导。

【问题讨论】:

  • 请参阅the docs 了解有关错误处理的一些想法,您可以使用 try:except 在无法比较值时捕获错误,或者您可以在进行比较之前检查输入的类型isinstance()return 是输入不是数字。此外,您在发布的代码中混合使用 a,bx,y
  • 您想如何处理 str 值?它们无效吗?你应该使用 ASCII 值吗?
  • 不,我只想让它返回 NA

标签: python


【解决方案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 float,你可以使用这个条件来代替:

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

【讨论】:

  • 是的,这会返回我正在寻找的内容 谢谢!!1
【解决方案2】:

您可以使用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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2013-08-30
    • 2018-09-06
    相关资源
    最近更新 更多