Calculator¶
This is a very easy calculator by writing a class
import math
class Calculator:
"""A Calculator which has a list of results and the option to add, substract, divide, multiply, pow and squareroot"""
results = []
# init method
def __init__(self):
self.results = []
def add(self,a,b):
"""a and b must be numbers, the numbers will be added and returned. The result will be stored in the results history"""
self.results.append("%f + %f" % (a,b))
self.results.append(a+b)
return a+b
def substract(self,a,b):
"""a and b must be numbers, the numbers will be substaced and returned. The result will be stored in the results history"""
self.results.append("%f - %f" % (a,b))
self.results.append(a-b)
return a-b
def multiply(self,a,b):
"""a and b must be numbers, the numbers will be multiplied and returned. The result will be stored in the results history"""
self.results.append("%f * %f" % (a,b))
self.results.append(a*b)
return a*b
def divide(self,a,b):
"""a and b must be numbers, the numbers will be divided and returned. The result will be stored in the results history"""
self.results.append("%f / %f" % (a,b))
try:
temp_result = a/b
except ZeroDivisionError:
self.results.append("division by zero is not allowed")
return('division by zero is not allowed')
else:
self.results.append("the division is not possible")
return "the division is not possible"
self.results.append(temp_result)
return temp_result
def pow(self,a,b):
"""a and b must be numbers, a pow b will be calculated and returned. The result will be stored in the results history"""
self.results.append("%f ** %f" % (a,b))
self.results.append(pow(a,b))
return pow(a,b)
def sqrt(self,a):
"""a must be a number, squareroot of a will be calculated and returned. The result will be stored in the results history"""
self.results.append("sqrt(%f)" % (a))
self.results.append(math.sqrt(a))
return math.sqrt(a)
def print_history(self):
for i in self.results:
print(i)
calc = Calculator()
calc.add(3,4)
7
calc.add(2,4)
6
calc.divide(2,0)
'division by zero is not allowed'
calc.divide(4,2)
2.0
calc.multiply(3,4)
12
calc.substract(4,5)
-1
calc.pow(2,2)
4
calc.sqrt(4)
2.0
calc.print_history()
3.000000 + 4.000000
7
2.000000 + 4.000000
6
2.000000 / 0.000000
the division is not possible
4.000000 / 2.000000
2.0
3.000000 * 4.000000
12
4.000000 - 5.000000
-1
2.000000 ** 2.000000
4
sqrt(4.000000)
2.0
calc2 = Calculator()
calc2.add(3,3)
6
calc2.print_history()
3.000000 + 3.000000
6
calc2.add(2.3,4.1)
6.3999999999999995
calc.print_history()
3.000000 + 4.000000
7
2.000000 + 4.000000
6
2.000000 / 0.000000
the division is not possible
4.000000 / 2.000000
2.0
3.000000 * 4.000000
12
4.000000 - 5.000000
-1
2.000000 ** 2.000000
4
sqrt(4.000000)
2.0