forked from python-frederick/python-testing-101
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.py
64 lines (50 loc) · 1.7 KB
/
calculator.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import numbers
class CalculatorError(Exception):
"""For calculator errors"""
class Calculator:
"""A terrible calculator."""
def add(self, a, b):
"""Add two numbers."""
self._check_operand(a)
self._check_operand(b)
return a + b
def subtract(self, a, b):
"""Subtract two numbers."""
return a - b
def multiply(self, a, b):
"""Multiply two numbers."""
return a * b
def divide(self, a, b):
"""Divide two numbers."""
try:
return a / b
except ZeroDivisionError as ex:
raise CalculatorError("You can't divide by zero.") from ex
def _check_operand(self, operand):
"""Check that the operand is a number."""
if not isinstance(operand, numbers.Number):
raise CalculatorError(f'"{operand}" is not a number.')
if __name__ == "__main__":
print("Let's calculate!")
print("Press Ctrl+C to quit.")
calculator = Calculator()
operations = {
"1": calculator.add,
"2": calculator.subtract,
"3": calculator.multiply,
"4": calculator.divide,
}
while True:
print("Pick a calculation:")
for choice, operation in sorted(operations.items()):
print(f"{choice}: {operation.__name__}")
operation = input("What operation? ")
if operation not in operations:
print("Sorry, that's not a valid choice.")
continue
a = float(input("Select first operand: "))
b = float(input("Select second operand: "))
try:
print("The result is: {}\n".format(operations[operation](a, b)))
except CalculatorError as error:
print(error)