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 start with a basic version and progressively add functionality. We’ll focus on clear explanations and working code examples.

Example 1: Basic Addition

Our first goal is to create a calculator that can perform addition. We’ll start with a simple script that prompts the user for two numbers and displays their sum.


def add_numbers():
    try:
        num1 = float(input("Enter the first number: "))
        num2 = float(input("Enter the second number: "))
        sum_result = num1 + num2
        print("The sum is:", sum_result)
    except ValueError:
        print("Invalid input. Please enter numbers only.")

add_numbers()

Explanation:

  • We define a function called add_numbers to encapsulate our calculator logic.
  • We use input() to prompt the user for two numbers.
  • float() converts the input strings to floating-point numbers. This allows the calculator to handle decimal numbers.
  • We calculate the sum using the + operator.
  • We use print() to display the result.
  • We include a try-except block to handle potential ValueError exceptions if the user enters non-numeric input.

Common Mistake & Correction: A common mistake is forgetting to convert the input strings to numbers. The float() function is crucial for this.

Input:


Enter the first number: 10
Enter the second number: 5

Intermediate Values:


num1 = 10.0
num2 = 5.0
sum_result = 15.0

Output:


Enter the first number: 10
Enter the second number: 5
The sum is: 15.0

Example 2: Adding Support for Subtraction

Now, let’s extend our calculator to perform subtraction as well. We’ll modify the previous script to include a subtraction operation.


def calculate():
    try:
        num1 = float(input("Enter the first number: "))
        num2 = float(input("Enter the second number: "))
        operation = input("Enter the operation (+, -, or ): ")

        if operation == "+":
            result = num1 + num2
        elif operation == "-":
            result = num1 - num2
        elif operation == "":
            result = num1  num2
        else:
            print("Invalid operation.")
            return

        print("The result is:", result)

    except ValueError:
        print("Invalid input. Please enter numbers only.")

calculate()

Explanation:

  • We added an operation variable to store the user’s choice of operation (+, -, or ).
  • We use an if-elif-else block to handle the different operations.
  • We calculate the result based on the chosen operation.
  • We include error handling for invalid operation input.

Input:


Enter the first number: 20
Enter the second number: 8
Enter the operation (+, -, or ): -

Intermediate Values:


num1 = 20.0
num2 = 8.0
operation = "-"
result = 12.0

Output:


Enter the first number: 20
Enter the second number: 8
Enter the operation (+, -, or ): -
The result is: 12.0

Example 3: Adding Multiplication and a Simple Input Validation

Let’s expand our calculator to include multiplication and improve input validation to handle potential errors more gracefully. This example showcases a slightly more robust approach.


def calculate():
    try:
        num1 = float(input("Enter the first number: "))
        num2 = float(input("Enter the second number: "))
        operation = input("Enter the operation (+, -, , or /): ")

        if operation == "+":
            result = num1 + num2
        elif operation == "-":
            result = num1 - num2
        elif operation == "":
            result = num1  num2
        elif operation == "/":
            if num2 == 0:
                print("Error: Cannot divide by zero.")
                return
            result = num1 / num2
        else:
            print("Invalid operation.")
            return

        print("The result is:", result)

    except ValueError:
        print("Invalid input. Please enter numbers only.")

calculate()

Explanation:

  • We added support for division (`/`) and included a check to prevent division by zero.
  • We’ve refined the input validation to allow for division.
  • The `if-elif-else` block now handles division and checks for zero division.

Input:


Enter the first number: 15
Enter the second number: 3
Enter the operation (+, -, , or /): /

Intermediate Values:


num1 = 15.0
num2 = 3.0
operation = "/"
result = 5.0

Output:


Enter the first number: 15
Enter the second number: 3
Enter the operation (+, -, , or /): /
The result is: 5.0

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.