Python Functions — Explain Like I'm 5
The Vending Machine of Code
Imagine a vending machine. You press a button, it does a whole series of things (checks your payment, releases the item, counts inventory) and gives you something back. You don’t have to know how the machine works inside — you just press the button.
Functions are like vending machine buttons in your code.
Instead of writing out the same instructions every time you need to do something, you write them once inside a function, give it a name, and then just “press the button” (call the function) whenever you need it.
Making Your Own Button
def greet(name):
message = "Hello, " + name + "!"
print(message)
The word def means “define a function.” Then you give it a name (greet), tell it what information it needs (name), and write the instructions inside (indented).
Now, anywhere in your program you can do:
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!
greet("Charlie") # Hello, Charlie!
Three different results, from pressing the same button three times with different inputs.
Getting an Answer Back
Some vending machines give you food. Some functions give you a value back:
def add_numbers(a, b):
return a + b
result = add_numbers(3, 4)
print(result) # 7
The return line sends a value back to whoever called the function. Without return, the function does its thing but hands you back None (nothing).
Why Bother?
Imagine you need to calculate a price with tax in 50 different places in your program. Without functions, you’d write price * 1.20 in 50 places. If the tax rate changes to 1.25, you’d have to find and change all 50.
With a function:
def add_tax(price):
return price * 1.20
Change it once, everywhere is fixed instantly.
One Thing to Remember
Functions let you name a set of instructions and reuse them. Instead of writing the same code over and over, you write it once and call it by name whenever you need it.
See Also
- Python Async Await Async/await helps one Python program juggle many waiting jobs at once, like a chef who keeps multiple pots moving without standing still.
- Python Basics Python is the programming language that reads like plain English — here's why millions of beginners (and experts) choose it first.
- Python Booleans Make Booleans click with one clear analogy you can reuse whenever Python feels confusing.
- Python Break Continue Make Break Continue click with one clear analogy you can reuse whenever Python feels confusing.
- Python Closures See how Python functions can remember private information, even after the outer function has already finished.