1.小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
用if-elif
判断并打印结果:
height= input('height: ')
weight = input('weight: ')
w = float(weight)
h = float(height)
h1 = h/100
bim = w/(h1*h1)
print(bim)
if bim <= 18.5:
print('过轻')
elif 18.5 <= bim < 25:
print('正常')
elif 25 <= bim <28:
print("过重")
elif 28 <= bim < 32:
print("肥胖")
else:
print("超级牛")
2.练习
请定义一个函数quadratic(a, b, c)
,接收3个参数,返回一元二次方程 ax^2+bx+c=0ax2+bx+c=0 的两个解。
提示:
一元二次方程的求根公式为:
x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}x=2a−b±b2−4ac
计算平方根可以调用math.sqrt()
函数:
>>> import math
>>> math.sqrt(2)
1.4142135623730951
import math
def quadratic(a, b, c):
if not isinstance(a, (int, float)):
raise TypeError('bad operand type')
if not isinstance(b, (int, float)):
raise TypeError('bad operand type')
if not isinstance(c, (int, float)):
raise TypeError('bad operand type')
if b * b - 4 * a * c < 0:
print = ('此方程组无解')
return
if a == 0 and b == 0:
print = ('此方程组无解')
return
if a == 0 and b != 0:
x = -c / b
return x
if b * b - 4 * a * c >= 0:
x1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
x2 = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
return x1, x2
# 测试
print('quadratic(2,3,1)=', quadratic(2, 3, 1))
print('quadratic(1,3,-4)=', quadratic(1, 3, -4))
if quadratic(2, 3, 1) != (-0.5, -1.0):
print('测试失败')
if quadratic(1, 3, -4) != (1.0, -4.0):
print('测试失败')