Functions
14 min
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!
f-strings (starting with f before the quote) are the standard way to interpolate variables into text.
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.
Write a function `max_of_three(a, b, c)` that returns the largest of the three arguments.
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.)
What does a Python function return if it has no explicit `return` statement?
You can define functions with parameters, default arguments, and pass functions as values.