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.
- 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
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))- 1.Lines 2-5: Compiles the function sanitize_email_text with parameter raw_text.
- 2.Line 11: Calls sanitize_email_text(email_1); raw_text receives email_1.
- 3.Line 4: Executes .strip().lower() and returns 'urgent: verify credentials!'.
- 4.Line 12: Calls sanitize_email_text(email_2), producing 'meeting agenda for thursday'.
Sanitized 1: urgent: verify credentials! Sanitized 2: meeting agenda for thursday
• 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
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- 1.Line 2: Defines matched_count (mandatory), weight_per_match (default 25), base_score (default 10).
- 2.Line 8: Calls with only matched_count=3. Defaults 25 and 10 are applied automatically.
- 3.Line 16: Calls using explicit keyword arguments; order can vary freely.
Default call (3 matches) : 85 Custom weight (3 matches @ 15pts) : 55 Keyword call (custom base 0) : 60
• 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'
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!- 1.Line 2: buggy_collector binds storage=[] at definition time.
- 2.Line 6: Appends 'A' -> ['A'].
- 3.Line 7: Reuses the SAME storage list and appends 'B' -> ['A', 'B']!
- 4.Line 11: safe_collector uses storage=None.
- 5.Lines 18-19: Each call allocates a fresh, independent list.
Buggy call 1: ['A'] Buggy call 2: ['A', 'B'] Safe call 1 : ['A'] Safe call 2 : ['B']
• 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
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}")- 1.Lines 6-8: Calculates min=12, max=94, average=63.0.
- 2.Line 9: Returns (12, 94, 63.0).
- 3.Line 13: Unpacks tuple into lowest=12, highest=94, average=63.0.
Lowest Risk : 12 Highest Risk : 94 Average Risk : 63.0
• 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
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!- 1.Line 2: Allocates GLOBAL_THRESHOLD = 70 at module scope.
- 2.Lines 4-7: evaluate_risk reads GLOBAL_THRESHOLD, computes local boolean, returns it.
- 3.Line 9: Prints True; Line 10: Prints False.
Score 85 elevated : True Score 50 elevated : False
• 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
basicDefine 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.
Modular Password Security & Entropy Validator Microservice
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.
- 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.
- 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.
# 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)
Chapter summary
Key concepts and syntax cards for review
- 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.
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?