簡體   English   中英

如何在python 3中解決“ int”和“ NoneType”實例之間不支持“'<'”的問題?

[英]How do I resolve “'<' not supported between instances of 'int' and 'NoneType'” in python 3?

我想在下面的代碼中添加一個條件。 如您所見,我想為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設置為浮點值,這就是為什么會出現錯誤(這表明您無法使用>運算符將浮點與None進行比較。 )。 您想要添加一個return語句,以便您的函數在調用時實際上返回一些內容,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM