gpt4 book ai didi

python - 如何在 python 3 中解析 "' <' not supported between instances of ' int' 和 'NoneType' "?

转载 作者:行者123 更新时间:2023-12-01 01:56:20 24 4
gpt4 key购买 nike

我想在下面的代码中添加一个条件。正如您所看到的,我想打印相应的 BMI 值的相应消息。我在 if 和 elif 语句中使用 <= 或 >+ 时遇到错误。请告诉我在这种情况下该使用什么。

def bmi(w,h):
print((w)/(h**2))

weight = float(input('Weight (kg): '))
height = float(input('Height (m): '))
b = bmi(weight,height)

if 18<b<25 :
print('Your weight is normal.')
elif b<18:
print('You are underweight.')
elif 25<b<29:
print('You are overweight.')
elif b>29:
print('You are obese.')

输出 -

Weight (kg): 65
Height (m): 1.72
21.971335857220122
Traceback (most recent call last):
File "D:/Coding/Python Exercises/Ass5/Ass5.py", line 8, in <module>
if 18<b<25 :
TypeError: '<' not supported between instances of 'int' and 'NoneType'

Process finished with exit code 1

最佳答案

问题出在你的函数上:

def bmi(w,h):
print((w)/(h**2))

您不会在此函数中返回任何内容,因此,当您在 b = bmi(weight,height) 行中调用它时,您不会设置 b 可以是 None 值以外的任何值。您所做的只是将 bmi 打印到屏幕上,但尚未将 b 设置为浮点值,这就是您收到错误的原因(这告诉您您无法使用 > 等运算符将 float 与 None 进行比较)。您想要添加一个 return 语句,以便您的函数在调用时实际上返回一些内容,如下所示:

def bmi(w,h):
print((w)/(h**2))
return w/h**2

关于python - 如何在 python 3 中解析 "' <' not supported between instances of ' int' 和 'NoneType' "?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50139140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com