0

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

BoarGules
  • 16,440
  • 2
  • 27
  • 44
DDDritte
  • 3
  • 1
  • Change your function to `return count` instead of printing it, call your function like this: `count=add(count)`, then `print (count)` after the call to `add()`. `count` inside the function is a different variable that is local to the function. – BoarGules Nov 16 '21 at 12:32
  • So I could also just declare `count` as being a global variable right? – DDDritte Nov 16 '21 at 12:44
  • You could, but don't. – BoarGules Nov 16 '21 at 12:57
  • It is technically possible to declare the variable inside the function as global (https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) but it is best to avoid that as it can lead to confusion. It is better practice to have the function simply return a value. – otocan Nov 16 '21 at 12:58

1 Answers1

3

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)
otocan
  • 824
  • 11
  • 16