簡體   English   中英

python中的BMI計算器:太多的if語句如何減少它?

[英]BMI calculator in python: too many if statements how to reduce that?

我是編程新手,已經開始學習python。 我用python編寫了自己的第一個BMI計算器,因此我對代碼並不真正滿意。 我想我的代碼中有太多if語句,想知道如何減少它? 您能否給我一些建議或建議,以使該腳本更好,更動態?

親切的問候!!

gender = input("Are you a male(m) or female(f): ")
age = int(input("How old are you: "))
weight = float(input("How much do you weigh in kilograms?: "))
height = float(input("What is your height in centimeters: "))


bmi = round(weight / ((height/100) ** 2))

if bmi in range(19, 24) and age in range(19, 24):
    print("Your BMI is optimal for your age!")
elif bmi in range(25, 34) and age in range(20, 25):
    print("Your BMI is optimal for your age!")
elif bmi in range(35, 44) and age in range(21, 26):
    print("Your BMI is optimal for your age!")
elif bmi in range(45, 54) and age in range(22, 27):
    print("Your BMI is optimal for your age!")
elif bmi in range(55, 64) and age in range(23, 28):
    print("Your BMI is optimal for your age!")
elif bmi >= 65 and age in range(24, 29):
    print("Your BMI is optimal for your age!")
else:
    print("Your BMI is not okay for your age!!!")

if bmi < 20 and gender == "m":
    print("Your BMI is",str(bmi)+". That means underweight")
elif bmi < 19 and gender == "f":
    print("Your BMI is",str(bmi)+". That means underweight")
elif bmi in range(20, 25) and gender == "m":
    print("Your BMI is",str(bmi)+". That means normal weight")
elif bmi in range(19, 24) and gender == "f":
    print("Your BMI is",str(bmi)+". That means normal weight")
elif bmi in range(26, 30) and gender == "m":
    print("Your BMI is",str(bmi)+". That means overweight")
elif bmi in range(25, 30) and gender == "f":
    print("Your BMI is",str(bmi)+". That means overweight")
elif bmi in range(31, 40) and gender == "m":
    print("Your BMI is",str(bmi)+". That means obesity")
elif bmi in range(31, 40) and gender == "f":
    print("Your BMI is",str(bmi)+". That means obesity")
elif bmi > 40 and gender == "m":
    print("Your BMI is",str(bmi)+". That means strong obesity")
elif bmi > 40 and gender == "f":
    print("Your BMI is",str(bmi)+". That means strong obesity")
else:
    print("Your BMI is",bmi)

好的,這里有很多地方需要改進。

  • 沒有對性別輸入的驗證,因此可以輸入無法識別的值,盡管在其他情況下似乎確實可以處理該值,在該情況下,僅打印沒有解釋的BMI。
  • if bmi in range(19, 24)表示“如果bmi具有值19、20、21、22、23之一”。 因此,如果bmi為24,這不僅會失敗,而且效率極低,而且如果您決定更改BMI的float值,它將會中斷。 使用大於和小於檢查值是否在范圍內會更好。
  • 您的agebmi在if語句中交換了位置。 if bmi >= 65 and age in range(24, 29) ,則建議25歲的BMI至少為65!
  • 年齡不小於19歲的兒童不得處理。他們總是會被告知自己的BMI不是最佳的。
  • 所有重復的打印語句執行相同的操作。 快速的改進將是在if情況下改為設置一個名為“ is_bmi_optimal”或類似名稱的布爾變量,然后最后使用單個if is_bmi_optimal進行打印。

至於如何減少if語句數量的實際問題,您需要用某種方法來替換它們,這些方法定義數據結構中的年齡范圍和相應的bmi范圍,然后對其進行迭代。

這是將bisect模塊用於此目的的一種方法。 Bisect用於按排序順序維護列表,但也可以用於搜索排序列表,以查找新值適合的位置,並保持排序順序。 這意味着可以通過將這些范圍定義為每個范圍的最小值列表來查找值在一系列范圍中的合適位置。 因此,您的年齡范圍19-24、25-35、35-44、45-54、55-64、65歲以上將被表示為列表[ bisect.bisect_left ],而bisect.bisect_left會告訴您年齡在該列表中的年齡介於0 (小於25)到5 (65或更大)之間的值。

import bisect

gender = input("Are you a male(m) or female(f): ")
age = int(input("How old are you: "))
weight = float(input("How much do you weigh in kilograms?: "))
height = float(input("What is your height in centimeters: "))

bmi = round(weight / ((height/100) ** 2))

if age < 19:
    print("You're too young for this and I'm concerned you may be at risk of developing an eating disorder.")
    exit()

optimal_bmi_range_min_ages = [25, 35, 45, 55, 65]
optimal_bmi_ranges = [(19, 24), (20, 25), (21, 26), (22, 27), (23, 28), (24, 29)]
optimal_bmi_range = optimal_bmi_ranges[bisect.bisect_left(optimal_bmi_range_min_ages, age)]

if bmi >= optimal_bmi_range[0] and bmi <= optimal_bmi_range[1]:
    print("Your BMI is optimal for your age!")
else:
    print("Your BMI is not okay for your age!!!")

bmi_categories = ["underweight", "normal weight", "overweight", "obesity", "strong obesity"]
if gender == "m":
    bmi_cat_thresholds = [20, 26, 31, 41]
elif gender == "f":
    bmi_cat_thresholds = [19, 25, 31, 41]
else:
    print("Your BMI is",bmi)
    exit()

bmi_category = bmi_categories[bisect.bisect_left(bmi_cat_thresholds,bmi)]
print("Your BMI is " + str(bmi) + ". That means " + bmi_category)

這里有兩個問題:

  1. 性能,即算法對大量輸入執行的效率。
  2. 可讀性和可維護性。

由於您的程序僅查看一組輸入,因此我僅考慮其中的第二個。

您可以以更簡單的方式編寫代碼的第一部分:

bmi = weight / ((height/100) ** 2)

optimal_bmi_age = [((19, 24), (19, 24)), ((25, 34), (20, 25)), ((35, 44), (21, 26)),
                   ((45, 54), (22, 27)), ((55, 64), (23, 28)), ((65, 1000), (24, 29))]

for ((bmi_min, bmi_max), (age_min, age_max)) in optimal_bmi_age:
    if (bmi_min <= bmi <= bmi_max) and (age_min <= age <= age_max):
        print('Your BMI is optimal for your age!')
        break
else:
    print('Your BMI is not okay for your age!!!')

注意我們在這里所做的。 我們將參數 (即最佳BMI /年齡的邊界)與邏輯 (即for / else循環和if語句)分開。 此過程可以在您的整個代碼中應用。 如果您更改參數,這將提高可讀性和維護性。

如果主要關注性能/優化,請參閱@DavidScarlett的解決方案 該解決方案還實現了分離參數和邏輯的類似想法。

嘗試這個

bmiheight=self.heightcm.get()
      print(bmiheight)
      bmiweight=self.weightkg.get()
      bmi= float((bmiweight)/((bmiheight / 100)**2))
      self.bmi = bmi
      print(bmi)
      self.label1=Label(self.master,text='Your BMI is %.2f' % bmi).grid(row=5,column=0)

      if bmi <= 18.5:
           self.label2=Label(self.master,text='This places you in the underweight group.',fg='blue').grid(row=6,column=0)
           totalindex = 'underweight'
           self.totalindex = totalindex
      elif bmi >18.5 and bmi <25:
           self.label3=Label(self.master,text='This places you in the healthy weight group.',fg='green').grid(row=6,column=0)
           totalindex = 'healthy'
           self.totalindex = totalindex
      elif bmi >= 25 and bmi < 30:
           self.label4=Label(self.master,text='This places you in the overweight group.',fg='orange').grid(row=6,column=0)
           totalindex = 'overweight'
           self.totalindex = totalindex
      elif bmi >=30:
           self.label5=Label(self.master,text='This places you in the obese group.',fg='red').grid(row=6,column=0)
           totalindex = 'obese'
           self.totalindex = totalindex

      if bmi >0 and bmi <999999999999999999999:
           self.button6=Button(self.master,text="Store Data",fg='red',command=self.dynamic_data_entry).grid(row=8,column=0)

暫無
暫無

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

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