CodingNic

Functions

Functions Basics

Functions 15 min read

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:

python
def function_name():
    # code goes here, indented

The indentation isn’t optional. Skip it and Python raises an IndentationError. Calling a function uses parentheses:

python
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:

python
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:

python
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:

python
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:

python
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

  1. Write a function with no parameters that returns a fixed value, then call it.
  2. Write a function that uses print() instead of return, then check what calling it and storing the result actually gives you.
  3. Predict, then confirm, what a function with no return statement returns.

Recap

  • def name(): defines a function; the body must be indented, or you’ll get an IndentationError.
  • return sends a value back out of a function; without it, a function always returns None, no matter what it prints along the way.

Next lesson: giving functions dynamic input, with parameters and arguments.