Task 2:
Write a Python class named "Calculator" that has no attributes.The class has only one method named "performOperation()" that takes in input three parameters, two numeric values (A and B) and one string value representing one of the four basic mathematical operations (+","", "*" or "/"). For each operation, it returns the result of the respective operation for the two numbers. In case the second value is zero and the operation is "/", the method returns a string message "Error: Can not divide by zero". If the operation is not as expected, the method returns a string message "Error: Operation not supported".
class Calculator():
def performOperation(self,A,B,operation):
try:
if operation == '+':
return A + B
elif operation == '-':
return A - B
elif operation == '*':
return A * B
elif operation == '/':
return A / B
except ZeroDivisionError:
return "Error: Can not divide by zero"
except TypeError:
return "Error: Operation not supported"
a = Calculator()
print(a.performOperation(1,2,'/'))
print(a.performOperation(1,2,'*'))
print(a.performOperation(1,2,'+'))
print(a.performOperation(1,2,'-'))
print(a.performOperation(1,0,'/'))
print(a.performOperation(1,'a','/'))
Comments
Leave a comment