Ch 07Functions and Code Organisation
Chapter 07 of 08·20 min

Functions and Code Organisation

As software grows in complexity, writing code as one continuous monolithic script becomes unmaintainable. Professional software architecture relies on decomposition: breaking complex workflows into small, isolated, testable, and reusable blocks called Functions. In this chapter, you will master function engineering: parameter passing, positional vs keyword arguments, the critical mutable default argument trap, return value contracts, local vs global scope, type annotations, and docstrings.

Learning objectives
  • 01Define modular functions using the def statement and encapsulate complex logic into testable units
  • 02Differentiate positional parameters, keyword arguments, and default parameters
  • 03Return single and multiple values using tuple unpacking, and distinguish printing from returning data
  • 04Navigate variable scope (Local, Enclosing, Global, Built-in - LEGB) and resolve UnboundLocalError exceptions
  • 05Avoid the notorious 'Mutable Default Argument Trap' using None sentinel defaults
  • 06Document software using modern PEP 484 type annotations and descriptive docstrings

7.1 Defining Functions with def: The Reusable Block

A **Function** is a named, self-contained block of instructions that performs a single well-defined task. ### The Anatomy of a Python Function: ```python def function_name(parameter_1, parameter_2): """Docstring explaining what the function does.""" # Function body (indented by 4 spaces) result = parameter_1 + parameter_2 return result ``` ### Core Engineering Benefits: 1. **DRY Principle (Don't Repeat Yourself)**: Eliminate duplicate logic across your codebase. 2. **Modularity & Testing**: Test and verify individual units of logic in complete isolation. 3. **Abstraction**: Callers only need to know what inputs the function expects and what output it produces, without needing to know internal implementation details.
Statement 1: Defining and Calling a Reusable Function

Encapsulating string normalization and keyword scoring logic.

# Defining a reusable sanitization function
def sanitize_email_text(raw_text):
    """Strips leading/trailing whitespace and converts text to lowercase."""
    cleaned = raw_text.strip().lower()
    return cleaned

# Calling the function multiple times with different inputs
email_1 = "   URGENT: Verify Credentials!  \n"
email_2 = "   Meeting Agenda for Thursday  "

print("Sanitized 1:", sanitize_email_text(email_1))
print("Sanitized 2:", sanitize_email_text(email_2))
Execution walkthrough
  1. 1.Lines 2-5: Compiles the function sanitize_email_text with parameter raw_text.
  2. 2.Line 11: Calls sanitize_email_text(email_1); raw_text receives email_1.
  3. 3.Line 4: Executes .strip().lower() and returns 'urgent: verify credentials!'.
  4. 4.Line 12: Calls sanitize_email_text(email_2), producing 'meeting agenda for thursday'.
Expected output
Sanitized 1: urgent: verify credentials!
Sanitized 2: meeting agenda for thursday
Edge cases

• Calling without parentheses: Writing `func = sanitize_email_text` does NOT execute the function! It merely binds another variable to the function object itself. You must include parentheses: `sanitize_email_text(...)` to execute. • Calling before definition: Calling a function on line 1 before its `def` statement on line 10 raises `NameError: name 'func' is not defined`. Python parses from top to bottom.

Why it happens: Calling a function allocates a new frame on Python's call stack, which is destroyed upon returning.

7.2 Parameters vs Arguments: Positional, Keyword & Defaults

It is important to distinguish vocabulary: - **Parameters**: The variable names listed in the function definition header. - **Arguments**: The actual data values passed into the function when invoking it. ### Types of Arguments: - **Positional Arguments**: Mapped strictly by order from left to right. - **Keyword Arguments**: Passed explicitly by parameter name (`func(rate=0.08, balance=1000)`), allowing arguments to be passed in any order. - **Default Parameters**: Parameters with pre-assigned fallback values (`def f(x, threshold=50):`). If the caller omits that argument, the default value is used automatically.
Statement 2: Positional, Keyword, and Default Parameters

Configuring default thresholds and calling with positional vs keyword arguments.

# Function with positional and default parameters
def calculate_threat_score(matched_count, weight_per_match=25, base_score=10):
    """Calculates total risk score with configurable weights and base bias."""
    total_score = base_score + (matched_count * weight_per_match)
    return total_score

# 1. Positional call (uses defaults for weight and base)
score_1 = calculate_threat_score(3)
print("Default call (3 matches)          :", score_1)  # 10 + (3 * 25) = 85

# 2. Overriding default parameter positionally
score_2 = calculate_threat_score(3, 15)             # 10 + (3 * 15) = 55
print("Custom weight (3 matches @ 15pts) :", score_2)

# 3. Explicit keyword call (order does not matter)
score_3 = calculate_threat_score(base_score=0, matched_count=2, weight_per_match=30)
print("Keyword call (custom base 0)      :", score_3)  # 0 + (2 * 30) = 60
Execution walkthrough
  1. 1.Line 2: Defines matched_count (mandatory), weight_per_match (default 25), base_score (default 10).
  2. 2.Line 8: Calls with only matched_count=3. Defaults 25 and 10 are applied automatically.
  3. 3.Line 16: Calls using explicit keyword arguments; order can vary freely.
Expected output
Default call (3 matches)          : 85
Custom weight (3 matches @ 15pts) : 55
Keyword call (custom base 0)      : 60
Edge cases

• Non-default parameters after default parameters: Writing `def f(a=10, b):` is illegal and raises `SyntaxError: non-default argument 'b' follows default argument`. All mandatory parameters must appear BEFORE any default parameters. • Positional argument after keyword argument: Calling `f(a=1, 2)` raises `SyntaxError: positional argument follows keyword argument`.

Why it happens: Python binds positional arguments first, then resolves keyword arguments by parameter dictionary lookup.

7.3 The Critical 'Mutable Default Argument Trap'

This is the **single most notorious bug in Python programming**. In Python, **default parameter values are evaluated once when the function is defined**, NOT every time the function is called! If you use a **mutable object** (like a `list` or `dict`) as a default parameter: ```python # DANGEROUS ANTI-PATTERN! def add_indicator(word, indicator_list=[]): indicator_list.append(word) return indicator_list ``` The same `indicator_list` is shared across EVERY call to `add_indicator()`! Calling `add_indicator('urgent')` followed by `add_indicator('free')` will append both into the same list! ### The Senior Python Solution (None Sentinel): Always use `None` as the default value for mutable parameters, and instantiate a new list inside the function body: ```python def add_indicator(word, indicator_list=None): if indicator_list is None: indicator_list = [] # Fresh list allocated every call! indicator_list.append(word) return indicator_list ```
Statement 3: Demonstrating and Fixing the Mutable Default Trap

Contrasting the buggy shared mutable default against the Pythonic None sentinel pattern.

# THE DANGEROUS TRAP (Shared state bug)
def buggy_collector(item, storage=[]):
    storage.append(item)
    return storage

print("Buggy call 1:", buggy_collector("A"))
print("Buggy call 2:", buggy_collector("B"))  # Unintentionally retains 'A'!

# THE PYTHONIC FIX (None Sentinel Pattern)
def safe_collector(item, storage=None):
    if storage is None:
        storage = []  # Brand new list created in local scope!
    storage.append(item)
    return storage

print("\nSafe call 1 :", safe_collector("A"))
print("Safe call 2 :", safe_collector("B"))  # Clean, independent list!
Execution walkthrough
  1. 1.Line 2: buggy_collector binds storage=[] at definition time.
  2. 2.Line 6: Appends 'A' -> ['A'].
  3. 3.Line 7: Reuses the SAME storage list and appends 'B' -> ['A', 'B']!
  4. 4.Line 11: safe_collector uses storage=None.
  5. 5.Lines 18-19: Each call allocates a fresh, independent list.
Expected output
Buggy call 1: ['A']
Buggy call 2: ['A', 'B']

Safe call 1 : ['A']
Safe call 2 : ['B']
Edge cases

• This applies to ALL mutable types: lists `[]`, dictionaries `{}`, and sets `set()`. Never use any mutable object as a default parameter value in Python.

Why it happens: Default parameters are stored on the function object's __defaults__ tuple, which is mutable if containing a list.

7.4 The return Statement: Outputs vs Printing

Beginners often confuse `print()` with `return`: - **`print()`** is a side-effect: it displays text on the terminal screen for human eyes. It produces no data that other code can use. - **`return`** sends computational data **back to the caller** so it can be stored in a variable, passed to another function, or used in mathematical formulas. ### Multiple Return Values (Tuple Unpacking): Python natively supports returning multiple values in a single `return` statement: `return min_val, max_val, avg`. Under the hood, Python packs them into a tuple, which the caller can unpack directly: `low, high, mean = compute_stats(data)`. *If a function finishes without encountering an explicit `return`, it implicitly returns `None`.*
Statement 4: Returning Multiple Values with Tuple Unpacking

Returning and capturing summary metrics from a single function call.

def analyze_score_stream(scores):
    """Computes minimum, maximum, and average across a score sequence."""
    if not scores:
        return 0, 0, 0.0
    
    min_val = min(scores)
    max_val = max(scores)
    avg_val = sum(scores) / len(scores)
    return min_val, max_val, avg_val  # Packed as a tuple

# Unpacking the returned tuple into 3 distinct variables
stream = [45, 88, 12, 94, 62, 77]
lowest, highest, average = analyze_score_stream(stream)

print(f"Lowest Risk  : {lowest}")
print(f"Highest Risk : {highest}")
print(f"Average Risk : {average:.1f}")
Execution walkthrough
  1. 1.Lines 6-8: Calculates min=12, max=94, average=63.0.
  2. 2.Line 9: Returns (12, 94, 63.0).
  3. 3.Line 13: Unpacks tuple into lowest=12, highest=94, average=63.0.
Expected output
Lowest Risk  : 12
Highest Risk : 94
Average Risk : 63.0
Edge cases

• Unpacking Count Mismatch: If a function returns 3 values but you write `a, b = func()`, Python crashes with `ValueError: too many values to unpack (expected 2)`. • Accidental None: If you write a function with only `print(...)` and assign its result: `res = my_func()`, `res` is `None`! `print()` returns `None`.

Why it happens: Python's tuple unpacking syntax allows clean multiple return values without needing custom container objects.

7.5 Variable Scope: The LEGB Rule & UnboundLocalError

Variables defined inside a function live in that function's **Local Scope**. They are born when the function is called and destroyed when the function returns. They cannot be seen or accessed by the outside script. ### The LEGB Lookup Hierarchy: When Python encounters a variable name, it searches 4 nested scopes in order: 1. **L (Local)**: Inside the currently executing function. 2. **E (Enclosing)**: Inside any enclosing functions (closures). 3. **G (Global)**: At top-level module scope. 4. **B (Built-in)**: Python's built-in namespace (`print`, `len`, `range`).
Statement 5: Variable Scope and Function Pureness

Understanding local isolation and avoiding global variable mutation.

# Global variable
GLOBAL_THRESHOLD = 70

def evaluate_risk(score):
    # Local variable 'score' and 'is_elevated'
    # Can READ GLOBAL_THRESHOLD, but cannot mutate it
    is_elevated = score >= GLOBAL_THRESHOLD
    return is_elevated

print("Score 85 elevated :", evaluate_risk(85))
print("Score 50 elevated :", evaluate_risk(50))

# Demonstrating that local variables do not leak outside
# print(is_elevated) -> NameError: name 'is_elevated' is not defined!
Execution walkthrough
  1. 1.Line 2: Allocates GLOBAL_THRESHOLD = 70 at module scope.
  2. 2.Lines 4-7: evaluate_risk reads GLOBAL_THRESHOLD, computes local boolean, returns it.
  3. 3.Line 9: Prints True; Line 10: Prints False.
Expected output
Score 85 elevated : True
Score 50 elevated : False
Edge cases

• UnboundLocalError: If you assign to a variable anywhere inside a function (e.g. `count = count + 1`), Python classifies `count` as a LOCAL variable for the ENTIRE function! If you try to read it before that assignment, Python crashes with `UnboundLocalError: local variable 'count' referenced before assignment`. • Pure Functions: In AI and data science, prefer **pure functions** that accept inputs via parameters and return outputs via return, without reading or mutating global state.

Why it happens: Python creates an isolated local scope whenever a function is called, ensuring local variables do not leak or collide with outside code.

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 7: Modular Temperature & Vitals Converter

basic

Define a function fahrenheit_to_celsius(f_temp) that converts Fahrenheit to Celsius using formula: (f_temp - 32) * 5 / 9, and returns the float rounded to 1 decimal place. Call the function for 98.6 and print the result.

Chapter 07 assignmentMilestone

Modular Password Security & Entropy Validator Microservice

Scenario

A cybersecurity infrastructure module at the Center of Excellence requires a modular security microservice. You must architect 3 pure, reusable functions: one to clean and normalize credentials, one to evaluate password complexity and entropy rules, and one to generate a structured audit dictionary report.

Implementation requirements
  • Function 1: clean_credential(text: str) -> str: Strips whitespace and returns cleaned string.
  • Function 2: check_password_complexity(password: str, min_length: int = 8, require_digit: bool = True) -> tuple[bool, int]:
  • - Calculates complexity score starting at 0.
  • - If len(password) >= min_length: +40 score.
  • - If any character in password is a digit (using char.isdigit()): +30 score.
  • - If any character is uppercase (using char.isupper()): +30 score.
  • - Returns a tuple: (is_valid: bool, score: int), where is_valid is True only if len >= min_length and (require_digit implies digit present).
  • Function 3: audit_user_account(user_id: str, raw_pwd: str, min_length: int = 8) -> dict:
  • - Calls clean_credential(raw_pwd).
  • - Calls check_password_complexity(cleaned, min_length=min_length).
  • - Returns a dictionary: {'user': user_id, 'length': len(cleaned), 'score': score, 'status': 'PASS' if is_valid else 'FAIL'}.
  • Test your functions by auditing user 'admin_01' with password 'CoE_Secure2026' and user 'guest_02' with password 'abc'. Print both audit reports.
Edge cases to handle
  • 1.Avoid mutable default arguments: Only use immutable types (int, bool, str) as default values.
  • 2.Empty password string: len(pwd) == 0 should return score = 0, is_valid = False without crashing.
  • 3.Correct tuple unpacking inside audit_user_account.
Starter template
# Chapter 7 Assignment: Modular Password Security Microservice
# Center of Excellence: Data Science & AI

# TODO: Function 1 - clean_credential(text)
# TODO: Function 2 - check_password_complexity(password, min_length=8, require_digit=True)
# TODO: Function 3 - audit_user_account(user_id, raw_pwd, min_length=8)

# Test runs:
# report_1 = audit_user_account("admin_01", "  CoE_Secure2026  ")
# report_2 = audit_user_account("guest_02", "abc")
# print(report_1)
# print(report_2)
Progressive hints

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01Functions encapsulate reusable logic using def and return; avoid repeating code across scripts.
  • 02Positional arguments are mapped by order; keyword arguments are mapped by parameter name.
  • 03Default parameters provide fallback values; non-default parameters must always precede default parameters.
  • 04NEVER use mutable objects ([], {}) as default parameters; use the None sentinel pattern.
  • 05return transmits data back to caller; functions without an explicit return implicitly return None.
Syntax reference
def func_name(param1, param2=default): ... return valDeclaring a function with default parameters and return value.
a, b = get_two_values()Unpacking multiple return values from a tuple.
def f(items=None): if items is None: items = []Safe None sentinel pattern avoiding the mutable default trap.

Knowledge check

Verify your grasp of the chapter concepts

What is the return value of a function that does not contain an explicit 'return' statement?

How should a function with a default list parameter be defined safely?

In Python's LEGB scope lookup, what does the 'E' stand for?