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 features. The goal is to understand the core concepts of user input, calculations, and output in Python.

Example 1: Basic Addition

Let’s start with the most fundamental operation: addition. This example will take two numbers as input from the user and print 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.
  • `input()` prompts the user to enter the first number.
  • `float()` converts the input string to a floating-point number. This allows us to handle decimal numbers.
  • We add `num1` and `num2` to calculate the sum.
  • `print()` displays the result to the user.
  • We use a `try…except` block to handle potential `ValueError` exceptions. This happens if the user enters non-numeric input.

Common Mistakes:

  • TypeError: This can occur if you attempt to perform mathematical operations on a string instead of a number. Make sure to convert your input to a numeric type (e.g., `float`, `int`).
  • SyntaxError: Incorrect syntax in your code will prevent it from running. Double-check your code for typos and ensure that your statements are correctly formatted.

Output:


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

Example 2: Adding Subtraction, Multiplication, and Division

Now, let’s extend our calculator to include subtraction, multiplication, and division. We’ll add more input prompts and perform the appropriate operation based on user selection.


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

        if operation == '+':
            result = num1 + num2
        elif operation == '-':
            result = num1 - num2
        elif operation == '':
            result = num1  num2
        elif operation == '/':
            if num2 == 0:
                print("Error: Division by zero!")
                result = None
            else:
                result = num1 / num2
        else:
            print("Invalid operation!")
            result = None

        if result is not None:
            print("The result is:", result)

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

calculate()

Explanation:

  • We add an `operation` input to allow the user to choose the desired operation.
  • We use `if…elif…else` statements to execute the appropriate calculation based on the selected operation.
  • We include error handling for division by zero.
  • We check if `result` is `None` before printing, avoiding printing `None` when an error occurs.

Output:


Enter the first number: 20
Enter the second number: 4
Enter the operation (+, -, , /): +
The result is: 24.0

Enter the first number: 10
Enter the second number: 0
Enter the operation (+, -, , /): /
Error: Division by zero!

Enter the first number: 5
Enter the second number: 2
Enter the operation (+, -, , /): ^
Invalid operation!

Example 3: Implementing Input Validation

Let’s refine our calculator to provide better input validation. This example will check if the user enters valid numeric input before proceeding.


def validate_input():
    try:
        num = float(input("Enter a number: "))
        return num
    except ValueError:
        print("Invalid input. Please enter a valid number.")
        return None

def calculate_with_validation():
    num1 = validate_input()
    if num1 is None:
        return

    num2 = validate_input()
    if num2 is None:
        return

    operation = input("Enter the operation (+, -, , /): ")

    if operation == '+':
        result = num1 + num2
    elif operation == '-':
        result = num1 - num2
    elif operation == '':
        result = num1  num2
    elif operation == '/':
        if num2 == 0:
            print("Error: Division by zero!")
            return
        result = num1 / num2
    else:
        print("Invalid operation!")
        return

    print("The result is:", result)

calculate_with_validation()

Explanation:

  • We create a `validate_input()` function that attempts to convert the user’s input to a float. If it’s not a valid number, it prints an error message and returns `None`.
  • We call `validate_input()` twice to get the two numbers from the user.
  • If either input is invalid (i.e., `None`), we exit the function to avoid further calculations.
  • The rest of the calculation logic is the same as in Example 2.

Output:


Enter a number: 10
Enter the operation (+, -, , /): +
Enter a number: 5
The result is: 15.0

Enter a number: abc
Invalid input. Please enter a valid number.
Enter a number: 20
Enter the operation (+, -, , /): /
Enter a number: 0
Error: Division by zero!

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.