Python Functions: Stop Copying and Pasting
Write functions with parameters, return values and default values, so you stop copying and pasting the same code. It also explains why variables inside a function stay inside it.
Course content
Sign in to save your progress.
-
Before You Write Code
-
Introduction to Python Programming: What It Is and Why Start Here
-
Installing Python and Running Your First Script
-
-
-
The Basics You Cannot Skip
-
Python Variables and Data Types
-
Python Operators and Expressions
-
Getting Input and Printing Output in Python
-
-
-
Making Decisions and Repeating Work
-
Python If Statements: Making Your Code Decide
-
Python Loops: For, While, and When to Stop
-
-
-
Organizing Your Code
-
Python Functions: Stop Copying and Pasting
-
Python Lists and Dictionaries
-
-
-
When Things Go Wrong
-
Reading Python Error Messages Instead of Panicking
-
Python Try and Except: Handling Errors Properly
-
-
- Final Check: Python for Beginners
Python Functions: Stop Copying and Pasting
A function is a named block of code you can run whenever you need it. You write the steps once, give them a name, and call that name instead of repeating the steps. If you have copied the same five lines into three places, you need a function.
Skip ahead: If you already write functions with parameters, return values, and default arguments, continue to "Python Lists and Dictionaries."
Why this matters
Copy-paste code has one big problem: when the rule changes, you have to find and fix every copy. You will miss one. I can almost guarantee it. With a function, you fix it once. Functions also make code readable, because a good name like calculate_total() tells you what a block does without reading it.
Defining and calling a function
def greet():
print("Hello, welcome to the course.")
greet()
greet()
def defines the function. Nothing runs until you call it with greet(). The parentheses are required. greet without them just refers to the function and does nothing.
Parameters: giving a function input
def greet(name):
print(f"Hello, {name}!")
greet("Ana")
greet("Ben")
name is a parameter: a placeholder that gets a real value each time the function is called.
return: getting a result back
This is the part beginners get wrong most. print() shows something on screen. return hands a value back to the code that called the function, so you can store it and use it.
def add_tax(amount, rate):
return amount * (1 + rate)
price = add_tax(1000, 0.12)
print(price) # 1120.0
print(add_tax(500, 0.12) + 50) # 610.0
Compare it with a function that only prints:
def add_tax_print(amount, rate):
print(amount * (1 + rate))
result = add_tax_print(1000, 0.12) # prints 1120.0
print(result) # None
The second one shows the number but gives nothing back, so result is None. If you need the value later, the function must return it. A good rule: functions that calculate should return. Let the caller decide whether to print.
Default values
def add_tax(amount, rate=0.12):
return round(amount * (1 + rate), 2)
print(add_tax(1000)) # uses 0.12 -> 1120.0
print(add_tax(1000, 0.05)) # overrides it -> 1050.0
The 12% here is only an example rate for the exercise. In real code, put rates and limits like this in one clearly named place, because rules change and you want one place to change them.
A real-world example: replacing copy-paste
Before, with the same discount logic pasted twice:
order_a = 1500
if order_a >= 1000:
order_a = order_a * 0.9
order_b = 800
if order_b >= 1000:
order_b = order_b * 0.9
print(order_a, order_b)
After:
def apply_discount(subtotal, minimum=1000, percent=10):
"""Return the subtotal after the discount, if it qualifies."""
if subtotal >= minimum:
return subtotal * (100 - percent) / 100
return subtotal
print(apply_discount(1500)) # 1350.0
print(apply_discount(800)) # 800
Same result. But now the discount rule lives in one place, has a name, and the text in triple quotes (a docstring) says what it does. When the minimum changes to 1,200, you change one number.
Variables inside functions stay inside
def make_total():
total = 500
return total
make_total()
try:
print(total)
except NameError as error:
print("Error:", error)
A variable created inside a function only exists inside it. That is a feature. It means functions do not accidentally overwrite each other's variables. If you need the value outside, return it.
⚠ Warning: Avoid using a list or dictionary as a default value, like def add_item(item, items=[]):. Python creates that default once and reuses it on every call, so items from earlier calls pile up. Use items=None and create a new list inside the function instead. This one surprises even people who have used Python for a while.
Common mistakes
- Printing instead of returning. Then the caller gets
None. - Calling before defining. Python reads top to bottom. The
defmust run before the call. - Forgetting the parentheses.
greetis notgreet(). - Functions that do everything. If you cannot name it without the word "and", it probably should be two functions.
💡 Tip: Name functions with a verb: calculate_total, send_reminder, is_valid_email. If you struggle to name it, you probably are not sure yet what it should do. Figure that out first.
What happens if you skip this step
Your scripts grow by copy and paste. They work. Then a rule changes, you update four of the five copies, and the fifth one keeps applying the old rule for months. Nobody notices until somebody does the math by hand. Functions do not make you a better programmer by themselves. They just make that particular mistake much harder to make.
Quick check: what does a function return if it has no return statement?
About
Write functions with parameters, return values and default values, so you stop copying and pasting the same code. It also explains why variables inside a function stay inside it.
- Duration
- 5 min
- Last update
- 09/10/2026
Comments (0)
Sign in to commentNo comments yet.