6.5 Return values
Learning objectives
By the end of this section you should be able to
- Identify a function's return value.
- Employ return statements in functions to return values.
Returning from a function
When a function finishes, the function returns and provides a result to the calling code. A return statement finishes the function execution and can specify a value to return to the function's caller. Functions introduced so far have not had a return statement, which is the same as returning None, representing no value.
Using multiple return statements
Functions that have multiple execution paths may use multiple return statements. Ex: A function with an if-else statement may have two return statements for each branch. Return statements always end the function and return control flow to the calling code.
In the table below, calc_mpg takes in miles driven and gallons of gas used and calculates a car's miles per gallon. calc_mpg checks if gallons is 0 (to avoid division by 0), and if so, returns -1, a value often used to indicate a problem.
def calc_mpg(miles, gallons):
if gallons > 0:
mpg = miles/gallons
return mpg
else:
print("Gallons can't be 0")
return -1
car_1_mpg = calc_mpg(448, 16)
print("Car 1's mpg is", car_1_mpg)
car_2_mpg = calc_mpg(300, 0)
print("Car 2's mpg is", car_2_mpg)
|
Car 1's mpg is 28.0
Gallons can't be 0
Car 2's mpg is -1
|
Using functions as values
Functions are objects that evaluate to values, so function calls can be used in expressions. A function call can be combined with other function calls, variables, and literals as long as the return value is compatible with the operation.
Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.