python - 在赋值/不支持的操作数类型之前引用的局部变量“计数”
问题描述
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 子例程中。Global 会弄乱作用域(OO '封装'),就像在这个子例程之外声明 count 变量一样。
希望有帮助。IMO 这里的 OP 指出的关于变量范围的问题没有任何问题。
你可以去,
counts = 0
def count(count):
count = 0
for i in range(0,10):
count += 1
print (count)
count(counts)
推荐阅读
- c++ - Visual Studio 2019 不想为 LIB 版本生成 ASM 文件,我做错了什么?
- netsuite - 根据模板的 NetSuite 自定义字段
- javascript - 对象中的箭头函数和简单函数行为
- javascript - 正则表达式删除数字以外的字符并仅在 Angular 6 中允许单个小数点
- django - django模型多个主键
- java - 如果元素是动态的,则无法定位元素
- reactjs - 使用返回对象内的对象的高阶组件的 mapState 函数遇到编译错误
- android - 如何在点击时设置计时器?
- flutter - Flutter:未能将本地化与 Provider 包结合起来
- opencv - 使用 OpenCV 检测图像是否有故障