Lesson 8 / 1173%

Lesson 8

Functions

25 min

def, parameters, return and variable scope: organize and reuse your code.

Definition

A function is a named andreusable block of code that performs a specific task. It can receive information as input (the parameters) and return a result as output (withreturn). You create it with thedefkeyword and run it by writing its name followed by parentheses, for examplecalculate(5).

Why write functions?

A function is a named block of code that you can call as many times as needed. It avoids copy-pasting the same code, and makes the program more readable and easier to fix. You already use some:print(),input()andlen()are functions provided by Python.

Writing your own functions means breaking a big problem down into small, simple steps, each with a clear name. If an error is hiding in a calculation, you fix it in a single place instead of hunting for it throughout the whole program.

Defining and calling a function

You define a function with thedefkeyword, followed by its name, parentheses and a colon. The body of the function is indented. Defining a function doesn’t run it: the code only runs when you call it by name.

simple_function.py
def say_hello():
    print("Hello!")
    print("Welcome to this program.")

say_hello()
say_hello()
Screenshot: a terminal showing the result of running the simple_function.py script, with the two messages displayed twice.

Parameters

Parameters are variables placed between the parentheses: they let you pass information to the function when you call it. The values you pass are called arguments.

parameters.py
def greet(first_name, city):
    print(f"Hello {first_name}, welcome to {city}!")

greet("Léa", "Lyon")
greet("Tom", "Lille")

By default, arguments are matched to parameters in order. You can also name them when calling, which makes the code more readable and lets you give them in any order.

named_arguments.py
def introduce(first_name, age):
    print(f"{first_name} is {age} years old.")

introduce("Léa", 25)                   # positional arguments
introduce(age=30, first_name="Tom")    # named arguments, any order

Returning a value with return

A function can return a result withreturn. You can then store this result in a variable. As soon as Python encountersreturn, the function stops: any lines written after it are never run.

return.py
def add(a, b):
    return a + b

result = add(4, 7)
print(result)               # 11
print(add(10, 5) * 2)       # 30

A function can even return several values at once, by separating them with commas (Python actually returns them grouped in a tuple). You then retrieve them in as many variables.

return_multiple.py
def min_and_max(a, b):
    if a < b:
        return a, b
    return b, a

smaller, larger = min_and_max(9, 3)
print(smaller, larger)   # 3 9

print() or return?

print()displays a value on the screen but doesn’t make it reusable.returnhands the value back to the code that called the function. As a general rule, a function calculates and returns, and it’s the main program that displays.

Default values

A parameter can have a default value, used when no argument is provided. Parameters with a default value always go after those without one.

defaults.py
def price_with_tax(price_before_tax, tax=0.20):
    return price_before_tax * (1 + tax)

print(price_with_tax(100))          # 120.0
print(price_with_tax(100, 0.055))   # 105.5

Variable scope

A variable created inside a function is local: it only exists while that function is running. It is invisible outside. Conversely, a variable created outside any function is global: it can be read from within a function, but it’s better to pass values through parameters.

scope.py
def calculate():
    result = 42
    print(result)

calculate()
print(result)   # NameError: result doesn't exist here

Documenting a function

You can describe what a function does with a docstring: a text between triple quotation marks placed right below thedefline. It serves as an instruction manual for other developers, and for you in a few weeks.

docstring.py
def rectangle_area(length, width):
    """Returns the area of a rectangle from its two sides."""
    return length * width

print(rectangle_area(5, 3))   # 15

Best practices

  • Give your functions names that express an action(calculate_total,is_even).
  • A function should do one single thing: if you struggle to name it, it may be doing too much.
  • Use snake_case names, as for variables.
  • Prefer passing values through parameters rather than depending on outside variables.
Screenshot: a terminal showing the result of running the docstring.py script, with the result displayed.

Common errors

  • Forgetting the parentheses when calling: writingsay_hellowithout()doesn’t run the function.
  • Wrong number of arguments: callingadd(4)when the function expects two values causes aTypeError.
  • Forgetting the return: withoutreturn, the function returnsNoneand the result is lost.
  • Using a local variable outside: it no longer exists once the function has finished.

Exercise

Write a functionis_even(number)that returnsTrueif the number is even andFalseotherwise, then test it with several values. Add a docstring that explains what it does.

Going further

Write a functionconvert(celsius)that returns the temperature in Fahrenheit (formula: C x 9/5 + 32), then use it in a loop to display the conversion from 0 to 100 degrees in steps of 10. Add a parameter with a default value to choose the number of decimals displayed.