Table of Contents
Why Reuse Code?
Reusing code means taking code you (or someone else) have already written and using it again, instead of writing similar code from scratch every time.
In Python, functions are one of the main tools for reusing code. Once you’ve defined a function, you can call it:
- Many times
- From different parts of the same program
- Even from other files (modules), once you know how to import code
Reusing code helps you:
- Avoid copy-paste duplication
- Make your programs shorter and easier to read
- Fix bugs in one place instead of many
- Build bigger programs by combining small, tested pieces
Recognizing Repeated Code
Before you can reuse code, you need to spot patterns in what you’re writing.
Typical signs that you should create or reuse a function:
- You copied and pasted code, then changed one or two small things.
- You have several blocks of code that:
- Do the same steps
- In slightly different situations (e.g., different messages or values)
- You find yourself scrolling a lot to understand what the program does.
Example of repeated code:
name = input("Enter your name: ")
print("Hello,", name, "!")
print("Welcome to our program.")
print("We hope you enjoy your stay.\n")
friend_name = input("Enter your friend's name: ")
print("Hello,", friend_name, "!")
print("Welcome to our program.")
print("We hope you enjoy your stay.\n")The pattern: “ask for a name, greet the person in a friendly way.”
Instead of repeating that logic, you can define a function and then reuse it.
Turning Repeated Code into a Function
Take the repeated pattern and:
- Move it into a function.
- Replace specific values (like names) with parameters.
- Call the function where you need it.
Rewriting the previous example:
def greet(name):
print("Hello,", name, "!")
print("Welcome to our program.")
print("We hope you enjoy your stay.\n")
# Reuse the function
name = input("Enter your name: ")
greet(name)
friend_name = input("Enter your friend's name: ")
greet(friend_name)Now:
- The greeting logic lives in one place (
greet). - If you want to change the greeting, you change it once, not in multiple places.
Reusing Functions in the Same Program
Once a function is defined (earlier in the file), you can call it:
- From the main part of your script
- From another function
Example: basic math helpers
def add(a, b):
return a + b
def multiply(a, b):
return a * b
def calculate_total_price(price, quantity, tax_rate):
subtotal = multiply(price, quantity)
tax = multiply(subtotal, tax_rate)
total = add(subtotal, tax)
return total
# Reusing helper functions
item_price = 10.0
item_quantity = 3
tax_rate = 0.1
total = calculate_total_price(item_price, item_quantity, tax_rate)
print("Total:", total)Here:
addandmultiplyare small, reusable building blocks.calculate_total_pricereuses them to build a more specific operation.- If you use
addormultiplysomewhere else in the program, you’re reusing tested code instead of rewriting it.
Reusing Functions with Different Arguments
The real power of reuse comes from calling the same function with different arguments.
Example: a function that prints a line of stars around some text:
def fancy_print(message):
border = "*" * (len(message) + 4)
print(border)
print("*", message, "*")
print(border)
fancy_print("Hello")
fancy_print("Python is fun")
fancy_print("Reusable functions save time")You write the formatting logic once, then reuse it for any message.
Another example: converting temperatures:
def celsius_to_fahrenheit(c):
return (c * 9 / 5) + 32
print(celsius_to_fahrenheit(0)) # freezing point
print(celsius_to_fahrenheit(25)) # room temperature
print(celsius_to_fahrenheit(100)) # boiling pointOne function, many uses.
Reusing Code with Helper Functions
A common practice is to break a bigger task into helper functions that each do one clear thing. This makes it easy to reuse parts of the logic in other contexts.
Example: a simple quiz structure:
def ask_question(question, correct_answer):
print(question)
answer = input("Your answer: ")
if answer == correct_answer:
print("Correct!\n")
return 1
else:
print("Wrong. The correct answer was:", correct_answer, "\n")
return 0
def run_quiz():
score = 0
score += ask_question("What is 2 + 2?", "4")
score += ask_question("What is the capital of France?", "Paris")
score += ask_question("What color is the sky?", "blue")
print("You scored", score, "out of 3")
run_quiz()Here:
ask_questionis a reusable helper: you can call it for any question.run_quizreusesask_questionmultiple times to build a complete quiz.- If you later want another game that asks questions, you can reuse
ask_questionagain.
Avoiding Repetition (DRY Principle)
A common idea in programming is “DRY”: Don’t Repeat Yourself.
When you notice repetition:
- Ask: “What is the general task this code is performing?”
- Create a function that performs that general task.
- Replace the repeated code with calls to the new function.
Example of “wet” (repetitive) code:
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
area1 = length * width
print("Area 1:", area1)
length2 = float(input("Enter the length: "))
width2 = float(input("Enter the width: "))
area2 = length2 * width2
print("Area 2:", area2)DRY version:
def rectangle_area():
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
area = length * width
print("Area:", area)
rectangle_area()
rectangle_area()Even better: separate input, calculation, and printing so each part can be reused independently:
def get_float(prompt):
return float(input(prompt))
def rectangle_area(length, width):
return length * width
def print_area(area):
print("Area:", area)
length1 = get_float("Enter the length: ")
width1 = get_float("Enter the width: ")
area1 = rectangle_area(length1, width1)
print_area(area1)Now:
get_floatcan be reused anywhere you need a number from the user.rectangle_areacan be reused for rectangles from any source (user input, files, etc.).print_areacan be reused if you compute areas in different ways.
Grouping Related Functions
As you write more code, you may group functions that solve related problems. Even before you learn about modules and packages, you can structure a single file to make reuse easier.
Example: a small “text utilities” section in your file:
# Text utilities
def shout(text):
return text.upper() + "!"
def whisper(text):
return text.lower()
def surround(text, wrapper):
return wrapper + text + wrapper
# Using the utilities
msg = "Python"
print(shout(msg))
print(whisper(msg))
print(surround(msg, "---"))Benefits:
- You have a toolbox of functions ready to reuse.
- You can easily find and modify your helpers.
- You can copy this small group of functions into other programs if needed (basic reuse across files).
When NOT to Create a Function
Not every line needs a function. Reuse is useful, but creating too many tiny functions can make code harder to read.
You generally do not need a function when:
- Code is used only once and is very short and clear.
- Creating a function would make understanding the flow more confusing.
- The code is already simple and doesn’t repeat.
A good rule of thumb:
- If you repeat a block of code 3 or more times, consider a function.
- If the code block is long or complicated, consider a function even if it appears only once, so you can give it a clear name (and later reuse it if needed).
Benefits of Reusing Code with Functions
Summarizing what you gain by reusing functions:
- Less code to write: fewer lines, less typing.
- Easier to change: update behavior in one place.
- Fewer bugs: a tested function can be trusted everywhere it’s used.
- Clearer structure: your main program reads like a list of high-level steps.
- Easier collaboration: others can use your functions without knowing their internal details.
As you continue learning Python, try to look at your programs and ask:
- “What parts here are doing the same kind of work?”
- “Can I turn this into a function and reuse it?”
Practicing that habit early will make you a much stronger programmer.