Python Command-Line Calculator Tutorial
This tutorial will guide you through building a simple command-line calculator in Python. We’ll focus on building the calculator step by step, reinforcing fundamental Python concepts along the way.
Example 1: Basic Addition
Our first goal is to create a calculator that can add two numbers. We’ll start with the core addition functionality.
def add(x, y):
"""This function takes two numbers, x and y, and returns their sum."""
return x + y
# Get input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Calculate the sum
result = add(num1, num2)
# Print the result
print("The sum is:", result)
Explanation:
- We define a function called `add` that takes two arguments, `x` and `y`.
- Inside the function, we return the sum of `x` and `y`.
- We use the `input()` function to get the first number from the user and convert it to a floating-point number using `float()`. This allows us to handle decimal numbers.
- We do the same for the second number.
- We call the `add` function with `num1` and `num2` as arguments and store the returned sum in the `result` variable.
- Finally, we use the `print()` function to display the result to the user.
Common Mistakes & Corrections:
- Error: `TypeError: unsupported operand type(s) for +: ‘str’ and ‘str’` – This occurs if you try to add a string to a string directly. Correction: We use `float()` to convert the input strings to numbers before adding.
# Example Execution:
# Enter the first number: 5
# Enter the second number: 3
# The sum is: 8.0
Output:
Enter the first number: 5
Enter the second number: 3
The sum is: 8.0
Example 2: Adding Support for Subtraction
Now, let’s extend our calculator to perform subtraction. We’ll modify the previous code to include a `subtract` function.
def add(x, y):
"""This function takes two numbers, x and y, and returns their sum."""
return x + y
def subtract(x, y):
"""This function takes two numbers, x and y, and returns their difference."""
return x - y
# Get input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Calculate the result (addition or subtraction)
operation = input("Enter operation (+ or -): ")
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
else:
print("Invalid operation")
exit()
# Print the result
print("The result is:", result)
Explanation:
- We define a new function called `subtract` that takes two arguments, `x` and `y`, and returns their difference.
- We prompt the user to enter the operation they want to perform (+ or -).
- We use an `if-elif-else` statement to check the value of `operation`.
- If `operation` is ‘+’, we call the `add` function and store the result.
- If `operation` is ‘-‘, we call the `subtract` function and store the result.
- If `operation` is neither ‘+’ nor ‘-‘, we print an error message and exit the program.
- Finally, we print the calculated result.
# Example Execution:
# Enter the first number: 10
# Enter the second number: 4
# Enter operation (+ or -): -
# The result is: 6.0
Output:
Enter the first number: 10
Enter the second number: 4
Enter operation (+ or -): -
The result is: 6.0
Example 3: Adding Multiplication and Division
Let’s extend the calculator further to include multiplication and division operations. We’ll add functions for these operations and handle potential errors like division by zero.
def add(x, y):
"""This function takes two numbers, x and y, and returns their sum."""
return x + y
def subtract(x, y):
"""This function takes two numbers, x and y, and returns their difference."""
return x - y
def multiply(x, y):
"""This function takes two numbers, x and y, and returns their product."""
return x y
def divide(x, y):
"""This function takes two numbers, x and y, and returns their quotient.
Handles division by zero.
"""
if y == 0:
print("Error: Division by zero!")
return None # Return None to indicate an error
else:
return x / y
# Get input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Get the operation
operation = input("Enter operation (+, -, , /): ")
# Calculate the result
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
elif operation == '':
result = multiply(num1, num2)
elif operation == '/':
result = divide(num1, num2)
else:
print("Invalid operation")
exit()
# Print the result
if result is not None:
print("The result is:", result)
Explanation:
- We define functions `multiply` and `divide` similar to `add` and `subtract`.
- The `divide` function includes error handling to prevent division by zero. It checks if `y` is equal to 0. If it is, it prints an error message and returns `None`.
- The main part of the program uses an `if-elif-else` statement to choose the appropriate function based on the user’s input.
- We added a check `if result is not None:` to handle the case when division by zero occurred.
# Example Execution:
# Enter the first number: 8
# Enter the second number: 2
# Enter operation (+, -, , /):
# The result is: 16.0
#
# Enter the first number: 10
# Enter the second number: 0
# Enter operation (+, -, , /): /
# Error: Division by zero!
#
# Enter the first number: 5
# Enter the second number: 2
# Enter operation (+, -, , /): /
# The result is: 2.5
Output:
Enter the first number: 8
Enter the second number: 2
Enter operation (+, -, , /):
The result is: 16.0
Enter the first number: 10
Enter the second number: 0
Enter operation (+, -, , /): /
Error: Division by zero!
Enter the first number: 5
Enter the second number: 2
Enter operation (+, -, , /): /
The result is: 2.5



Leave a Reply