当我运行以下内容时:

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

这是为什么?

有帮助吗?

解决方案

做:

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

不是:

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

其他提示

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

当然,您的断言不会失败,但是现在成长> 100,因为成长为列表,而0是整数和“列表”>“整数”。

assert (each >= 0)不是 assert (growthRates >= 0) :-)

您也可以使用:

growthRates = [0, 10, 100, -1]
assert all(0<=each<=100 for each in growthRates), 'growthRate is not between 0 and 100'

Traceback (most recent call last):
File "any.py", line 2, in <module>
assert all([0<=each<=100 for each in growthRates]), 'growthRate is not between 0 and 100'
AssertionError: growthRate is not between 0 and 100

测试每个而不是列表成长。

您也可以使用:

growthRates = [3, 4, 5, 0, 3]
testRange = range(0,100)
for each in growthRates:
    print each
    assert each in testRange, 'Growth Rate is not between 0 and 100'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top