Python Decomposition

Breaking Down Complex Problems into Manageable Functions

What is Decomposition?

Decomposition is the practice of breaking a large problem into smaller, manageable components. In Python, this is often done by defining functions or organizing code into modules. This enhances:

Example 1: Read, Process, and Print

def read_data(path):
    # Simulated data reading
    return [1, 2, 3, 4, 5]

def process(data):
    # Square each number
    return [x**2 for x in data]

def main():
    raw = read_data("data.csv")
    result = process(raw)
    print("Processed Result:", result)

if __name__ == "__main__":
    main()

Example 2: Email Validation Pipeline

def get_input():
    return input("Enter your email: ")

def is_valid_email(email):
    return "@" in email and "." in email

def main():
    email = get_input()
    if is_valid_email(email):
        print("Valid email!")
    else:
        print("Invalid email.")

if __name__ == "__main__":
    main()

Example 3: Basic Calculator

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def calculate():
    x = 10
    y = 5
    print("Add:", add(x, y))
    print("Subtract:", subtract(x, y))

if __name__ == "__main__":
    calculate()

Each example demonstrates decomposition by separating logic into smaller functions. This makes the code cleaner, testable, and easier to maintain.