Python Day 17: More Exceptions

Write a Calculator class with a single method: int power(int,int). The power method takes two integers, n and p, as parameters and returns the integer result of n^p. If either n or p is negative, then the method must throw an exception with the message: n and p should be non-negative

  1. #Write your code here
  2. class e(Exception):
  3. "n and p should be non-negative"
  4. class Calculator():
  5. def power(self, n, p):
  6. try:
  7. if n | p < 0:
  8. raise e
  9. else:
  10. return (n ** p)
  11. except e:
  12. return ("n and p should be non-negative")
  13. myCalculator=Calculator()
  14. T=int(input())
  15. for i in range(T):
  16. n,p = map(int, input().split())
  17. try:
  18. ans=myCalculator.power(n,p)
  19. print(ans)
  20. except Exception as e:
  21. print(e)