Search code examples
pythonfunctioncounter

Why does this simple python function only work once


I want to create a simple counter so i created this function:

count = 0

def add(count):
    count += 1
    print(count)

and if re-called the count goes up to 1 but if I recall it again it stays at 1. I also tried to output the count variable outside of the function after recalling it but that led to a constant output of 0


Solution

  • The count variable in your function has a different scope to the count variable in the rest of your script. Modifying the former does not affect the latter.

    You would need to do something like:

    def add(count):
        count += 1
        print(count)
        return count
    
    count = 0
    count = add(count)
    count = add(count)