Packaging Logic
A function is a named, reusable block of code that performs a specific task. Defining a function once and calling it many times avoids repetition.
A function takes parameters (named inputs in the definition) and receives arguments (actual values passed during the call).
def square(n):
return n * n
y = square(5) # y becomes 25
The return statement hands a result back to the caller and ends the function execution. Functions enable abstraction, letting you use code without knowing its internal implementation.
Scope and Pitfalls
Scope governs where variables are visible. Local variables are created inside functions and exist only during that call. Global variables are declared outside all functions and are visible everywhere.
| Term | Definition |
|---|---|
| Parameter | Name listed in the function definition |
| Argument | Actual value passed during a function call |
Common pitfall: Confusing parameters with arguments. Also, trying to access a local variable from outside its function will cause an error because it does not exist there.