Console Calculator Program
🎯 Project: Console Calculator
In this lesson, you'll build a fully functional calculator program that performs basic arithmetic operations. This project will help you practice using if statements, handling user input, and managing edge cases.
The calculator will accept two numbers and an operator (+, -, *, /) and display the result. We'll also implement error handling for invalid inputs and division by zero.
Project Requirements
Your calculator should meet these requirements:
- Accept two numbers from the user (or use predefined values for testing)
- Accept an operator (+, -, *, /)
- Perform the correct calculation based on the operator
- Handle division by zero with a clear error message
- Handle invalid operators with an error message
- Display the result in a clear format
Basic Calculator Structure
Here's a basic structure using if-elif statements to handle different operators:
Enhanced Calculator with Match Statement
You can also use a match statement for cleaner code (Python 3.10+):
Error Handling Tips
⚠️ Division by Zero
Always check if the divisor is zero before dividing. Division by zero will crash your program with a ZeroDivisionError.
✅ User-Friendly Messages
Provide clear, helpful error messages when something goes wrong. This makes your program more user-friendly and easier to debug.
Advanced: Multiple Operations
You can extend the calculator to handle multiple operations or additional operators: