CREATE A CALCULATOR USING PYTHON

FEATURE OF CALCULATOR

New Features:

  1. Support for Exponentiation (^)
    Allows the user to calculate powers (e.g., 2^3 = 8).
  2. Support for Modulus (%)
    Provides the remainder when dividing two numbers (e.g., 10 % 3 = 1).
  3. Error Handling for Invalid Inputs
    Ensures users only input valid operations and numbers.
  4. Loop for Multiple Calculations
    The calculator will continue running until the user decides to exit.
  5. Formatted Output
    Adds formatting to improve the user experience.
def calculator():
    print("\nWelcome to the Advanced Calculator!")
    print("Supported Operations:")
    print("+  : Addition")
    print("-  : Subtraction")
    print("*  : Multiplication")
    print("/  : Division")
    print("^  : Exponentiation")
    print("%  : Modulus (Remainder)")
    print("Type 'exit' to quit the calculator.\n")

    while True:
        # Prompt the user for the operation
        operation = input("Enter operation (+, -, *, /, ^, %) or 'exit' to quit: ").strip()

        # Exit condition
        if operation.lower() == 'exit':
            print("Thank you for using the calculator. Goodbye!")
            break

        # Validate operation
        if operation not in ['+', '-', '*', '/', '^', '%']:
            print("Invalid operation. Please choose a valid operation.\n")
            continue

        # Input numbers with validation
        try:
            num1 = float(input("Enter the first number: "))
            num2 = float(input("Enter the second number: "))

            # Perform the operation
            if operation == '+':
                result = num1 + num2
            elif operation == '-':
                result = num1 - num2
            elif operation == '*':
                result = num1 * num2
            elif operation == '/':
                if num2 != 0:
                    result = num1 / num2
                else:
                    print("Error: Division by zero is not allowed.\n")
                    continue
            elif operation == '^':
                result = num1 ** num2
            elif operation == '%':
                if num2 != 0:
                    result = num1 % num2
                else:
                    print("Error: Division by zero is not allowed.\n")
                    continue

            # Display the result
            print(f"The result of {num1} {operation} {num2} is: {result}\n")

        except ValueError:
            print("Invalid input. Please enter valid numbers.\n")

# Run the calculator
calculator()
Python

Leave a Reply

Your email address will not be published. Required fields are marked *


error: Content is protected !!
Scroll to Top
MacroNepal
Verified by MonsterInsights