首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简易BMI计算器(Python 3)

问简易BMI计算器(Python 3)
EN

Code Review用户
提问于 2019-04-19 18:33:26
回答 2查看 4.9K关注 0票数 5

作为我的第一个Python程序,我编写了一个简单的BMI计算器。我想知道怎样才能改进这个计划。功能有用吗?我怎样才能改进它的呈现方式?

代码语言:javascript
复制
#Introduce BMI Calculator
print ('Welcome to BMI Calculator!')

#Ask if user would like to use Metric or Imperial units
input1 = input ('Would you like to input Metric units or Imperial units? ')

#If Imperial... If Metric... Calculate BMI...
if input1 == 'imperial':
    heightIN = float(input('Input your height in Inches (in): '))
    weightLB = float(input('Input your weight in Pounds (lbs):' ))
    BMI = round(((weightLB/(heightIN*heightIN))*703), 2) 


    if BMI >= 19 and BMI <= 24:
        print ('Your BMI is', BMI, 'so, you are healthy weight!')

    elif BMI >= 25 and BMI <= 29:
        print ('Your BMI is', BMI, 'so, you are overweight!')

    elif BMI >= 30 and BMI <= 39:
        print ('Your BMI is', BMI, 'so, you are obese!')

    elif BMI > 39:
        print ('Your BMI is', BMI, 'so, you are extremely obese!')

    elif BMI < 19:
        print ('Your BMI is', BMI, 'so, you are underweight!')

elif input1 == 'metric':
    heightCM = float(input('Input your height in Centimeters (cm): '))
    weightKG = float(input('Input your weight in kilograms (kg): '))
    heightM = heightCM*0.01
    BMI = round((weightKG/(heightM*heightM)), 2)

    if BMI >= 19 and BMI <= 24:
        print ('Your BMI is', BMI, 'so, you are healthy weight!')

    elif BMI >= 25 and BMI <= 29:
        print ('Your BMI is', BMI, 'so, you are overweight!')

    elif BMI >= 30 and BMI <= 39:
        print ('Your BMI is', BMI, 'so, you are obese!')

    elif BMI > 39:
        print ('Your BMI is', BMI, 'so, you are extremely obese!')

    elif BMI < 19:
        print ('Your BMI is', BMI, 'so, you are underweight!')

else:
    print ('There was an error with your input. Please restart the program!')
EN

回答 2

Code Review用户

发布于 2019-04-19 18:50:13

最好使用一个使用SI单元的函数--然后您可以将lbs转换为kgs,并将其转换为cm。此外,由于世界上大多数人要么使用帝国语,要么使用度量,所以我们可以使用布尔值来表示要使用哪一种:

代码语言:javascript
复制
def BMI(height,weight,is_metric):
    if (is_metric):
        # Height in meters, weight in kg
        return weight / height**2
    else:
        # Height in inches, weight in lbs
        height = height * 0.0254
        weight = weight * 0.453
        return BMI(height,weight,True)
票数 1
EN

Code Review用户

发布于 2019-04-19 20:08:02

您没有使用循环或函数,所以我想您还没有学习它们。

在大多数情况下,您的代码是干净的和可读的,所以让我建议您做一些修改。

首先,请参阅佩普-8。这是Python的编码标准(不管喜欢与否)。我在您的代码中遇到的许多问题将通过遵循该标准来解决:

  • 操作数和运算符之间的空间
  • snake_case名称

接下来,请注意Python有一个指数运算符,**可以用于计算。

您的评论是正确的,但没有增加任何价值。删除任何简单地用英语解释下一行在Python中做什么的注释。

最后,应用干燥的原则:不要重复自己!每个块中的if...elif...else语句是相同的,因为索引值是规范化的。将它们移到底部,在您的第一个if else (自由对度量单位)之后,并在错误情况下将索引设置为一些伪值。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/217751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档