首页 > 解决方案 > 在赋值/不支持的操作数类型之前引用的局部变量“计数”

问题描述

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.

>>> count = 0
>>> def count():
    for i in range(1, 10):

        count = count + 1
        print(count)

>>> count()

Local variable 'count' referenced before assignment

>>> def count():
    global count
    for i in range(1, 10):

        count = count + 1
        print(count)

>>> count()


Unsupported operand type(s) for +: 'function' and 'int'

标签: pythonvariablestypeslocal

解决方案


只是一个变量范围错误,解决方案:

def count():
    count = 0
    for i in range(0,10):
        count += 1
        print (count)

count()

打印很好,因为 count 变量的范围在 count 子例程中。Global 会弄乱作用域(OO '封装'),就像在这个子例程之外声明 count 变量一样。

希望有帮助。IMO 这里的 OP 指出的关于变量范围的问题没有任何问题。

你可以去,

counts = 0

def count(count):
    count = 0
    for i in range(0,10):
        count += 1
        print (count)

count(counts)

推荐阅读