Python 101Free
FUNCTIONS

Defining Functions

Wrapping a chunk of behavior behind a name.

SECTION 01

def, parameters, return

def introduces a new function. The parameter list inside the parentheses is the function's signature, the body is what it does, and return produces a value back to the caller.

Function definitions are statements, not declarations. They run at the point they appear and bind a function object to a name. That is why you can pass them around, reassign them, or define them inside other functions.

The distinction between parameters (the names in the signature) and arguments (the values passed in at the call site) is a useful one when you read other people's code. Same idea, two views: the signature is what the function expects, the call is what the caller actually sent.

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

add(3, 5)    # 8
SECTION 02

Multiple returns and None

A function can have many return statements. The first one that runs ends the function and produces the value. Different branches of an if chain can return different things, which is how you express "compute this and stop" in a single statement.

If a function ends without hitting any return, Python returns None implicitly. Functions that exist to do something (printing, mutating, logging) and not to compute a value usually fall into this category.

Beginners sometimes get caught when they call such a function and assign the result, expecting the printed value to come back. result = print("hi") sets result to None, because print does not return anything useful. The fix is to remember that printing and returning are different operations.

python
def label(n):
    if n > 0:
        return "positive"
    if n < 0:
        return "negative"
    # falls through, returns None implicitly

label(0)   # None
NEXT →
Arguments