Python - How to reference a global variable from a function [duplicate]

允我心安 提交于 2019-12-10 21:14:36

问题


I must be missing some very basic concept about Python's variable's scopes, but I couldn't figure out what.

I'm writing a simple script in which I would like to access a variable that is declared outside the scope of the function :

counter = 0

def howManyTimesAmICalled():
    counter += 1
    print(counter)

howManyTimesAmICalled()

Unexpectedly for me, when running I get :

UnboundLocalError: local variable 'counter' referenced before assignment

Adding a global declaration at the first line

global counter
def howManyTimesAmICalled():
    counter += 1
    print(counter)

howManyTimesAmICalled() 

did not change the error message.

What am I doing wrong? What is the right way to do it?

Thanks!


回答1:


You need to add global counter inside the function definition. (Not in the first line of your code)

Your code should be

counter = 0

def howManyTimesAmICalled():
    global counter
    counter += 1
    print(counter)

howManyTimesAmICalled()


来源:https://stackoverflow.com/questions/17928791/python-how-to-reference-a-global-variable-from-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!