Python Functions & Modular Code
A function is like a button on a coffee machine: you define the recipe once with def, and whenever someone presses the button (calls the function), the machine brews the coffee without rewriting the recipe every morning.
"Imagine a recipe for chocolate chip cookies. Instead of rewriting the recipe every time a guest visits, you write it once in your recipe book under "bake_cookies()", and whenever you want cookies, you just call that name."
Deep Dive: How It Works
The def keyword defines a function followed by its name, parentheses (), and a colon :. The instructions inside the function must be indented by 4 spaces.
Definition vs Execution: Writing def my_func(): does NOT run the code. It simply teaches Python the recipe. To execute it, you must call the function by writing my_func().
The DRY Principle (Don't Repeat Yourself): If you find yourself copying and pasting the same 3 lines of code in multiple places, wrap them into a function.
Variable Scope: Variables created inside a function are local to that function and disappear when the function finishes running.
Syntax Blueprint
def function_name():
# 4 spaces of indentation
do_task_one()
do_task_two()
# Call the function:
function_name()Define with def and colon, indent the body, and execute by calling the name with parentheses ().
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting parentheses when calling: my_functionWhy it happens: Writing my_function without () references the function object itself instead of executing it.
How to fix: Always include parentheses to execute: my_function().
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 custom function
Define a function named say_hello() that prints "Hello from a function!".
Call say_hello() on a new line.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.