python - Python全局变量int和set在函数中访问时结果不同
问题描述
text = "abcdefg"
counter = 0
chars = set()
def do_something(i):
print(chars)
print(counter)
counter += 1
if i not in chars:
chars.add(i)
for i in text:
do_something(i)
运行错误:
UnboundLocalError: local variable 'counter' referenced before assignment
在计数器之前添加全局时,它运行良好
set()
0
{'a'}
1
{'a', 'b'}
2
{'c', 'a', 'b'}
3
{'c', 'a', 'd', 'b'}
4
{'a', 'b', 'c', 'e', 'd'}
5
{'a', 'f', 'b', 'c', 'e', 'd'}
6
为什么 int 变量“ counter ”在函数内部调用时需要声明为全局变量?
为什么在函数内部调用时可以在没有全局声明的情况下使用set chars ?
解决方案
推荐阅读
- flutter - 参数类型'列表
>' 不能分配给参数类型 'List ' - eclipse - 无法在 spark local 中生成 badrecord 文件
- laravel - 错误:EPERM:不允许操作,找不到 mkdir 'C:\Users\Sourov' 命令:webpack
- node.js - config.js中的Azure nodejs Webapp“未定义未捕获的参考错误模块”
- node.js - mongodb typescript 类型检查
- android-sqlite - 未创建 SQLite 表且未调用 onUpgrade
- laravel - Laravel Excel 设置活动单元格的所有边框
- autofilter - 自动过滤器返回相同的单元格值
- python - 如何在 Django 中将 unicode 字符转换为十进制
- rest - 收集微信公众号文章