以下代码返回人员的BMI风险 - 低,中等或高。 它工作得很好。但是,我想知道是否有其他方法可以解决它而不使用太多的返回语句。
还有其他方式,Pythonic或逻辑上让它更短吗?
def bmi_risk(bmi, age):
''' function returning bmi's risk on human '''
if bmi < 22 and age < 45:
return "Low"
if bmi < 22 and age >= 45:
return "Medium"
if bmi >= 22 and age < 45:
return "Medium"
if bmi >= 22 and age >= 45:
return "High"
答案 0 :(得分:5)
也许最好的,或者至少是最清晰的方式是使用multiple if
/elif
/else
blocks来控制风险的变量:
def bmi_risk(bmi, age):
''' function returning bmi's risk on human '''
if bmi < 22 and age < 45:
risk = "Low"
elif bmi < 22 and age >= 45:
risk = "Medium"
elif bmi >= 22 and age < 45:
risk = "Medium"
elif bmi >= 22 and age >= 45:
risk = "High"
else:
risk = "Unknown"
return risk
至少,这允许您在分配之后但在返回之前对risk
进行额外检查。
在编程语言中有一个关于单个或多个返回的非常主观的讨论 - 特别是像Python那样具有自动垃圾收集的。
您的代码没有任何可怕的错误,并且多次返回允许在需要时提前返回。例如:
def my_function(argument1, argument2):
if some_obvious_error_condition:
return "ERR"
# 100 lines of complex code
return other_thing
答案 1 :(得分:4)
只有3种选择。如果它不低或高,那么它必须是中等的。因此,在检查低和高后,您可以返回中等:
def bmi_risk(bmi, age):
''' function returning bmi's risk on human '''
if bmi < 22 and age < 45:
return "Low"
if bmi >= 22 and age >= 45:
return "High"
return "Medium"
不太可读但更紧凑的形式是使用表格并根据条件计算其中的索引,该条件代表风险因素的总和:
def bmi_risk(bmi, age, risktable=["Low", "Medium", "High"]):
return risktable[(1 if (bmi >= 22) else 0) + (1 if (age >= 45) else 0)]
或者(感谢@ZeroPiraeus):
def bmi_risk(bmi, age, risktable=["Low", "Medium", "High"]):
return risktable[(bmi >= 22) + (age >= 45)]
答案 2 :(得分:0)
另一种使用字典的方法,
age = 45
bmi = 22
age1 = int(input("Age:"))
bmi1 = int(input("BMI:"))
test1 = {(age1 < age and bmi1 < bmi) : "Low",
(age1 >= age and bmi1 < bmi) : "Medium",
(age1 < age and bmi1 >= bmi) : "Medium1",
(age1 >= age and bmi1 >= bmi) : "High", }
if True in test1:
print(test1[True])
else:
print("Unknown")
Age:22
BMI:44
Medium1
[Program finished]