Build a Safe Calculator
Advanced · Write the code · from Python Try-Except: Handle Errors Without Crashing
From the lesson: Python Try-Except: Handle Errors Without Crashing
Imagine a trapeze artist performing high above the ground. No matter how skilled they are, there's always a safety net below. If they slip, the net catches them and they can climb back up and try again.
Read the lessonWrite a function called calculate(expression) that takes a string like "10 + 5" and returns the result. It should:
1. Split the expression into parts (number, operator, number)
2. Support +, -, *, / operators
3. Handle these errors:
- ValueError if the numbers can't be converted: print "Invalid numbers in expression"
- ZeroDivisionError for division by zero: print "Cannot divide by zero"
- For any unknown operator, raise a ValueError with message "Unknown operator: X"
4. Use else to print "Result: X" on success
5. Use finally to print "Calculation complete"
Test with: "10 + 5", "20 / 0", and "abc + 2"
More Try-Except exercises
- Safe DivisionBeginner
- Predict the OutputBeginner
- Fix the Number ConverterIntermediate
- Input Validator with raiseIntermediate
- Safe Dictionary LookupAdvanced
All Python exercises · 50 practice problems · Error Handling quiz