Code of the Day
BeginnerCore syntax

Functions

Package logic into named, reusable pieces with parameters, return values, and defaults.

PythonBeginner9 min read
Recommended first
By the end of this lesson you will be able to:
  • Define a function with def, parameters, and a return value
  • Use default and keyword arguments
  • Explain the difference between returning and printing

A function is the unit of decomposition (the fundamentals lesson) made concrete: a named, reusable piece of logic with inputs and an output. Python's syntax for them is clean and worth getting exactly right early.

Defining and calling

def defines a function; return hands a value back to the caller:

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

total = add(2, 3)   # total is 5

The parameters a and b are names that exist only inside the function. Calling add(2, 3) binds them to 2 and 3, runs the body, and the call evaluates to whatever you return.

Return vs print

A common beginner mix-up: print shows a value on screen; return gives it back to your program to use. A function that prints but doesn't return gives you if you try to use its result.

Python — editable, runs in your browser

Default and keyword arguments

Parameters can have defaults, making them optional, and callers can pass arguments by name for clarity:

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

greet("Ada")                      # "Hello, Ada!"
greet("Ada", greeting="Hi")       # "Hi, Ada!"  (keyword argument)

Defaults let one function serve many cases; keyword arguments make calls self-documenting at the call site.

Don't use a mutable value (like [] or {}) as a default argument — it's created once and shared across calls, a classic Python gotcha. Use None and create the list inside the function instead.

Where to go next

Functions let you name and reuse logic. Next: strings — working with text, which you'll do constantly.

Finished reading? Mark it complete to track your progress.

On this page