3、 定义一个匿名函数,他的功能是计算BMI。BMI公式为BMI=体重/(身高*身高),体重的单位为kg,身高单位为m。传入体重50,身高1.65.编写程序判断,如果BMI小于18.5,则格式化输出“你的BMI为(),体重过轻。
时间: 2024-05-02 13:22:17 浏览: 18
如果BMI在18.5到24之间,则输出“你的BMI为(),体重正常。如果BMI大于24,则输出“你的BMI为(),体重过重。
代码如下:
```python
bmi = lambda weight, height: weight / (height * height)
w = 50
h = 1.65
result = bmi(w, h)
if result < 18.5:
print("你的BMI为 {:.2f},体重过轻。".format(result))
elif result >= 18.5 and result <= 24:
print("你的BMI为 {:.2f},体重正常。".format(result))
else:
print("你的BMI为 {:.2f},体重过重。".format(result))
```
输出结果为:
```
你的BMI为 18.37,体重过轻。
```
相关问题
python定义一个函数gcd,功能是求两个正整数的最小公倍数;
您好,下面是Python实现求两个正整数的最小公倍数的gcd函数:
```python
def gcd(a, b):
# 先求出a、b的最大公约数
if a < b:
a, b = b, a
while b != 0:
temp = a % b
a = b
b = temp
# 两个数的乘积等于它们的最大公约数与最小公倍数的积
return int(a * (a / gcd))
```
其中,我们可以利用辗转相除法求出a、b的最大公约数,然后利用公式计算最小公倍数。
编写程序完成以下功能: (1)编写函数writeFile(),其功能是打开一个文件,文件名称为“data.txt”,将考生本人的学号姓名和文字“健康状况判断!”写入文件中n次。 (2)编写函数,其功能是:根据BMI值判断身体状况,函数名称和参数为: judgeHealth(bmi)。bmi为身体质量指数。 BMI计算公式为:BMI = weight / (height*height) 根据BMI判断身体状况的标准: 身体状况 BMI值 偏瘦 <18.5 正常 [18.5, 24) 偏胖 [24, 28) 肥胖 >=28 (3)编写函数,其功能是:输出p_list列表中所有人的姓名、身高、体重、身体状况。函数名称和参数为:printResult(p_list)。 (4)下面列表中存放了所有人的姓名、身高、体重,调用writeFile函数写入100次对应信息;调用printResult函数输出所有人的姓名、身高、体重、身体状况;编写程序统计身体状况为正常的人数。
以下是Python的程序代码实现:
```python
import random
class Person:
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
self.bmi = weight / (height * height)
def writeFile(n):
with open("data.txt", "w") as f:
for i in range(n):
f.write("学号:xxx 姓名:xxx 健康状况判断!\n")
def judgeHealth(bmi):
if bmi < 18.5:
return "偏瘦"
elif bmi < 24:
return "正常"
elif bmi < 28:
return "偏胖"
else:
return "肥胖"
def printResult(p_list):
for p in p_list:
print("姓名:{} 身高:{}m 体重:{}kg 身体状况:{}".format(p.name, p.height, p.weight, judgeHealth(p.bmi)))
p_list = [
Person("张三", 1.75, 70),
Person("李四", 1.68, 65),
Person("王五", 1.8, 75),
Person("赵六", 1.6, 55),
Person("钱七", 1.85, 80)
]
writeFile(100)
printResult(p_list)
normal_count = 0
for p in p_list:
if judgeHealth(p.bmi) == "正常":
normal_count += 1
print("身体状况为正常的人数为:{}".format(normal_count))
```
注意:这里随机生成了五个人的身高和体重,其它人的信息是填充不完整的,需要自己根据实际情况填充。