Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Implementing a Simple Calculator Class in Python

Implementing a Simple Calculator Class in Python

Document Object Reference Manual Python3 Examples

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

(

)

print

(

"Addition: "

,

calc.

add

(

10

,

5

)

)

print

(

"Subtraction: "

,

calc.

subtract

(

10

,

5

)

)

print

(

"Multiplication: "

,

calc.

multiply

(

10

,

5

)

)

print

(

"Division: "

,

calc.

divide

(

10

,

5

)

)

Code analysis:

Output result:

Addition:  15
Subtraction:  5
Multiplication:  50
Division:  2.0

This simple calculator class performs basic arithmetic, and exception handling makes division safe.

Document Object Reference Manual Python3 Examples