Question

The original code:

>>> def calcItemsLowShelfLife(shelfLifeList):
    ctLowShelfLife = 0
    for number in shelfLifeList:
        if number <= 7:
            ctLowShelfLife += 1
    return ctLowShelfLife
>>> shelfLifeList = [5, 7, 10]
>>> lowShelfLife = calcItemsLowShelfLife(shelfLife)

When I try to run python 3.2 gives me the error:

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    lowShelfLife = calcItemsLowShelfLife(shelfLife)
  File "<pyshell#5>", line 3, in calcItemsLowShelfLife
    for number in shelfLifeList:
TypeError: 'int' object is not iterable
Was it helpful?

Solution 2

You should declare variable ctLowShelfLife =0 before the loop begins.

UPDATE

The problem is with your indentation. Your code should be like this ,

>>> def calcItemsLowShelfLife(shelfLifeList):
    ctLowShelfLife = 0
    for number in shelfLifeList:
        if number <= 7:
            ctLowShelfLife += 1
    return ctLowShelfLife

>>> shelfLifeList = [5, 7, 10]
>>> lowShelfLife = calcItemsLowShelfLife(shelfLifeList)
>>> lowShelfLife
2
>>> 

OTHER TIPS

You need to initialize the variable before make += 1:

ctLowShelfLife = 0    

def calcItemsLowShelfLife(shelfLifeList):
    global ctLowShelfLife
    for number in shelfLifeList:
        if number <= 7:
            ctLowShelfLife += 1
    return ctLowShelfLife

shelfLifeList = [5, 7, 10]
lowShelfLife = calcItemsLowShelfLife(shelfLifeList)
print(lowShelfLife)

If you declare ctLowShelfLife as global, you have to tell the function that you want to use the global variable.

If you don't want to use global, you can make it like:

def calcItemsLowShelfLife(shelfLifeList):
    ctLowShelfLife = 0  
    for number in shelfLifeList:
        if number <= 7:
            ctLowShelfLife += 1
    return ctLowShelfLife

shelfLifeList = [5, 7, 10]
lowShelfLife = calcItemsLowShelfLife(shelfLifeList)
print(lowShelfLife)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top