Python ProgrammingBeginner9 min read read

Python Functions: Defining Reusable, Modular Code

Learn def statements, positional parameters, keyword arguments, default values, and scope rules.

Coding Hub Technical Editorial Team(Software Engineering & Education)
•
Updated 2026-03-15

Overview & Context

Functions are the foundational building blocks of organized software. They allow developers to encapsulate logic into named, self-contained, and reusable routines. Instead of repeating lines of code across scripts, functions enable the DRY (Don't Repeat Yourself) principle, making programs easier to test, debug, and maintain.

What You Will Learn
Define functions with clear parameters and explicit return statements
Configure default argument values safely without mutable default traps
Accept arbitrary numbers of parameters with *args and **kwargs
Understand variable scope rules governed by Python's LEGB hierarchy

1. Defining Functions & Return Values

The def statement, parameters, and early returns

In Python, a function is declared using the `def` keyword, followed by the function name, parentheses containing optional parameters, and a colon.

The code block indented beneath the definition executes only when the function is called. Use the `return` keyword to pass calculated results back to the caller. If a function reaches its end without an explicit `return`, it implicitly returns `None`.

python
def calculate_attendance_needed(conducted: int, attended: int, target: float = 0.75) -> int:
    """Calculates additional consecutive classes needed to hit target percentage."""
    if conducted <= 0:
        return 0
    current_percentage = attended / conducted
    if current_percentage >= target:
        return 0
    
    # Mathematical derivation: ceil((target * conducted - attended) / (1 - target))
    import math
    numerator = (target * conducted) - attended
    denominator = 1.0 - target
    return max(0, math.ceil(numerator / denominator))

# Calling the function
needed = calculate_attendance_needed(48, 34, 0.75)
print(f"Classes needed: {needed}")  # Output: 8
Key note: This function mirrors the exact mathematical formula implemented in Coding Hub's online Attendance Calculator.

2. Positional vs Keyword Arguments

Default values and the dangerous mutable default argument pitfall

Arguments passed in order are positional arguments. You can also specify arguments by name using keyword arguments (`key=value`), which allows arguments to be passed in any order.

Common Mistake to Avoid
  • The Mutable Default Trap: Never use a mutable container (like `target_list=[]`) as a default parameter value! Default values are evaluated once when the function is defined, meaning all calls share the exact same list instance. Use `target_list=None` instead and initialize inside the function body.

3. Handling Arbitrary Arguments with *args and **kwargs

When you do not know in advance how many arguments will be passed to a function, use `*args` to collect extra positional arguments into a tuple, and `**kwargs` to collect extra keyword arguments into a dictionary.

python
def calculate_simple_cgpa(*semester_gpas: float) -> float:
    """Computes simple arithmetic mean of any number of semester GPAs."""
    if not semester_gpas:
        return 0.0
    return round(sum(semester_gpas) / len(semester_gpas), 2)

# Pass any number of arguments dynamically
average = calculate_simple_cgpa(8.5, 8.2, 8.8, 8.4)
print(f"CGPA: {average}")  # Output: 8.48
Key note: `*semester_gpas` packs the 4 float numbers into a single tuple `(8.5, 8.2, 8.8, 8.4)`.

4. Variable Scope & The LEGB Rule

Python searches for variable names in a strict 4-tier hierarchy: Local (inside current function) → Enclosing (outer enclosing functions) → Global (module-level) → Built-in (Python system functions like `len`, `sum`, `range`).

Variables created inside a function exist only within that local scope and cannot be accessed from outside.

5. Docstrings & Type Annotations

Professional Python developers write multi-line docstrings beneath the `def` line using triple quotes `"""`. Docstrings provide immediate tooltips inside code editors and generate automatic documentation.

Summary & Key Takeaways

  • 1Define functions with `def`, pass parameters in parentheses, and return values with `return`.
  • 2Never use mutable default arguments; use `None` and initialize inside the function body.
  • 3`*args` collects extra positional parameters into a tuple; `**kwargs` collects keyword arguments into a dictionary.
  • 4Variable lookup strictly follows the Local → Enclosing → Global → Built-in (LEGB) rule.
Frequently Asked Questions

Can a Python function return multiple values?

Yes. In Python, returning comma-separated values (e.g. `return x, y`) packs them into a single tuple. The caller can easily unpack them: `a, b = get_coordinates()`.

What is a lambda function?

A lambda is an anonymous, single-line function defined with the `lambda` keyword (e.g., `lambda x: x * 2`). They are typically used for short transform callbacks inside `sorted()` or `map()`.