2

I am having following issue with my code in propagating an Exception:

What the code should do:

It takes an input for number a of combinations or Test Cases to be run.

It takes n = number and its power = p. (i.e 2^3=8)

If p and n are positive, it needs to print 2^3 = 8 and return it - this is working.

If either n or p is negative, it needs to print "n and p should be non-negative" - this is not working.

My code:

class Calculator():
    def power(self,n,p):
        self.n=n
        self.p=p
        try:
            raise NameError("n and p should be non-negative")

        except NameError:
            a=pow(n,p)
            return a
myCalculator=Calculator()
T=int(raw_input())
for i in range(T):
    n,p = map(int, raw_input().split())
    try:
        ans=myCalculator.power(n,p)
        print ans
    except Exception,e:
        print e 

Input given

4
3 5
2 4
-1 -2
-1 3

Output received:

243
16
1.0
-1

However, I should have received "n and p should be non-negative" for 3rd and 4th Test Case as last 2 Test Cases(Test Case number 3 and 4) had either of the values set to negative.

What is wrong?

1
  • You're not actually testing for the values to be positive.. Commented May 17, 2016 at 17:55

1 Answer 1

1

You're not actually checking the values. Do you want something like that?

class Calculator():
    def power(self,n,p):
        self.n=n
        self.p=p
        if n<0 or p<0:
            raise NameError("n and p should be non-negative")
        a=pow(n,p)
        return a

A NameError doesn't make much sense though, replace it with ValueError.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried the other way round as well earlier but that didn't worked either , please forgive as i am a new-bee: class Calculator(): def power(self,n,p): self.n=n self.p=p try: if n>0 and p>0: a=pow(n,p) return a except ValueError,e: print "n and p should be non negative" : I will try your code and let you know
yes you are absolutely right , i figured my mistake and found out what i was doing wrong . Kudos to you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.