定义一个类People,属性有name、age、weight、height。定义成员方法judeg_BMI(self),使得可以计算该实例的BMI值。已知BMI = weight / (height *height),其中height的单位为米。BMI < 18.5体重为过轻,BMI > 18.5 且 BMI < 24.9体重为正常范围,BMI >= 24.9且BMI < 29.9体重为超重,BMI >=29.9体重为肥胖。要求设计一个程序可以在控制台输入姓名、年龄、体重、身高(米),然后输出BMI并且给出合理建议。 Python代码
时间: 2024-03-12 19:50:06 浏览: 68
python定义一个people类 基于python语言实现opencv自带svm检测行人.zip
以下是符合要求的Python程序代码:
```python
class People:
def __init__(self, name, age, weight, height):
self.name = name
self.age = age
self.weight = weight
self.height = height
def judge_BMI(self):
BMI = self.weight / (self.height ** 2)
if BMI < 18.5:
suggestion = "过轻"
elif BMI >= 18.5 and BMI < 24.9:
suggestion = "正常范围"
elif BMI >= 24.9 and BMI < 29.9:
suggestion = "超重"
else:
suggestion = "肥胖"
print("{0}的BMI值为{1},属于{2},需要{3}。".format(self.name, round(BMI, 2), suggestion, "增加锻炼量" if suggestion != "正常范围" else "继续保持"))
name = input("请输入姓名:")
age = input("请输入年龄:")
weight = float(input("请输入体重(kg):"))
height = float(input("请输入身高(m):"))
person = People(name, age, weight, height)
person.judge_BMI()
```
程序运行后,会提示输入姓名、年龄、体重、身高,然后会自动计算BMI并给出合理建议。
阅读全文