0

I want to raise an Value Error for negative values of a and b. I have played around with this but it raises ValueError for different values and it does not seem to work properly.

class RightTriangle:
    def __init__(self, a, b):
            self.a = a
            self.b = b
            self.c = np.sqrt(a**2+b**2)

            if (self.a or self.b) < 0:
                raise ValueError("Negative")
multiib
  • 13
  • 1
  • 3
  • Does this answer your question? [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – G. Anderson Oct 20 '20 at 16:27
  • Use the Pipe character '''|''' the do the "A or B" operation. – Martial P Oct 20 '20 at 16:32
  • 1
    @MartialP While you're correct doing a bitwise OR before the inequality would fix this problem, I think it's worse for clarity and readability. I wouldn't use bitwise operations except where they're required, and this is definitely a case where they aren't. – Macattack Oct 20 '20 at 16:38

1 Answers1

2

Fix:

if self.a < 0 or self.b < 0:

What you've got is evaluating (self.a or self.b) first. What this first part is doing is this:

if self.a: # anything but 0 is True
    return self.a
else:
    return self.b

So, you're probably going to get self.a most of the time, and then it's going to be compared in < 0.

Macattack
  • 1,917
  • 10
  • 15