【问题标题】:local variable referenced before assignment in python 3.2在 python 3.2 中赋值之前引用的局部变量
【发布时间】:2014-04-05 01:42:10
【问题描述】:

原代码:

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

【问题讨论】:

  • 你的缩进关闭了,我也不知道ctLowShelfLife是什么?
  • 已修复!计算低保质期,计算有多少产品的保质期为 7 天或更短

标签: python list function variable-assignment python-3.2


【解决方案1】:

在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)

如果将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)

【讨论】:

  • 我发了,只是忘记发了,抱歉!
  • 我写的代码在我的ubuntu中用python3工作,你检查缩进了吗?
  • 我尝试了全局,但我的教授不喜欢,当我尝试运行时它关闭了 python
  • 我编辑我的答案。我在 windows 8 中使用 python3.3 尝试了这两种解决方案并且工作正常
  • 我的错误在这里:lowShelfLife = calcItemsLowShelfLife(shelfLifeList),我使用的是shelfLife而不是shelfLifeList。谢谢
【解决方案2】:

你应该在循环开始之前声明变量ctLowShelfLife =0

更新

问题在于您的缩进。 你的代码应该是这样的,

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

【讨论】:

  • 在我的外壳上打印 7
  • @user3311946 你能把你的代码发布在你在shell中到底尝试什么吗?
  • @user3311946 又是你的缩进问题。
猜你喜欢
  • 2013-07-04
  • 2020-04-10
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多