减少退货单的数量

Moh*_*d H 3 boolean-logic boolean python-3.x

以下代码返回人员的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"
Run Code Online (Sandbox Code Playgroud)

小智 5

也许最好的,或者至少是最清晰的方式是通过使用带有保存风险的变量的多个if/ elif/ else:

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
Run Code Online (Sandbox Code Playgroud)

至少,这允许您risk在分配之后但在返回之前进行额外检查.


关于编程语言中的单个或多个返回,有一个非常主观的讨论 - 特别是像Python那样具有自动垃圾收集功能.

您的代码没有任何严重错误,多次返回允许在需要时提前返回.例如:

def my_function(argument1, argument2):
    if some_obvious_error_condition:
        return "ERR"

    # 100 lines of complex code

    return other_thing
Run Code Online (Sandbox Code Playgroud)