python 3.x - Reducing the amount of return statements -
the following code returns bmi risk of person - either low, medium or high. works fine. however, wondering if there way solve without using many return statements.
is there other way, either, pythonic or logically make shorter?
def bmi_risk(bmi, age): ''' function returning bmi's risk on human ''' if bmi < 22 , age < 45: return "low" if bmi < 22 , age >= 45: return "medium" if bmi >= 22 , age < 45: return "medium" if bmi >= 22 , age >= 45: return "high"
perhaps best, or @ least clearest, way through use of multiple if
/elif
/else
blocks variable holding risk:
def bmi_risk(bmi, age): ''' function returning bmi's risk on human ''' if bmi < 22 , age < 45: risk = "low" elif bmi < 22 , age >= 45: risk = "medium" elif bmi >= 22 , age < 45: risk = "medium" elif bmi >= 22 , age >= 45: risk = "high" else: risk = "unknown" return risk
at least, allows checks on risk
after assigning before returning.
there subjective discussion had single or multiple returns in programming languages - ones python have automatic garbage collection.
there isn't terrible wrong code, , multiple returns allow return when needed. example:
def my_function(argument1, argument2): if some_obvious_error_condition: return "err" # 100 lines of complex code return other_thing