Breaking Down Complex Problems into Manageable Functions
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:
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()
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()
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.