How to create a global variable in python

In my program I need a counter, but it just counts to one and not higher. Here is my code:

# 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)

this is the important part of my code. I guess the problem is that the method counter() starts with the value 0 all the time, but how can I fix that? Is it possible that my program "remembers" my value for c? Hope you understand my problem. Btw: I am a totally beginner in programming, but I want to get better

Upvotes: 1

Views: 480

Answers (2)

Raghav Maheshwari
Raghav Maheshwari

Reputation: 19

If you want to use outer variable "c" inside your function, write it as global c.

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

Upvotes: 1

Steammasker
Steammasker

Reputation: 32

You always call the function with the value 0 (like you expected). You can return "c" and call it again.

Look:

# set a counter variable
c = 0

def counter(c):

    c += 1
    print(c)
    return c



def do_something(c):

    c=counter(c)
    return c

for i in range(10):    
    c=do_something(c)

Upvotes: 0

Related Questions