Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

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.

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.