当我运行以下内容时:
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
为什么?
答案 0 :(得分:10)
执行:
assert each >= 0, 'Growth Rate is not between 0 and 100'
不
assert growthRates >= 0, 'Growth Rate is not between 0 and 100'
答案 1 :(得分:6)
assert 0 <= each <= 100, 'Growth Rate %i is not between 0 and 100.' % each
你的断言当然不会失败,但现在增长率&gt; 100因为growthRates是list而0是整数,'list'&gt;'integer'。
答案 2 :(得分:4)
assert (each >= 0)
不是assert (growthRates >= 0)
: - )
答案 3 :(得分:2)
您也可以使用:
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
答案 4 :(得分:0)
测试每个而不是列表growthRates。
你也可以使用:
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'