Functions & Scope
Overview
Functions let you bundle blocks of reusable code under a descriptive name, keeping your code organized.
Learning Objectives
- Create functions using def, parameters, and return statements.
- Understand the scope rules that determine where variables can be accessed.
- Use arguments like *args and **kwargs to accept dynamic values.
Concept Explanation
Create functions using def. Variables created inside a function are local to it; they cannot be accessed outside. Python uses the LEGB (Local, Enclosing, Global, Built-in) rule to search for variables. Avoid using mutable default values (like lists) as they share state across calls.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
def greet(name):
return f'Hello, {name}!'
print(greet('Alice'))
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Calculate tax with safe default parameters
def calculate_total(price, tax_rate=0.05):
return price * (1 + tax_rate)
print(calculate_total(100))
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Create user configs profile dictionary dynamically
def build_profile(username, *hobbies, **details):
profile = {'username': username, 'hobbies': list(hobbies)}
profile.update(details)
return profile
print(build_profile('alex', 'reading', 'cycling', email='alex@corp.com'))
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Call function name → Bind inputs parameters → Run function body statements → Return result value
Common Mistakes
Review these common pitfalls when working with this topic:
- Using mutable values (like default empty lists lst=[]) as default arguments.
- Modifying global variables inside functions without declaring them global.
- Forgetting to write return statements, which causes the function to implicitly return None.
- Confusing parameter order when invoking functions.
Best Practices
Enforce these Pythonic best practices in your codebase:
def append_item(val, lst=[]):
lst.append(val)
return lst # Shared state default list
def append_item(val, lst=None):
if lst is None:
lst = []
lst.append(val)
return lst # Safe initialization
Quick Revision
Use these key summaries for last-minute revision:
- def declares reusable functions.
- return sends values back to callers.
- Local variables are only visible inside their function.
- LEGB rule determines variable lookups.
- Never use mutable default arguments.
- *args captures extra positional arguments.
DataPlayArena Technical Editorial Board
Curated & maintained by enterprise data platform engineers with 10+ years in distributed systems.
Runtime Verification Standards: Every code example, query, and architecture diagram in this tutorial is compiled and verified against real runtimes (Apache Spark 3.5, Python 3.11, PostgreSQL, and DuckDB). If you spot any errata or want to suggest improvements, please submit feedback.