我必须遗漏一些关于Python变量范围的基本概念,但我无法弄清楚是什么.
我正在编写一个简单的脚本,我想在其中访问在函数范围之外声明的变量:
counter = 0
def howManyTimesAmICalled():
counter += 1
print(counter)
howManyTimesAmICalled()
Run Code Online (Sandbox Code Playgroud)
出乎我意料的是,跑步时我得到:
UnboundLocalError: local variable 'counter' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
在第一行添加全局声明
global counter
def howManyTimesAmICalled():
counter += 1
print(counter)
howManyTimesAmICalled()
Run Code Online (Sandbox Code Playgroud)
没有更改错误消息.
我究竟做错了什么?做正确的方法是什么?
谢谢!
您需要global counter在函数定义中添加内容.(不在代码的第一行)
你的代码应该是
counter = 0
def howManyTimesAmICalled():
global counter
counter += 1
print(counter)
howManyTimesAmICalled()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5617 次 |
| 最近记录: |