문제

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
도움이 되었습니까?

해결책 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
>>> 

다른 팁

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top