Functions
The structuring unit without which programming gets very uncomfortable very quickly.
Many Python commands you have used so far — print(), input(), range(), len() — are functions someone else wrote. Functions are the fundamental building block of every program: they take input, do work, and return a result.
In this article, you will learn to build your own functions, understand why they make code shorter and safer, and discover scope — the invisible rules that prevent variables inside functions from leaking out and causing chaos.
What Is a Function?
You have been calling functions since your first line of Python. Here are eight you already know:
Definition
Function
Analogy
Definition
The juicer analogy works well for input/output and abstraction. But a juicer can only juice — a function can contain any logic including conditionals, loops, and calls to other functions. Some functions take no input, and some return no meaningful result.
Note
How a Function Call Works
- 1. Python sees the call greet("Ada") — greet is defined as def greet(name): return f"Hello, {name}!"
- 2. The argument "Ada" is bound to the parameter name
- 3. The function body executes: f"Hello, {name}!"
- 4. return sends the value "Hello, Ada!" back
- 5. The caller receives the string and can use it further
Displays text on the screen but returns None. The result cannot be stored in a variable or used further. Good for displaying, not for computing.
Sends a value back to the caller. The result can be stored in a variable, processed further, or passed to another function. This is how you get data out of a function.
Caution
Common Mistake: print() Instead of return
Beginners often confuse print() and return. A function that only uses print() does display something — but the caller receives None instead of a usable value.
def double(x):
print(x * 2) # Shows 10...
result = double(5)
print(result) # ...but result is None!The correct version: return x * 2 — then result holds the value 10 and can be used further.
Why Functions? DRY and Modularization
Definition
DRY Principle
Analogy
Definition
The directions analogy works well: repeated sub-routes are factored out, the name serves as a reference, and one change propagates everywhere. In real life, you can rely on implicit knowledge ("you know the way") — in code, every instruction must be explicit.
Example: Gross Price Calculation
Without a function — the same formula copied three times:
price1 = 100 * 1.19 # 119.0
price2 = 250 * 1.19 # 297.5
price3 = 49.90 * 1.19 # ≈ 59.381 (Python shows 59.38099999999999)With a function — the formula exists only once:
def gross(net):
return net * 1.19
price1 = gross(100) # 119.0
price2 = gross(250) # 297.5
price3 = gross(49.90) # ≈ 59.381 (Python shows 59.38099999999999)If the tax rate changes from 19% to 16%, you update one single line instead of searching through the entire program.
Modularization means splitting a big problem into small, named functions. Each function has one clear job: load_data(), validate(), process(), display(). The function names act like an outline — you can read the program flow without understanding every single step.
Caution
Misconception: Functions Are Only for Large Programs
Even a 20-line script benefits from structure. If you write the same logic twice, that is a sign: extract it into a function. And copy-paste with small tweaks is not a solution — parameterize the differences instead.
Scope — Where Variables Live and Die
Definition
Scope (Variable Visibility)
Analogy
Definition
The hotel analogy works well: public space (global) vs. private space (local), and contents disappear after checkout. But in a hotel, you can carry objects from your room to the lobby — in Python, the clean way is to return values and assign them outside.
Example: Same Name, Different Scope
message = "I am global"
def show_message():
message = "I am local"
print(message) # "I am local"
show_message()
print(message) # "I am global"Inside the function, a separate variable message exists that shadows the global one. The global variable remains unchanged — this is exactly the intended behavior. Scope keeps functions independent from each other.
Note
Error: Accessing Outside the Scope
def calculate():
x = 42
calculate()
print(x) # NameError: name 'x' is not definedThe variable x exists only inside the function calculate(). After the call, it is gone — like a hotel room after checkout.
Caution
Warning: Modifying Global Variables in Functions
The global keyword allows a function to directly modify global variables. This works — but it is almost always a bad idea because it makes functions dependent on their environment and bugs become hard to track down.
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # 1Prefer return over global. The clean approach: return the new value and assign it outside.
Interactive: Function Call Step by Step
You learned that local variables exist only inside their function. But WHERE exactly do they live? Click through the steps of a function call and observe the call stack — the internal data structure where Python creates a separate frame for each call. Watch how variables appear in the frame and disappear when the function returns.
def greet(name): msg = f"Hello, {name}!" return msgresult = greet("Ada")print(result)Python encounters the line result = greet("Ada"). It recognizes a function call and prepares to execute the function greet.
Parameters can have default values. If no argument is passed during the call, the default is used:
def greet(name="World"):
return f"Hello, {name}!"
print(greet()) # "Hello, World!"
print(greet("Ada")) # "Hello, Ada!"With keyword arguments you can address parameters by name: greet(name="Ada"). With multiple parameters, this makes the code more readable because the order no longer matters.
Caution: never use an empty list as a default value (def f(items=[])). Python creates the default only once — the list accumulates entries across multiple calls. Use items=None instead and create the list inside the function body.
The true power of functions shows when one function's return value becomes the input for the next — a pipeline of small, specialized building blocks:
def load(file):
with open(file, encoding="utf-8") as f:
return f.read()
def clean(text):
return text.strip().lower()
def count(text):
return len(text.split())
# Pipeline: load -> clean -> count
content = load("data.txt")
cleaned = clean(content)
word_count = count(cleaned)
print(f"{word_count} words")In later articles, you will see this pattern in data processing and machine learning workflows.
Note
Key Takeaways
- A function is defined with def, takes parameters as input, and uses return to send a result back. Without return, the function returns None.
- print() displays text on the screen but returns None. return passes a value back to the caller for further use. They are not interchangeable.
- The DRY principle: write logic once, call it everywhere. When the logic changes, you fix it in one place.
- Modularization means splitting a big problem into small, named functions. Each function has one clear job.
- Variables inside a function are local — they exist only while the function runs and are invisible outside. This isolation makes functions reusable and protects against unwanted side effects.
Check
Quiz: Functions
What does a function return if it has no return statement?
Select one answer
1. What does a function return if it has no return statement?
2. What is the value of result after this code? def double(x): print(x * 2) result = double(5)
3. What does print(x) output at the end? x = "global" def test(): x = "local" test() print(x)
4. You have the same calculation in 5 places in your code. The formula changes. What is the best approach?
Check
Checkpoint
Can you explain this in your own words? Tick what you've got.
0 of 3 done