Functions in Python (`def`, Scope & Returns)

Module 2 • Session 12 • Allocation: 1 Contact Hr

def return docstrings LEGB scope first-class objects

Functions are named, reusable blocks of code designed to perform a single, cohesive task. They are the primary tool for modularizing code, reducing complexity, and adhering to the DRY (Don't Repeat Yourself) software engineering principle.

1. Defining and Calling Functions

Use the def keyword followed by the function name, parenthesized parameters, and a colon. Indented code forms the body.

def calculate_tax(subtotal, tax_rate=0.08): """Calculates final tax amount for a shopping cart.""" return round(subtotal * tax_rate, 2) # Invoking the function subtotal_amount = 150.0 tax_due = calculate_tax(subtotal_amount) print(f"Tax due: ${tax_due}") # Output: Tax due: $12.0

2. Anatomy of a Python Function

Component Syntax / Keyword Purpose & Description
def Keyword def name(): Informs Python that a function definition is beginning.
Docstring """Doc text""" Optional triple-quoted string describing function behavior. Accessible via help(fn) or fn.__doc__.
Parameters (arg1, arg2) Variables declared in the function definition that receive values when invoked.
return Statement return val Exits the function and passes a result back to the caller. If omitted, returns None.

3. Multiple Return Values & Implicit `None`

In Python, returning multiple values separated by commas packs them into a single Tuple, which can be cleanly unpacked on assignment.

def compute_vector_stats(numbers): if not numbers: return None, None # Explicit return return min(numbers), max(numbers) # Returns a tuple (min, max) low, high = compute_vector_stats([42, 11, 88, 3, 99]) print(f"Minimum: {low}, Maximum: {high}")
Implicit Return: If execution reaches the end of a function body without hitting a return statement, Python automatically evaluates the result as None.

4. Variable Scope and the LEGB Rule

Names defined inside a function exist in its local scope. When resolving variable references, Python searches scopes in a strict order known as LEGB:

  • L (Local): Names assigned inside the executing function.
  • E (Enclosing): Names in enclosing function scopes (nested functions).
  • G (Global): Top-level module variables or declared global.
  • B (Built-in): Preloaded names in Python (e.g., len, range, print).
global_counter = 100 # Global scope def update_counter(): global global_counter # Declare intent to modify global variable local_offset = 5 # Local scope global_counter += local_offset update_counter() print(f"Updated global counter: {global_counter}") # Output: 105
Avoid Excessive `global`: Modifying global variables inside functions introduces side-effects, making testing and debugging difficult. Prefer passing inputs as arguments and capturing return values.

5. Functions as First-Class Objects

In Python, functions are first-class objects. You can assign them to variables, pass them as arguments to other functions (higher-order functions), or store them inside dictionaries and lists.

def apply_discount(price): return price * 0.9 def apply_surcharge(price): return price * 1.15 # Store functions inside a dictionary mapping pricing_strategies = { "DISCOUNT": apply_discount, "SURCHARGE": apply_surcharge } price = 100.0 action = "DISCOUNT" final_price = pricing_strategies[action](price) print(f"Final calculated price: ${final_price:.2f}")

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Temperature Converter

Write a function celsius_to_fahrenheit(c_temp) that returns the temperature converted to Fahrenheit. Include a docstring.

Challenge 2: Multi-Stat Calculator

Define a function analyze_dataset(data) that returns the count, mean, and range (max - min) as unpacked tuple elements.

Challenge 3: First-Class Operation Dispatcher

Create a dictionary mapping string math operators ("+", "-", "*") to helper functions and invoke them dynamically.

⚡ Interactive Sandbox (Python Function Engine)
Console Output:
Click "Run Code" above to execute interactive function scripts...

📝 Knowledge Check Quiz

1. What does a Python function return if no explicit `return` statement is executed?
2. In the LEGB variable lookup rule, what does the letter 'E' stand for?
3. How are multiple comma-separated values in a `return` statement delivered to the caller?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)