views:

98

answers:

5

When I run the following:

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'

I get:

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

Why is that?

+8  A: 

Do:

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

not:

assert growthRates >= 0, 'Growth Rate is not between 0 and 100'
katrielalex
Better yet, it could be `assert 0 <= each <= 100`.
mjschultz
I had this syntax originally (with growthRates), but changed it out to troubleshoot it. I was really confused when one worked and one didn't, but as explained below it makes sense now! Thanks.
NoahClark
+4  A: 

assert (each >= 0) not assert (growthRates >= 0) :-)

fredley
+3  A: 

Do enter code here

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

Your asserts do not fail of course then, but now the growthRates > 100 because growthRates is list and 0 is integer and 'list'>'integer',

Tony Veijalainen
+1: This is the only response so far that answers the question -- which was "Why is that?"
martineau
A: 

Test for each instead of the list growthRates.

You could also use:

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'
Rod
It would be to use range checking (0<=rate<=100) rather than containment testing (i.e. `in`) here because it's more efficient and could easily handle all the possible floating point rates such as 6.789.
martineau
+2  A: 

You can also use:

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
Chinmay Kanchi
You don't need the `[]`.
katrielalex
Thanks. <15 chars>
Chinmay Kanchi