Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中创建全局变量_Python_Loops_Counter_Counting - Fatal编程技术网

如何在python中创建全局变量

如何在python中创建全局变量,python,loops,counter,counting,Python,Loops,Counter,Counting,在我的程序中,我需要一个计数器,但它只计数到1,而不是更高。这是我的密码: # 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开

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

# 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值?希望你能理解我的问题。顺便说一句:我是一个编程新手,但我想做得更好

你总是调用值为0的函数(就像你期望的那样)。您可以返回“c” 再叫一次

看:


如果要在函数中使用外部变量“c”,请将其写成全局c

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

你应该调查范围。在函数
计数器
中,只向函数参数
c
添加1。从参数列表和调用站点中删除参数
c
,然后您将看到您期望的结果。但谷歌和研究范围。可能的重复是的,这是真的。
def counter():
    global c
    c += 1
    print(c)
    if c == 10:
        methodXY()