KAHIBARO Bookshelves
Discord Login Register

9.6. 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:

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

  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:

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

  • add and multiply are small, reusable building blocks.
  • calculate_total_price reuses them to build a more specific operation.
  • If you use add or multiply somewhere 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 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:

  • ask_question is a reusable helper: you can call it for any question.
  • run_quiz reuses ask_question multiple times to build a complete quiz.
  • If you later want another game that asks questions, you can reuse ask_question again.

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:

  • get_float can be reused anywhere you need a number from the user.
  • rectangle_area can be reused for rectangles from any source (user input, files, etc.).
  • print_area can 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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms