Python: Build a Simple Command-Line Calculator

Python Command-Line Calculator Tutorial

Python Command-Line Calculator Tutorial

This tutorial will guide you through building a simple command-line calculator using Python. We’ll focus on building the calculator step-by-step, explaining the code as we go. This is a great way to learn Python fundamentals like input/output, variables, and basic arithmetic.

Step 1: Getting Started – Basic Input and Calculation

Our first version will handle addition and subtraction. We’ll prompt the user to enter two numbers and an operation (+ or -), then calculate and display the result. Let’s start with the code:


# Get user input
num1 = float(input("Enter the first number: "))
operator = input("Enter the operator (+ or -): ")
num2 = float(input("Enter the second number: "))

# Perform the calculation
if operator == '+':
    result = num1 + num2
elif operator == '-':
    result = num1 - num2
else:
    print("Invalid operator. Please use '+' or '-'.")
    result = None  # Set result to None to avoid errors

# Display the result
if result is not None:
    print("Result:", result)

Explanation:

  • We use the `input()` function to get the user’s input.
  • `float()` converts the input strings to floating-point numbers. This allows us to handle decimal numbers.
  • We use `if/elif/else` statements to check the operator and perform the appropriate calculation.
  • We print the `result` using `print()`.
  • We added a check for invalid operators and set `result` to `None` to prevent errors if the user enters something other than ‘+’ or ‘-‘.

Example Execution:

Enter the first number: 10
Enter the operator (+ or -): +
Enter the second number: 5
Result: 15.0

Common Mistakes & Corrections:

  • Error: `TypeError: unsupported operand type(s) for +: ‘str’ and ‘float’` Correction: Ensure you are using `float()` to convert the input to a number before performing the addition.
  • Error: The program crashes if the user enters an invalid operator. Correction: We added an `else` block to handle invalid operators and set `result` to `None`.

Step 2: Adding Multiplication and Division

Now, let’s extend the calculator to include multiplication and division. We’ll modify our existing code to support these operations.


# Get user input
num1 = float(input("Enter the first number: "))
operator = input("Enter the operator (+, -, , /): ")
num2 = float(input("Enter the second number: "))

# Perform the calculation
if operator == '+':
    result = num1 + num2
elif operator == '-':
    result = num1 - num2
elif operator == '':
    result = num1  num2
elif operator == '/':
    if num2 == 0:
        print("Cannot divide by zero!")
        result = None
    else:
        result = num1 / num2
else:
    print("Invalid operator. Please use +, -, , or /.")
    result = None

# Display the result
if result is not None:
    print("Result:", result)

Explanation:

  • We added `elif` blocks for multiplication (“) and division (`/`).
  • For division, we added a check to prevent division by zero. If `num2` is 0, we print an error message and set `result` to `None`.

Example Execution:

Enter the first number: 8
Enter the operator (+, -, , /): 
Enter the second number: 3
Result: 24.0

Example Execution (Division by Zero):

Enter the first number: 10
Enter the operator (+, -, , /): /
Enter the second number: 0
Cannot divide by zero!

Step 3: Handling More Complex Calculations

Let’s add more robustness. We can extend this calculator to handle more complex calculations, such as order of operations (PEMDAS/BODMAS), although a fully functional calculator would require a more sophisticated approach. We’ll also add a function to re-run the calculator if the user desires.


def calculator():
    while True:
        # Get user input
        try:
            num1 = float(input("Enter the first number: "))
        except ValueError:
            print("Invalid input. Please enter a number.")
            continue

        operator = input("Enter the operator (+, -, , /): ")
        try:
            num2 = float(input("Enter the second number: "))
        except ValueError:
            print("Invalid input. Please enter a number.")
            continue
        
        # Perform the calculation
        if operator == '+':
            result = num1 + num2
        elif operator == '-':
            result = num1 - num2
        elif operator == '':
            result = num1  num2
        elif operator == '/':
            if num2 == 0:
                print("Cannot divide by zero!")
                result = None
            else:
                result = num1 / num2
        else:
            print("Invalid operator.")
            result = None
        
        # Display the result
        if result is not None:
            print("Result:", result)

        another_calculation = input("Do you want to perform another calculation? (yes/no): ")
        if another_calculation.lower() != 'yes':
            break
    print("Calculator exiting.")

# Start the calculator
calculator()

Explanation:

  • We encapsulate the calculator logic within a function called `calculator()`.
  • We use `try…except` blocks to handle potential `ValueError` exceptions if the user enters non-numeric input.
  • We added a loop that continuously prompts the user for input and performs calculations until the user types ‘no’.
  • We improved input validation with `try…except` blocks, providing user-friendly error messages.

Example Execution:

Enter the first number: 5
Enter the operator (+, -, , /): +
Enter the second number: 3
Result: 8.0
Do you want to perform another calculation? (yes/no): yes
Enter the first number: 10
Enter the operator (+, -, , /): /
Enter the second number: 2
Result: 5.0
Do you want to perform another calculation? (yes/no): no
Calculator exiting.

Leave a Reply

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

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.