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'
只是一个变量作用域错误,解决方案:
def count():
count = 0
for i in range(0,10):
count += 1
print (count)
count()
打印很好,因为count变量的范围在count子例程内。全局会弄乱范围(OO“封装”),就像在此子例程外声明count变量一样。
希望有帮助。 IMO在这里没有关于OP所指示的变量作用域的问题。
你可以去,
counts = 0
def count(count):
count = 0
for i in range(0,10):
count += 1
print (count)
count(counts)