Python Functions: Declarations, Local Scope & Return Values
Functions modularize script logic into reusable, testable units. Inside functions, arguments are accessed via positional parameters (`$1`, `$2`), variables MUST be scoped with `local` to prevent global pollution, and values are returned via stdout or numeric exit codes (`return 0-255`).
"A function is a mini-script inside your script: it takes inputs, works in its own private workspace (`local`), and produces an answer on stdout."
Deep Dive: How It Works
Syntax Styles: `function_name() { ... }` (POSIX standard) or `function name { ... }`. Prefer the POSIX syntax without the redundant `function` keyword.
Local Variable Scoping: Always write `local my_var="value"` inside functions.
Return vs Output: `return N` only returns an integer status code (0 = success, 1-255 = error); To return a string or data structure, print to stdout (`echo "$result"`) and capture with command substitution (`RES=$(my_func)`).
Syntax Blueprint
calculate_tax() {
local amount="$1"
local rate="$2"
echo "$(( amount * rate / 100 ))"
}
TAX=$(calculate_tax 500 10)
echo "Calculated tax: $TAX"Use local for variables and echo for string/data return values.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Trying to return a string with `return "hello"`.Why it happens: `return` in Bash only accepts integer status codes between 0 and 255.
How to fix: Use `echo "hello"` and capture with `RESULT=$(my_func)`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Define and Call a Function
Define a function `greet()` that takes a name `$1` and echoes "Hello, $1!".
Call `greet "ZenCompiler"`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.