TutreNews Learn

Functions and errors

Defining functions

Goal: Write functions with parameters and return values · 10 min

A function packages code under a name so you can reuse it:

def area(width, height):
    return width * height

width and height are parameters; when calling area(3, 4) the arguments 3 and 4 are passed in. return sends a value back to the caller and ends the function.

A function without return returns None. print vs. return: print shows a value on screen; return hands it back so the program can keep working with it.

Worked example: Reusing a function

  1. Define celsius → fahrenheit once.
  2. Call it for several values.
  3. Output: 32.0 212.0
def to_f(c):
    return c * 9 / 5 + 32

print(to_f(0), to_f(100))

Output:

32.0 212.0