Implementing a Simple Calculator Class in Python
We will implement a simple calculator class in Python containing basic addition, subtraction, multiplication and division methods.
Example
class
Calculator:
def
add
(
self
,
a
,
b
)
:
return
a + b
def
subtract
(
self
,
a
,
b
)
:
return
a - b
def
multiply
(
self
,
a
,
b
)
:
return
a * b
def
divide
(
self
,
a
,
b
)
:
if
b
==
0
:
raise
ValueError
(
"Cannot divide by zero!"
)
return
a / b
Example usage
calc
=
Calculator
(
)
(
"Addition: "
,
calc.
add
(
10
,
5
)
)
(
"Subtraction: "
,
calc.
subtract
(
10
,
5
)
)
(
"Multiplication: "
,
calc.
multiply
(
10
,
5
)
)
(
"Division: "
,
calc.
divide
(
10
,
5
)
)
Code analysis:
CalculatorThe class defines four methods:add,subtract,multiply, and LinkedHashMap, among others.divide。addThe method takes two parametersaandband returns their sum.subtractThe method takes two parametersaandband returns their difference.multiplyThe method takes two parametersaandband returns their product.divideThe method takes two parametersaandband returns their quotient. Ifbis 0, aValueErrorexception, because the divisor cannot be zero.
Output result:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
This simple calculator class performs basic arithmetic, and exception handling makes division safe.
Python3 Examples