-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex-try-except-write-calculator.py
More file actions
42 lines (31 loc) · 1.15 KB
/
ex-try-except-write-calculator.py
File metadata and controls
42 lines (31 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class FormulaError(Exception):
pass
def calculate(formula):
try:
values = formula.split()
# If the input does not consist of 3 elements, raise a FormulaError, which is a custom Exception
if len(values) != 3:
raise FormulaError("Invalid formula")
# convert the first and third input to a float
num1 = float(values[0])
operator = values[1]
num2 = float(values[2])
# catch ValueError that occurs, and instead raise a FormulaError
if operator not in ['+', '-']:
raise FormulaError("Invalid operator")
if operator == '+':
result = num1 + num2
else:
result = num1 - num2
print("Result:", result)
except ValueError:
# If the second input is not '+' or '-', again raise a FormulaError
raise FormulaError("Invalid value")
while True:
user_input = input("Enter a formula (e.g., 1 + 1), or 'quit' to exit: ")
if user_input.lower() == 'quit' or user_input.lower() == 'q':
break
try:
calculate(user_input)
except FormulaError as e:
print("Error:", e)