MarkK
MarkK

Reputation: 1088

Python checking for negative values

Take the following code below. It should raise and error if the value (int) is a negative value:

if up_votes > 0 or down_votes > 0:
   raise ValueError('cannot be negative.')

However, when I input up_votes=100 and down_votes=100 this evaluates as True. Why?

Upvotes: 0

Views: 136

Answers (1)

The6thSense
The6thSense

Reputation: 8335

It should be like this

You are using the greater than sign [>] instead of lesser then sign [<]

if up_votes < 0 or down_votes < 0:
  raise ValueError('cannot be negative.')

Sample:

up_votes=-10
down_votes=-10
if up_votes < 0 or down_votes < 0:
raise ValueError('cannot be negative.')

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-2b318d5e4006> in <module>()
    1 up_votes=-10
    2 if up_votes < 0 or down_votes < 0:
----> 3   raise ValueError('cannot be negative.')
    4 

ValueError: cannot be negative.

A more generic sample:

1<0
False

-1<0
True

Upvotes: 3

Related Questions