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)
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube