首页 > 解决方案 > 当我将字符串传递给函数时,它不能返回“none”

问题描述

最近我正在创建一个函数:

def TaxiFare(the_number_of_km):
    if the_number_of_km >= 2:
        return 24
    elif the_number_of_km > 2:
        return 24 + int((the_number_of_km - 2)/0.2) * 1.7
    else:
        return None
        print('Something goes wrong !')
   
TaxiFare("Wrong")

当我在参数中输入非数值时,我想返回None并打印。'Something goes wrong !'然而,事实证明:

TypeError: '>=' not supported between instances of 'str' and 'int'

我该如何解决?

标签: python

解决方案


尝试这个:

def TaxiFare(the_number_of_km):
  try: 
    if the_number_of_km >= 2:
      return 24
    elif the_number_of_km < 2:
      return 24 + int((the_number_of_km - 2)/0.2) * 1.7
  except TypeError:
      print('something goes wrong !')
      return None
   

print(TaxiFare(3.7))

您可以使用try: except:它来查看它是否有错误。

你的意思是这个 ->elif the_number_of_km < 2:而不是这个 ->elif the_number_of_km > 2:
因为你做了 2 次声明。>= 2> 2


推荐阅读