Python Write a Class to Implement Addition, Subtraction, Multiplication and Division
We will write a class named Calculator containing four methods:add(addition),subtract(subtraction),multiply(multiplication) and divide(division). These methods take two numbers as arguments and return the corresponding result.
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
Code analysis:
add(self, a, b): this method takes two parametersaandband returns their sum.subtract(self, a, b): this method takes two parametersaandband returns their difference.multiply(self, a, b): this method takes two parametersaandband returns their product.divide(self, a, b): this method takes two parametersaandband returns their quotient. Ifbis 0, it raises aValueErrorexception, because the divisor cannot be zero.
Output result:
Example
calc
=
Calculator
(
)
(
calc.
add
(
10
,
5
)
)
Output: 15
(
calc.
subtract
(
10
,
5
)
)
Output: 5
(
calc.
multiply
(
10
,
5
)
)
Output: 50
(
calc.
divide
(
10
,
5
)
)
Output: 2.0
This class can be used for basic arithmetic, and exception handling makes division safe.
Python3 Examples