Functions Basics
Objectives
By the end of this chapter, you should be able to:
- Explain the value and purpose of a function
- Return output from a function
💡 Why this matters: Functions are how you turn a one-off piece of code into something you can run again, with different input, whenever you need it.
What Is a Function?
A function is a repeatable process. A real-world analogy is the brew button on a coffee machine: it takes inputs (water, coffee grounds) and produces an output (coffee) every time you press it. A Python function works the same way: it takes in some input and returns some output.
You’ve already used plenty of functions. List methods like .append() are functions built into Python. You can also write your own:
def function_name():
# code goes here, indented
The indentation isn’t optional. Skip it and Python raises an IndentationError. Calling a function uses parentheses:
def first_function():
print("Hello World!")
first_function() # Hello World!
Getting Output with return
Here’s a function that’s supposed to add two numbers:
def add_five_plus_five():
5 + 5
Calling add_five_plus_five() produces nothing. That’s because the function never sends anything back out: it just computes 5 + 5 and discards it. return is what actually hands a value back to whoever called the function:
def add_five_plus_five():
return 5 + 5
add_five_plus_five() # 10
Since it returns a value now, you can save it and use it later:
ten = add_five_plus_five()
print(ten + 10) # 20
No return Means None
A function with no return statement always gives back None, even if it prints something along the way:
def print_five_plus_five():
print(5 + 5)
def add_five_plus_five():
return 5 + 5
ten = add_five_plus_five()
maybe_ten = print_five_plus_five() # prints 10 to the console
ten # 10
maybe_ten # None
print_five_plus_five displays 10, but it doesn’t return anything. Those are two different things.
Try It
- Write a function with no parameters that returns a fixed value, then call it.
- Write a function that uses
print()instead ofreturn, then check what calling it and storing the result actually gives you. - Predict, then confirm, what a function with no
returnstatement returns.
Recap
def name():defines a function; the body must be indented, or you’ll get anIndentationError.returnsends a value back out of a function; without it, a function always returnsNone, no matter what it prints along the way.
Next lesson: giving functions dynamic input, with parameters and arguments.