Here’s a step-by-step explanation to create a simple calculator in Python:
“`python
# Simple Calculator in Python
# 1. Get user input
num1 = input(“Enter first number: “)
operator = input(“Enter operator (+, -, *, /): “)
num2 = input(“Enter second number: “)
try:
# 2. Convert to float numbers
num1 = float(num1)
num2 = float(num2)
# 3. Perform calculation based on operator
if operator == ‘+’:
result = num1 + num2
elif operator == ‘-‘:
result = num1 – num2
elif operator == ‘*’:
result = num1 * num2
elif operator == ‘/’:
if num2 == 0:
# 4. Handle division by zero
print(“Error: Division by zero!”)
else:
result = num1 / num2
else:
# 5. Handle invalid operator
print(“Invalid operator!”)
result = None
# 6. Display result if valid
if result is not None:
print(f”{num1} {operator} {num2} = {round(result, 2)}”)
except ValueError:
# Handle invalid number input
print(“Invalid number input! Please enter valid numbers.”)
“`
**Key Features:**
1. Basic arithmetic operations (+, -, *, /)
2. Error handling for:
– Non-numeric inputs
– Division by zero
– Invalid operators
3. Rounded results to 2 decimal places
4. User-friendly prompts
**How to Use:**
1. Run the program
2. Enter first number
3. Choose an operator
4. Enter second number
5. Get calculated result
**Example Output:**
“`shell
Enter first number: 5
Enter operator (+, -, *, /): *
Enter second number: 3
5.0 * 3.0 = 15.0
“`
This calculator handles basic operations while including essential error checking for common user input mistakes. You can expand it by adding more operations (like exponentiation) or decimal precision control as needed.