繁体   English   中英

如何在python中的断言语句中使用小于和等于

[英]How to use less than and equal to in an assert statement in python

当我运行以下命令时:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM