有效的编程来计算Python中的BMI

时间:2017-11-12 07:56:46

标签: python

我是编程和初级阶段的新手。我写了一个程序来计算BMI,这里有几个主题的帮助。

代码审查:我在程序中使用了main函数三次,我认为编写bmi公式也可以更有效,即避免将float转换为变量。所以请建议有效地编写相同的代码。

我也可以从https://automatetheboringstuff.com学习ptyhon,如果你能提出建议在线学习python的最佳方法。 这是我的代码:

import re
print('Calculate your body mass index(BMI) today.')
def main():

    while True:
        myName = input('Enter your name:')
        if re.match('^[a-z, A-Z, ,]*$', myName):
            print ('Nice to meet you, ' + myName)
            return
        else:
            print ('You should enter a to z letters only!')

if __name__ == "__main__":
    main()
def main():
    while True:
        global height
        height = input('Enter your height in cms: ')
        if re.match('^[0-9]*$', height):
            return
       else:
            print ('You should enter 0 to 9 letters only!')

if __name__ == "__main__":
    main()
def main():
    while True:
        global weight
        weight = input('Enter your weight in kgs: ')
        if re.match('^[0-9]*$', weight):
            return
        else:
            print ('You should enter 0 to 9 letters only!')

if __name__ == "__main__":
    main()
bmi = round((float (weight)/ (0.0001*float(height)*float(height))), 2)
minIdealWeight = round(18.5*0.0001*float(height)*float(height), 2)
maxIdealWeight = round(25*0.0001*float(height)*float(height), 2)
if 18.5<bmi<25:
        print('Your BMI is '+str(bmi)+'.' '\n Maintain your weight, you\'re normal.')
elif bmi<18.5:
        print('Your BMI is '+str(bmi)+'.' '\nGain some weight, you\'re underweight.')
        print('Your ideal weight is between '+str(minIdealWeight)+' to ' +str(maxIdealWeight)+' kgs.')
else:
        print('Your BMI is '+str(bmi)+'.' '\nLoose some weight, you\'re overweight.')
        print('Your ideal weight is between '+str(minIdealWeight)+' to ' +str(maxIdealWeight)+' kgs.')

1 个答案:

答案 0 :(得分:0)

我建议你看看

  • 使用类(帮助删除全局变量)
  • 使用命令行开关
  • 在代码中添加一些文档
  • 具有一些通用的错误处理能力

说完了,做得好,并继续工作。