🌱BeginnerControl Flow

Functions

Defining reusable blocks of code with def, parameters, return values, and default arguments.

Overview

A function is a named, reusable block of code that performs a specific task. Functions are the primary tool for avoiding repetition (the DRY principle Don't Repeat Yourself) and for breaking complex programs into smaller, manageable pieces. In Python, functions are defined with the def keyword, followed by the function name, parentheses containing any parameters, and a colon. The function body is indented. A return statement sends a value back to the caller; without it (or with a bare return), the function returns None. Python functions support several parameter types: required positional parameters, default parameters (which have a fallback value), *args for variable-length positional arguments, and **kwargs for variable-length keyword arguments. You'll also encounter keyword arguments when calling functions, which make code more readable.

Key Points

  • •Define with `def name(params):` followed by an indented body
  • •return sends a value back; functions without return (or bare return) return None
  • •Default parameters: `def greet(name, greeting="Hello"):` optional when calling
  • •Calling with keyword arguments: `greet(name="Alice", greeting="Hi")` order doesn't matter
  • •Functions are first-class objects assignable to variables, passable as arguments
  • •Docstrings: the first string literal in a function body documents what it does
  • •Local variables inside a function don't affect variables outside (scope isolation)

Examples

Basic function with parameters and return value

def add(a, b):
    """Return the sum of a and b."""
    return a + b

result = add(3, 5)
print(result)         # 8
print(add(10, -2))    # 8

Default parameters and keyword arguments

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

print(greet("Alice"))                       # Hello, Alice!
print(greet("Bob", greeting="Hi"))          # Hi, Bob!
print(greet("Carol", punctuation="."))      # Hello, Carol.
print(greet("Dave", "Hey", "?"))            # Hey, Dave?

Functions returning multiple values and None

def min_max(numbers):
    """Return (minimum, maximum) of a list."""
    return min(numbers), max(numbers)

lo, hi = min_max([3, 1, 4, 1, 5, 9, 2, 6])
print(f"min={lo}, max={hi}")    # min=1, max=9

def log_message(msg):
    print(f"[LOG] {msg}")       # no return statement → returns None

result = log_message("test")
print(result)                   # None

Common Mistakes

  • Forgetting parentheses when calling a function: `print` refers to the function object, `print()` calls it
  • Mutable default arguments: `def fn(lst=[])` is a famous Python trap the default list is shared across calls. Use `def fn(lst=None): if lst is None: lst = []` instead
  • Mixing up parameter order: positional arguments must come before keyword arguments in a call

Note

Write a docstring for every function you define. Even a one-liner helps: `"""Calculate and return the area of a circle."""` Python's built-in help() reads these docstrings.

Exercises

Write Python code to solve each exercise. Run it in your browser and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

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