Reducing the number of applications returned

The following code returns a person's risk of BMI - either low, medium, or high. It works great. However, I was wondering if there is another way to solve the problem without using too many return operators.

Is there any other way, either Pythonic or logically, to make it shorter?

def bmi_risk(bmi, age):
    ''' function returning bmi 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"

      

+3


source to share


2 answers


Perhaps the best, or at least the clearest way is to use multiple if

/ elif

/ blockselse

with a variable holding the risk:

def bmi_risk(bmi, age):
    ''' function returning bmi 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

      

At the very least, it allows for additional checks risk

after its assignment, but before returning.




There is a very subjective debate regarding single or multiple returns in programming languages, especially Python, which has automatic garbage collection.

There is nothing wrong with your code, and multiple returns allow early return when needed. For example:

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

    # 100 lines of complex code

    return other_thing

      

+4


source


There are only 3 options. If it's not short or tall, it should be medium. So after checking for low and high, you can simply return the environment:

def bmi_risk(bmi, age):
    ''' function returning bmi risk on human '''
    if bmi < 22 and age < 45:
        return "Low"
    if bmi >= 22 and age >= 45:
        return "High"
    return "Medium"

      

A less readable but more compact form is to use a table and calculate an index on it based on conditions that are the sum of the risk factors:



def bmi_risk(bmi, age, risktable=["Low", "Medium", "High"]):
    return risktable[(1 if (bmi >= 22) else 0) + (1 if (age >= 45) else 0)]

      

Alternatively (thanks @ZeroPiraeus):

def bmi_risk(bmi, age, risktable=["Low", "Medium", "High"]):
    return risktable[(bmi >= 22) + (age >= 45)]

      

+4


source







All Articles