作为我的第一个Python程序,我编写了一个简单的BMI计算器。我想知道怎样才能改进这个计划。功能有用吗?我怎样才能改进它的呈现方式?
#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!')发布于 2019-04-19 18:50:13
最好使用一个使用SI单元的函数--然后您可以将lbs转换为kgs,并将其转换为cm。此外,由于世界上大多数人要么使用帝国语,要么使用度量,所以我们可以使用布尔值来表示要使用哪一种:
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)发布于 2019-04-19 20:08:02
您没有使用循环或函数,所以我想您还没有学习它们。
在大多数情况下,您的代码是干净的和可读的,所以让我建议您做一些修改。
首先,请参阅佩普-8。这是Python的编码标准(不管喜欢与否)。我在您的代码中遇到的许多问题将通过遵循该标准来解决:
snake_case名称接下来,请注意Python有一个指数运算符,**可以用于计算。
您的评论是正确的,但没有增加任何价值。删除任何简单地用英语解释下一行在Python中做什么的注释。
最后,应用干燥的原则:不要重复自己!每个块中的if...elif...else语句是相同的,因为索引值是规范化的。将它们移到底部,在您的第一个if else (自由对度量单位)之后,并在错误情况下将索引设置为一些伪值。
https://codereview.stackexchange.com/questions/217751
复制相似问题