In this tutorial, we will create a simple calculator using Python, organized into multiple files to demonstrate modular programming. This approach ensures a clean and maintainable structure by dividing responsibilities across different modules.
simple_calculator/
├── main.py # Main file (entry point)
├── operations.py # Contains mathematical operations
├── input_handler.py # Handles user input and validation
# main.py
from operations import add, subtract, multiply, divide
from input_handler import get_number, get_operation
def main():
"""Main function to run the calculator."""
print("Welcome to the Simple Modular Calculator!")
while True:
num1 = get_number("Enter the first number: ")
num2 = get_number("Enter the second number: ")
operation = get_operation()
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
elif operation == '*':
result = multiply(num1, num2)
elif operation == '/':
result = divide(num1, num2)
else:
print("Invalid operation.")
continue
print(f"The result of {num1} {operation} {num2} is: {result}")
choice = input("Do you want to perform another calculation? (yes/no): ").lower()
if choice != 'yes':
print("Thank you for using the calculator. Goodbye!")
break
if __name__ == "__main__":
main()
The if __name__ == "__main__":
statement is crucial for creating reusable and modular Python scripts. It ensures that the main()
function runs only when the script is executed directly, and not when it is imported as a module into another program. This practice enhances code clarity and allows functions to be reused across projects without triggering unnecessary behavior.
# operations.py
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def subtract(a, b):
"""Returns the difference of two numbers."""
return a - b
def multiply(a, b):
"""Returns the product of two numbers."""
return a * b
def divide(a, b):
"""Returns the quotient of two numbers. Handles division by zero."""
if b == 0:
return "Error: Division by zero!"
return a / b
# input_handler.py
def get_number(prompt):
"""Prompts the user for a number and validates the input."""
while True:
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a valid number.")
def get_operation():
"""Prompts the user to choose an operation."""
while True:
operation = input("Choose an operation (+, -, *, /): ").strip()
if operation in ('+', '-', '*', '/'):
return operation
print("Invalid operation. Please choose one of (+, -, *, /).")