如何在Python的assert语句中使用小于和等于

5 投票
5 回答
19604 浏览
提问于 2025-04-16 03:23

当我运行下面的代码时:

growthRates = [3, 4, 5, 0, 3]
for each in growthRates:
    print each
    assert growthRates >= 0, 'Growth Rate is not between 0 and 100'
    assert growthRates <= 100, 'Growth Rate is not between 0 and 100'

我得到的结果是:

3
Traceback (most recent call last):
  File "ps4.py", line 132, in <module>
    testNestEggVariable()
  File "ps4.py", line 126, in testNestEggVariable
    savingsRecord = nestEggVariable(salary, save, growthRates)
  File "ps4.py", line 106, in nestEggVariable
    assert growthRates <= 100, 'Growth Rate is not between 0 and 100'
AssertionError: Growth Rate is not between 0 and 100

这是为什么呢?

5 个回答

4

这段代码的意思是:我们在检查每个值是否都大于等于0。用简单的话说,就是我们希望确保每个值都是非负的(也就是0或更大)。

而后面那句“not assert (growthRates >= 0)”则表示我们不想检查“增长率是否大于等于0”。这句话带着一点幽默的语气,意思是说我们不关心增长率的情况。

6
assert 0 <= each <= 100, 'Growth Rate %i is not between 0 and 100.' % each

你的断言当然不会失败,但现在的 growthRates > 100 是因为 growthRates 是一个列表,而 0 是一个整数。在比较时,'列表' 是大于 '整数' 的。

15

要做的:

assert each >= 0, 'Growth Rate is not between 0 and 100'

不要做的:

assert growthRates >= 0, 'Growth Rate is not between 0 and 100'

撰写回答