Organize Your Python Code with a Modular Calculator

Building a Modular Python Calculator

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.

Project Structure


    simple_calculator/
    ├── main.py             # Main file (entry point)
    ├── operations.py       # Contains mathematical operations
    ├── input_handler.py    # Handles user input and validation
    

Code Breakdown

Main File: main.py


    # 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()
    
  • Main Functionality: The main.py acts as the entry point, importing and using functions from other modules.
  • Loop for Continuity: The program keeps running until the user decides to quit.
Understanding if __name__ == "__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 Module: operations.py


    # 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
    
  • Separate Operations: Each function handles a specific arithmetic operation.
  • Error Handling: The divide function includes a check for division by zero.

Input Handler Module: input_handler.py


    # 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 (+, -, *, /).")
    
  • User Input: Functions validate user input for numbers and operations.
  • Error Prevention: Ensures invalid inputs do not crash the program.

How It Works

  • The main.py serves as the "home page," coordinating functionality across the project.
  • The operations.py contains all arithmetic logic, ensuring separation of concerns.
  • The input_handler.py validates user input, preventing invalid or unsafe operations.

Advantages of Modular Programming

  • Improved Maintainability: Changes in one module do not affect the others.
  • Reusability: Modules like operations.py can be reused in other projects.
  • Scalability: Adding new features, such as additional operations, is straightforward.

Online Classes on Python Basics More on Modules and Packages

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer