1

I came accross a problem 2 days ago and I couldn't find a way to make it work, it's simple and my solution seems "good" to me. Here is what I got :

leftKeyCounter = 0

def sendCommand():
    # I want to get the counter back to 0.
    leftKeyCounter = 0
    return leftKeyCounter

while True:
...
leftKeyCounter = leftKeyCounter + 1

The sendCommand() function is called automatically every 5 seconds with the "schedule" helper. In my terminal, the "leftKeyCounter" is not changed, for example; if it is 4, when the function is run, it tells me the variable is 0 now, but if i add one again, it's 5...

All the solutions I look for send me back to the "global variable" that has been deprecated, so I don't find a working solution...

Thanks for any help :)

ThaoD5
  • 183
  • 3
  • 14

3 Answers3

4

The reason its doing this, is because the leftKeyCounter inside your method is different than the lefKeyCounter defined outside - even if they have the same name.

One way to make the method modify the leftKeyCounter that is defined outside, is to use the global keyword - so it knows that it is modifying the global version of the variable.

Another way is to pass the variable in, and return the modified value, and then save this return value:

def sendCommand(leftKeyCounter):
   # do something here
   if something_is_true:
       leftKeyCounter = 0
   return leftKeyCounter # this is the new value of leftKeyCounter

leftKeyCounter = 0 # this is the starting value
while True:
   # do something here
   leftKeyCounter = sendCommand(leftKeyCounter)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
2

If you want to refer to global scope variables, and modify them, then you can do the following thing:

leftKeyCounter = 0

def sendCommand():
    # I want to get the counter back to 0.
    global leftKeyCounter
    leftKeyCounter = 0
    return leftKeyCounter

while True:
...
leftKeyCounter = leftKeyCounter + 1

This question had already been answered: Using global variables in a function other than the one that created them

Community
  • 1
  • 1
Patrick Trentin
  • 7,126
  • 3
  • 23
  • 40
  • I will try it right now, and I already came across this post you're refering to, but i thought it was deprecated, I've read it at so many places, that's why I didn't wan't to use the global var way... (the post is from 2009, so... ), thanks – ThaoD5 Mar 24 '16 at 10:20
2

This is a scoping issue.

sendCommand -> leftKeyCounter is not the same as leftKeyCounter - it'll tell you it's 0 because within the scope of the function it is.

This stack overflow question has some excellent answers and information about how this works. Short Description of the Scoping Rules?

Community
  • 1
  • 1
Callam Delaney
  • 641
  • 3
  • 15