Definition
Named blocks of code designed to perform a specific, single task. They allow for code reuse and logical separation within a program.
Why It Matters
Functions are the primary tool for managing software complexity; by encapsulating logic into reusable ‘black boxes,’ they prevent code bloat, reduce the surface area for bugs, and allow teams to collaborate on massive codebases without needing to understand every line of code.
Core Concepts
- Deduplication (DRY): The primary goal of functions is to eliminate duplicated code (“Don’t Repeat Yourself”). This makes programs shorter, easier to read, and easier to update (fixing a bug once instead of in multiple copies).
- The “Black Box” Model: A function should be viewed as a black box: you care about what goes in (arguments) and what comes out (return value), but you don’t need to know how the code inside works to use it.
- The None Value: In Python, every function call evaluates to a return value. If a function lacks a
returnstatement (or reaches the end without one), it implicitly returnsNone. - Definition vs. Call:
defcreates the function; parentheses()invoke it. Without parentheses, you are referring to the function object itself.
def greet_user(username):
"""Display a simple greeting."""
message = f"Hello, {username.title()}!"
return message
greeting = greet_user('jesse')
print(greeting)