Python检查负值

2024-04-25 20:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

采用下面的代码。如果值(int)为负值,则会引发错误:

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

但是,当我输入up_votes=100down_votes=100时,它的计算结果是True。为什么?你知道吗


Tags: or代码if错误beintdownraise
1条回答
网友
1楼 · 发布于 2024-04-25 20:23:50

应该是这样的

您使用的是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

相关问题 更多 >