Answer to Question #171648 in Python for Andu

Question #171648

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".


1
Expert's answer
2021-03-14T18:45:24-0400
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','/'))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS