Defining Functions
Learn how to create your own reusable functions in Python — the building blocks that keep your code clean, organized, and DRY.
Imagine you need to wrap a gift. You could tape, fold, and ribbon every single present from scratch each time — or you could follow a written set of steps once and repeat it whenever you need. Functions are exactly that: a named set of instructions you write once and use as many times as you want.
In Python, defining a function is how you teach the language a brand-new trick. Once taught, you can use that trick anywhere in your program with a single line.
See it in action
— step through the idea, then dive into the details below.Write Once, Use Anywhere
A function is a named set of instructions you define once and run whenever you need. It's how you teach Python a brand-new trick — no copy-pasting required.
#Why Functions Matter
Without functions, you end up copying and pasting the same code over and over. That's a problem because:
- It wastes time. More typing, more chances to make a mistake.
- It breaks easily. If you need to fix something, you have to find every copy.
- It's hard to read. A wall of repeated code doesn't tell you what it does.
Functions solve all three problems. This idea has a name in programming: DRY — Don't Repeat Yourself.
A Function Is Like a Recipe
A recipe has a name ("Chocolate Cake"), ingredients you pass in (flour, eggs, sugar), and steps to follow. You don't re-invent the recipe every time — you just call it by name and supply the ingredients. Python functions work the same way.
#Defining Your First Function
Use the keyword def (short for define) followed by a name, parentheses, and a colon. Everything indented underneath belongs to the function.
def greet():
print("Hello, world!")
greet()Breaking down the syntax:
def— tells Python you are defining a functiongreet— the name you choose (same rules as variable names)()— the parentheses hold any inputs; empty means no inputs:— the colon opens the function body- Indented lines — the body of the function (Python requires consistent indentation, typically 4 spaces)
#Calling a Function
Defining a function does not run it. Think of it as writing the recipe down. To actually bake the cake, you have to call the function — write its name followed by ().
def greet():
print("Hello, world!")
# Nothing has happened yet — we only defined the function.
greet() # NOW it runs
greet() # Run it again — for free!#Parameters and Arguments
A function becomes much more useful when it can accept inputs. The variable names listed inside the parentheses in the def line are called parameters. The actual values you pass when calling the function are called arguments.
- Parameter — the placeholder variable in the definition
- Argument — the real value you supply when calling
def greet(name):
print("Hello,", name)
greet("Alice")
greet("Bob")You can have multiple parameters, separated by commas.
def add(a, b):
result = a + b
print(a, "+", b, "=", result)
add(3, 5)
add(10, 20)#Documenting with Docstrings
It's good practice to explain what your function does. Python has a built-in way to do this: a docstring — a triple-quoted string placed as the very first line of the function body.
def greet(name):
"""Print a friendly greeting for the given name."""
print("Hello,", name)
def add(a, b):
"""Return the sum of a and b."""
result = a + b
print(a, "+", b, "=", result)
greet("Priya")Always Write a Docstring
Even one short sentence is enough. Future-you (reading the code in six months) will be very grateful. Write it in plain English: "Do X given Y."
#Functions Without a Return Value Give None
Every function in Python returns something. If you don't use the return keyword, Python quietly returns a special value called None — a way of saying "nothing here". You will learn more about return in the next lesson; for now, just know it exists.
def greet(name):
"""Print a friendly greeting."""
print("Hello,", name)
result = greet("Sam")
print("Return value:", result)Don't Forget the Colon — or the Indent
Two of the most common beginner mistakes:
- Missing colon after the parentheses:
def greet(name)instead ofdef greet(name): - Wrong indentation inside the body — Python will raise an
IndentationError.
If Python complains, check those two things first.
Calling Before Defining
You must define a function before you call it. If you try to call greet() on line 1 but the def greet is on line 5, Python will raise a NameError. Always define first, call second.
What is the difference between a *parameter* and an *argument*?
Key takeaways
- Use `def name(params):` followed by an indented body to define a function.
- Functions let you reuse code — write once, call many times (the DRY principle).
- Parameters are placeholders in the definition; arguments are the values you pass when calling.
- Add a docstring (triple-quoted string) as the first line of a function to document what it does.
- A function with no `return` statement automatically returns `None`.
What does this code print?
def greet(name):
print("Hello,", name)
greet("Alice")
greet("Bob")This code has a bug. What is wrong?
def add(a, b)
result = a + b
print(a, "+", b, "=", result)
add(3, 5)Complete the code so it defines a function called `welcome` that prints "Welcome!".
welcome():
print("Welcome!")
welcome()Put these lines in the right order to define and call a function that greets a user by name.
greet("Sam")def greet(name):
"""Print a greeting for the given name."""
print("Hello,", name)Write a function called introduce that takes two parameters: name and age. It should print a sentence like: "Hi, I'm Alice and I'm 30 years old." Add a docstring. Then call your function twice with different names and ages.
Try it live — edit the code and hit Run to execute real Python: