2014-04-05 81 views
0

原始代碼:局部變量在Python賦值之前引用3.2

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

當我試圖運行python 3.2給我的錯誤:

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 
+0

你壓痕是關閉的,而且我不知道是什麼'ctLowShelfLife'是什麼? –

+0

固定!算低保質期,算多少產品的保質期不超過7天 – Frangello

回答

0

在循環開始之前,您應該聲明變量ctLowShelfLife =0

UPDATE

問題是與您的壓痕。 您的代碼應該是這樣的,

>>> 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 
>>> 
+0

我做到了,仍然沒有工作 – Frangello

+0

@ user3311946請參閱最新的答案。 – fledgling

+0

在我的外殼上打印7 – Frangello

1

需要初始化變量使+= 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) 

如果您聲明ctLowShelfLife爲全球性,告訴函數你想使用全局變量。

如果你不想使用全局,你可以把它想:

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) 
+0

我做過了,只是忘了貼吧,求求你! – Frangello

+0

我寫的代碼在python3的ubuntu中工作,你檢查縮進嗎? –

+0

檢查我的更新 –

相關問題