Python检查负值

时间:2015-08-26 09:56:15

标签: python

请使用以下代码。如果值(int)是负值,它应该引发错误:

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

但是,当我输入up_votes=100down_votes=100时,评估为True。为什么?

1 个答案:

答案 0 :(得分:3)

应该是这样的

您使用greater than sign [>]代替lesser then sign [<]

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

<强>示例:

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.

更通用的示例:

1<0
False

-1<0
True