且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python - 如何从函数中引用全局变量

更新时间:2023-11-14 09:20:58

需要在函数定义中添加global counter.(不在代码的第一行)

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

你的代码应该是

counter = 0

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

howManyTimesAmICalled()