HackerRank Day 17 Solution in Python: More Exceptions

Today we will see the HackerRank Day 17 Solution in Python. The problem is named More Exceptions, part of 30 Days of code on HackerRank. Let’s get started!

Day 17: More Exceptions Problem statement

We have to write a Calculator class with a method, power. The power method takes two integers as parameters and returns the integer result of the first integer power second integer. If either the first integer or second integer is negative, then the method must throw an exception

Sample Input

2
3 5
-1 -3

Sample Output

243
n and p should be non-negative

Explanation

The first input indicates the number of test cases. The first test case gives the power of 3 raised by 5 as output. The second test case gives output as n and p should be non-negative since the input contains negative integers.

You can solve the problem here.

HackerRank Day 17 Solution in Python

#Calculator class
class Calculator:
    
    #Method to calculate power
    def power(self,n,p):
        self.n = n
        self.p = p
        
        #If input contains negative value 
        if n<0 or p<0:
            raise ValueError("n and p should be non-negative")
        
        #returns n power p value
        else:
            return n**p

#Object of Calculator class
myCalculator=Calculator()
T=int(input())
for i in range(T):
    n,p = map(int, input().split())
    try:
        ans=myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)   

Code Explanation

  • First, we created a class names Calculator
  • Then we created a method named power to calculate the power of two integers
  • If any one of the integers contains a negative value then raise the Exception and print n and p should be non-negative
  • Otherwise, print the power value calculated from the integers

Also Read:

Share:

Author: Keerthana Buvaneshwaran