python - 当我将字符串传递给函数时,它不能返回“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'
我该如何解决?
解决方案
尝试这个:
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
推荐阅读
- php - PHP soap客户端调用停止脚本
- php - 查询检索到所有记录时如何访问每条记录 Yii2
- python - 安装flask-mysqldb失败
- jquery - 如何获取所有值剑道日历
- c++ - 为什么我不能读“”,空格,作为一个字符
- symbolic-math - 象征性地优化表达式-找出等式 Maple 2018 中的数值异常可能性
- ios - 在 MacOS 错误中弃用 i386 架构
- tensorflow - tensorflow Seq2seq模型:推理结果与预期完全不同
- java - Netbeans 无法导入 FileUtils 包?
- android - 点击屏幕,打开被点击的布局