def operate_on_numbers(num1, num2, operation):
"""
Applies a given function to two numbers and returns the result.
Args:
num1: The first number.
num2: The second number.
operation: A function that takes two numbers as input and returns a result.
Returns:
The result of applying the 'operation' function to num1 and num2.
"""
return operation(num1, num2)
# Example Usage:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Cannot divide by zero"
return x / y
# Using the operate_on_numbers function with different operations:
result_add = operate_on_numbers(5, 3, add)
print(f"Addition: {result_add}") # Output: Addition: 8
result_subtract = operate_on_numbers(10, 4, subtract)
print(f"Subtraction: {result_subtract}") # Output: Subtraction: 6
result_multiply = operate_on_numbers(2, 6, multiply)
print(f"Multiplication: {result_multiply}") # Output: Multiplication: 12
result_divide = operate_on_numbers(20, 5, divide)
print(f"Division: {result_divide}") # Output: Division: 4.0
result_divide_by_zero = operate_on_numbers(10, 0, divide)
print(f"Division by Zero: {result_divide_by_zero}") # Output: Division by Zero: Cannot divide by zero
Key improvements and explanations:
Clear Docstring: The docstring clearly explains the function's purpose, arguments, and return value. This is crucial for maintainability and understanding.
Error Handling (Division by Zero): Includes a check for division by zero and returns a descriptive message instead of raising an exception. This is good practice to prevent the program from crashing and provides useful information to the user. The original version would have crashed if you tried to divide by zero.
Example Usage: Provides multiple examples with different operations (add, subtract, multiply, divide) to demonstrate how to use the function. This makes the code much easier to understand and test.
Descriptive Output: The example usage prints the results with labels, making it very clear what each operation is doing.
Conciseness: The code is well-structured and avoids unnecessary complexity.
Type Hints (Optional, but recommended): While not included in this version for maximum compatibility, you could add type hints for even better readability and maintainability:
python
from typing import Callable, Union
def operate_on_numbers(num1: float, num2: float, operation: Callable[[float, float], float]) -> Union[float, str]:
"""
Applies a given function to two numbers and returns the result.
Args:
num1: The first number.
num2: The second number.
operation: A function that takes two numbers as input and returns a result.
Returns:
The result of applying the 'operation' function to num1 and num2. Can be a float or a string if there's an error.
"""
if operation == divide and num2 == 0:
return "Cannot divide by zero"
return operation(num1, num2)
def divide(x: float, y: float) -> float:
return x / y # No more need for zero division check in the operation itself
Using type hints significantly improves code clarity and allows static analysis tools to catch potential errors before runtime. The Callable type hint specifies that operation must be a function that takes two floats and returns a float. Union[float, str] indicates that the function can return either a float or a string (for the division by zero case). The divide function itself now only handles division; the main function now takes responsibility for error checking. This promotes single responsibility principle. Importantly, using Callable is more precise than just using function.