[英]Is there a way to better write the code to find the number between two numbers? It's not reading the 2nd or the 3rd elif statements
BMI_num = 21
if BMI_num <= 18.5:
BMI_title = 'Underweight'
print ('Results . . . ')
print ('Your BMI is: ', BMI_num , '--' , BMI_title)
elif 18.5 > BMI_num >= 24.9:
BMI_title = 'Normal'
print ('Results . . . ')
print ('Your BMI is: ', BMI_num , '--' , BMI_title)
elif 25 >= BMI_num >= 29.9:
BMI_title = 'Overweight'
print ('Results . . . ')
print ('Your BMI is: ', BMI_num , '--' , BMI_title)
elif BMI_num < 30:
BMI_title = 'Obese'
print ('Results . . . ')
print ('Your BMI is: ', BMI_num , '--' , BMI_title)
您需要將>
替換為<
。 諸如18.5 > BMI_num >= 24.9
類的比較將始終為 False,因為沒有數字可以同時小於 18.5 和大於 24.9。
您可能還需要考慮當BMI_num
為 24.95 或 29.95 時不會運行任何代碼。
您還可以通過在之后打印來減少一些代碼重復。
if BMI_num <= 18.5:
BMI_title = 'Underweight'
elif 18.5 < BMI_num < 25:
BMI_title = 'Normal'
elif 25 <= BMI_num <= 29.9:
BMI_title = 'Overweight'
elif BMI_num < 30:
BMI_title = 'Obese'
print ('Results . . . ')
print (f'Your BMI is: {BMI_num} -- {BMI_title}')
你的方法實際上是看一個數字是否在兩個數字之間完全沒問題。 只是你的范圍不對。 對於第二個 if 語句,18.5 > BMI_num >= 24.9 永遠不可能。 24.9 不低於 18.5。 我相信你的意思
elif 18.5 < BMI_num <= 24.9:
# some code that runs because this elif is true.
第三個elif,29.9不能小於等於25,你也改一下
elif 25 <= BMI_num <= 29.9:
# some code that runs because this elif is true
第四個和第一個 if 語句沒問題。
您可能希望將第四個 if 語句更改為
elif BMI_num >= 29.9
# some code that runs because this elif is true
因為它與前面的語句一起工作的唯一方法是 BMI_num > 29.9 且小於 30。它還包括 29.9 到 30,這與做
elif BMI_num >= 30
# some code that runs because this elif is true
也可以是
else:
"""
some code that runs because all the previous ones were
false
"""
另一種方法是
if {variable_name} in range(x, y)
,但不要使用大括號,而只使用變量,在這段代碼中是 BMI_num,x,y 是兩個數字。 范圍是從 x 到 y 的所有數字,不包括 y。 從任一變量中加/減一個以獲得正確的范圍
elif
條件中的比較符號是錯誤的,因為它們是錯誤的方向並且也不涵蓋邊界情況。 我還建議使用 function 並刪除多余的打印語句,如下所示:
def log_bmi(BMI_num):
if BMI_num <= 18.5:
BMI_title = 'Underweight'
elif 18.5 < BMI_num <= 25:
BMI_title = 'Normal'
elif 25 < BMI_num <= 30:
BMI_title = 'Overweight'
else:
BMI_title = 'Obese'
print ('Results . . . ')
print ('Your BMI is: ', BMI_num , '--' , BMI_title)
def log_bmi(BMI_num):
if BMI_num <= 18.5:
BMI_title = 'Underweight'
elif BMI_num <= 25:
BMI_title = 'Normal'
elif BMI_num <= 30:
BMI_title = 'Overweight'
else:
BMI_title = 'Obese'
print ('Results . . . ')
print ('Your BMI is: ', BMI_num , '--' , BMI_title)
labels = {0.1: "Underweight", 18.5: "Normal", 24.9: "Overweight", 29.9: "Obese"}
ibm = 21
print([labels[label] for label in labels if ibm/label >= 1][-1])
一種簡單的 2 行方式,只是為了好玩(因為它的可讀性很低)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.