下面这段代码计算用户的Body Mass Index。有一个函数在用户提供了他或她的体重(kg)和身高(m)之后执行计算。还会打印一条包含用户BMI值的消息。
代码还包括一些异常处理,以避免出现错误。例如,如果提供的是字符串而不是数字,或者如果提供的是极值(例如高度大于2.40m),则会打印一条特殊消息(例如,“请正确输入您的身高!)。
def find_bmi(weight,height):
my_bmi=weight/height**2
return my_bmi
try:
weight=float(input("What is your weight (kg)?"))
if weight < 200:
height=float(input("What is your height (m)?"))
try:
if height < 2.40:
print("Your BMI is: "+str(round(find_bmi(weight,height),2))+"!!!")
else:
print("Please enter your height correctly!")
except ValueError:
print("Enter a number please!")
else:
print("Please enter your weight correctly")
except ValueError:
print("Enter a number please!")有没有更具Pythonic风格的方式来写这篇文章呢?有没有什么东西可以用更好的方式写出来呢?请记住,我最近开始学习Python!
发布于 2021-03-21 04:08:13
def find_bmi(weight, height):
return weight/(height**2)
def prompt():
try:
weight, height = [float(a) for a in input("Enter space separated
weight(kg) and height(m), weight height\n").split()]
return weight, height
except ValueError:
raise Exception("Enter a number please!")
def range_error(weight, height):
raise Exception("height out of range") if height >= 2.40 else null
raise Exception("weight out of range") if weight >= 200 else null
weight, height = prompt()
range_error(weight,height) if (height >=2.40 or weight >=200) else print("Your BMI is: "+str(round(find_bmi(weight,height),2))+"!!!")https://stackoverflow.com/questions/66725484
复制相似问题