Python - Functions Basics

Overview

Estimated time: 35–45 minutes

Define functions, choose parameter styles, avoid mutable default pitfalls, and document with docstrings.

Learning Objectives

  • Define and call functions with positional and keyword arguments.
  • Use parameter kinds (positional-only, keyword-only, *args, **kwargs) appropriately.
  • Avoid mutable default arguments; write clear docstrings.

Prerequisites

Defining functions

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

print(add(2, 3))
print(add(a=2, b=3))

Expected Output: 5\n5

Defaults and pitfalls

def bad_append(x, items=[]):  # don't do this
    items.append(x)
    return items

print(bad_append(1))
print(bad_append(2))  # unexpected: shares list

# Correct approach
def good_append(x, items=None):
    if items is None:
        items = []
    items.append(x)
    return items

Expected Output (first two lines): [1]\n[1, 2]

Common Pitfalls

  • Mutable default arguments that persist across calls.
  • Overusing *args/**kwargs leading to unclear APIs.

Checks for Understanding

  1. How do you safely provide a list default parameter?
  2. What are two benefits of keyword arguments?
Show answers
  1. Use None as default and initialize inside the function.
  2. They improve readability and allow argument order flexibility.

Exercises

  1. Write a function with a keyword-only parameter and call it by name.
  2. Refactor a function to avoid using *args/**kwargs when not necessary.