FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-testing-101/calculator.py at master · python-frederick/python-testing-101 · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
python-frederick
/
python-testing-101
Public
Notifications
You must be signed in to change notification settings
Fork
4
Star
9
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
python-testing-101
/
calculator.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
64 lines (50 loc) · 1.7 KB
Breadcrumbs
python-testing-101
/
calculator.py
Copy path
File metadata and controls
64 lines (50 loc) · 1.7 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
)
Back
|
FazBrowse Home
|
New Git URL