PYTHON / CHAPTER 05
Functions that return an answer
BeginnerGive a reusable calculation a name, inputs, and a returned result.
By the end of this chapter
- Define a function with def
- Pass arguments to parameters
- Reuse a returned result instead of only printing
The idea
A function gives a reusable operation a name. def starts the definition, parentheses list the input parameters, and an indented body contains the work. Defining the function does not run its body; calling the function with arguments runs it with those input values.
return sends a result back to the caller and ends that function call. The caller can save the result, use it in another expression, or print it. print displays something for a person; it does not replace returning the value another calculation needs.
Begin with a small function that uses only its parameters. Test two different calls and an edge case such as a quantity of zero. Local parameter names are filled separately for each call. Lists and default parameters introduce additional state rules; those come later in Functions and dependable defaults.
def line_total(price, quantity):
return price * quantity
first = line_total(4, 3)
second = line_total(4, 0)
print(first)
print(second)12 0
Each call supplies its own arguments. The function returns a number, and printing is the caller’s separate choice.
Try it yourself
Define a function that takes a number of minutes and returns seconds. Save the result of two different calls before printing them.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open Python coding challengesCHECK YOUR UNDERSTANDING