Kahibaro
Discord Login Register

Reusing code

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:

Reusing code helps you:

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:

  1. You copied and pasted code, then changed one or two small things.
  2. You have several blocks of code that:
    • Do the same steps
    • In slightly different situations (e.g., different messages or values)
  3. 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:

  1. Move it into a function.
  2. Replace specific values (like names) with parameters.
  3. 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:

Reusing Functions in the Same Program

Once a function is defined (earlier in the file), you can call it:

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:

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 point

One 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:

Avoiding Repetition (DRY Principle)

A common idea in programming is “DRY”: Don’t Repeat Yourself.

When you notice repetition:

  1. Ask: “What is the general task this code is performing?”
  2. Create a function that performs that general task.
  3. 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:

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:

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:

A good rule of thumb:

Benefits of Reusing Code with Functions

Summarizing what you gain by reusing functions:

As you continue learning Python, try to look at your programs and ask:

Practicing that habit early will make you a much stronger programmer.

Views: 17

Comments

Please login to add a comment.

Don't have an account? Register now!