Build a Simple Command-Line Calculator in Python
This tutorial will guide you through building a basic command-line calculator using Python. We’ll focus on building it step-by-step, adding functionality incrementally. This will help you understand the core concepts of Python programming, including user input, basic arithmetic operations, and handling different data types. We’ll build a calculator that can perform addition, subtraction, multiplication, and division.
Example 1: Basic Addition
Let’s start with a simple calculator that only performs addition. This will give you a foundation for building a more complex calculator.
# This program adds two numbers provided by the user.
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 the addition logic.
- `input()` prompts the user to enter two numbers.
- `float()` converts the input strings to floating-point numbers, allowing for decimal values.
- `num1 + num2` performs the addition.
- `print()` displays the result.
- `try…except` handles potential `ValueError` exceptions if the user enters non-numeric input.
Common Mistakes & Corrections:
- Mistake: Using `int()` instead of `float()`. `int()` will truncate decimal numbers.
- Correction: Using `float()` to allow for decimal numbers.
Expected Output:
Enter the first number: 10
Enter the second number: 5
The sum is: 15.0
Example 2: Adding Multiple Operations
Now, let’s extend the calculator to support multiple operations (addition, subtraction, multiplication, and division). We’ll use a loop to repeatedly ask the user for calculations until they choose to exit.
# This program performs calculations based on user input.
def calculate():
while True:
operation = input("Enter the operation (+, -, , /, or 'q' to quit): ")
if operation == 'q':
break
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
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!")
continue
result = num1 / num2
else:
print("Invalid operation.")
continue
print("The result is:", result)
except ValueError:
print("Invalid input. Please enter numbers only.")
calculate()
Explanation:
- We define a function called `calculate()` to manage the calculator’s operation.
- A `while True` loop keeps the calculator running until the user chooses to quit.
- The user is prompted to enter an operation (+, -, , /) or ‘q’ to quit.
- Input validation is performed to ensure the user enters a valid operation.
- The `try…except` block handles potential `ValueError` exceptions.
- Based on the operation entered, the calculation is performed. A check for division by zero is included.
- The result is printed to the console.
Expected Output:
Enter the operation (+, -, , /, or 'q' to quit): +
Enter the first number: 5
Enter the second number: 3
The result is: 8.0
Enter the operation (+, -, , /, or 'q' to quit): /
Enter the first number: 10
Enter the second number: 2
The result is: 5.0
Enter the operation (+, -, , /, or 'q' to quit): q
Example 3: Adding Error Handling and Improved Input
Let’s add more robust error handling and improve the user input experience by prompting for the operator first.
# This program performs calculations with improved error handling.
def calculate():
while True:
operation = input("Enter the operation (+, -, , /, or 'q' to quit): ")
if operation == 'q':
break
if operation not in ['+', '-', '', '/', 'q']:
print("Invalid operation. Please try again.")
continue
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
except ValueError:
print("Invalid input. Please enter numbers only.")
continue
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!")
continue
result = num1 / num2
print("The result is:", result)
calculate()
Explanation:
- We added a check to ensure the operation is valid before proceeding.
- The `try…except` block remains to handle potential `ValueError` exceptions.
- The division by zero check remains.
Expected Output:
Enter the operation (+, -, , /, or 'q' to quit): +
Enter the first number: 7
Enter the second number: 2
The result is: 9.0
Enter the operation (+, -, , /, or 'q' to quit): /
Enter the first number: 15
Enter the second number: 0
Error: Division by zero!
Enter the operation (+, -, , /, or 'q' to quit): q



Leave a Reply