Python: Functions
What you will learn
How to define a reusable block of code, pass arguments, return values, and use default parameters.
Defining and calling a function
def greet(name):
"""Return a greeting string."""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
Functions are defined with def, followed by the name, parentheses for parameters, and a colon. The body is indented. The optional return sends a value back where the function was called.
Default arguments
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (exponent defaults to 2)
print(power(3, 3)) # 27
Parameters with defaults must come after parameters without defaults.
Multiple return values
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([1, 5, 2, 8])
print(lo, hi) # 1 8
Python packs multiple values into a tuple automatically.
Common mistakes
- Mutable default arguments (
def f(x=[])) are shared across calls. UseNoneand create a new list inside instead. - Forgetting the colon or mis-indenting the body.
Quick check below!