10. Functions

Functions

As programs grow, repeating the same lines in many places becomes error-prone. A function is a named, reusable block of code. You define it once and call it whenever you need it, often with different inputs. Functions make programs shorter, clearer, and easier to fix.

Defining and calling a function

Use the keyword def, a name, parentheses for any inputs, and a colon. The body is indented. Call the function by writing its name followed by parentheses:

PYTHON
def greet():
    print("Hello!")

greet()
greet()
▸ OUTPUT
Hello!
Hello!

Parameters and return values

The names in the parentheses are parameters; the values you pass in when calling are arguments. The return statement sends a value back to whoever called the function, so you can use the result:

PYTHON
def add(a, b):
    return a + b

total = add(3, 4)
print(total)
print(add(10, 20))
▸ OUTPUT
7
30

A function without a return statement automatically returns None. The difference between print and return matters: print only shows text on screen, while return gives a value your program can keep using.

a = 3, b = 4 add(a, b) return a + b 7 inputs return

Default and keyword arguments

A parameter can have a default value, used when the caller does not supply one. You may also pass arguments by name, which makes a call self-explanatory and lets you skip earlier optional values:

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

print(greet("Ada"))
print(greet("Max", "Welcome"))
print(greet(name="Sam", greeting="Hi"))
▸ OUTPUT
Hello, Ada!
Welcome, Max!
Hi, Sam!

Scope

Variables created inside a function are local: they exist only while the function runs and cannot be seen from outside. This keeps functions independent and prevents them from accidentally interfering with each other:

PYTHON
def compute():
    result = 42
    return result

print(compute())
# print(result)   # NameError: result is not defined here
▸ OUTPUT
42

Docstrings

A docstring is a string placed as the first line inside a function to describe what it does. Tools and the built-in help() function can read it, and it reminds future readers (including you) of the function's purpose:

PYTHON
def area(width, height):
    """Return the area of a rectangle."""
    return width * height

print(area(3, 5))
print(area.__doc__)
▸ OUTPUT
15
Return the area of a rectangle.

A gentle look at *args and **kwargs

Sometimes you want a function to accept any number of arguments. Writing *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary:

PYTHON
def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3))
print(total(10, 20, 30, 40))
▸ OUTPUT
6
100

You will not need these every day, but they power many flexible library functions. For now, remember the core idea: a function takes inputs, does work, and returns a result.

Functions are the main way programmers organise ideas. Practice by writing a function that takes a temperature in Celsius and returns it in Fahrenheit using the formula c * 9 / 5 + 32.