Latticework

Command Palette

Search for a command to run...

Python

Functions

14 min

Explanation

A function is defined with def, a name, and parentheses holding its parameters. return sends a value back to the caller — without it, the function returns None.

def greet(name):
    return f"Hello, {name}!"

print(greet("World"))  # Hello, World!
Try it

f-strings (starting with f before the quote) are the standard way to interpolate variables into text.

Loading editor…
Explanation

Parameters can have default values, and can be passed by keyword:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Ada")                    # "Hello, Ada!"
greet("Ada", greeting="Hi")     # "Hi, Ada!"

Functions are also values in Python — you can pass one function as an argument to another. That's the idea behind the next exercise.

Exercise

Write a function `max_of_three(a, b, c)` that returns the largest of the three arguments.

Exercise

Write a function `apply_twice(f, x)` that calls the function f on x, then calls f again on the result, and returns that final value. (This is your first taste of higher-order functions — functions that take other functions as arguments.)

Quiz

What does a Python function return if it has no explicit `return` statement?

Checkpoint

You can define functions with parameters, default arguments, and pass functions as values.