python - 如何在Python中创建全局变量

标签 python loops counter counting

在我的程序中,我需要一个计数器,但它只计数到一,而不是更高。这是我的代码:

# set a counter variable
c = 0

def counter(c):

    c += 1
    print(c)
    if c == 10:
        methodXY()

def do_something():
    # here is some other code...
    counter(c)

这是我的代码的重要部分。我想问题是 counter() 方法始终以 0 值开头,但我该如何解决这个问题呢?我的程序是否有可能“记住”我对 c 的值?希望你理解我的问题。顺便说一句:我完全是编程初学者,但我想变得更好

最佳答案

如果你想在函数中使用外部变量“c”,请将其写为global c

def counter():
    global c
    c += 1
    print(c)
    if c == 10:
        methodXY()

关于python - 如何在Python中创建全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926334/

相关文章:

Python、单元测试、mock内置/扩展类型类方法

python - 什么会导致 Gdata Python 客户端在 appengine 中调用 YouTubeVideoQuery 时失败?

python - 无法退出 python 循环

function - 在 pine 脚本中使用循环时更改元组值

javascript - 尝试按距离计算计数器消息

python - 全新 python 3.3.5 安装时出现 _socket 模块导入错误

javascript - Substr python 版本

excel - 试图让 vba 嵌套 for 循环以用于电子邮件和 pdf 导出

javascript - 在计数器上设置间隔发行

php - 大网站公司都有什么样的下载柜台?