Python Forum
Spyder Quirk? global variable does not increment when function called in console - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Spyder Quirk? global variable does not increment when function called in console (/thread-29759.html)



Spyder Quirk? global variable does not increment when function called in console - rrace001 - Sep-18-2020

I did not see that Spyder had a forum so I tried here. If I should go somewhere else then please let me know.

The following code works as expected when run in a file using Spyder:

v= 0
def inc():    
    global v
    v +=1
    return v

print(v)
inc()
inc()
inc()
print(v)
Spyder Console:
In [135]: runfile('untitled0.py', wdir='/')
0
3

As expected, variable v prints 3 but if I call inc() from the Spyder console it continues to increment the return value but the variable v is not updated.

Spyder Console:

In [136]: inc()
Out[136]: 4

In [137]: v
Out[137]: 3

In [138]: inc()
Out[138]: 5

In [139]: v
Out[139]: 3


Does anyone know why this happens? Any insight would be appreciated.

Very Respectfully from an Unladen Swallow


RE: Spyder Quirk? global variable does not increment when function called in console - deanhystad - Sep-18-2020

The value of v in the program updating. That is shown by the value returned by inc(). For some reason Spyder is looking elsewhere when you ask for the value of v.

This all works as expected in IDLE. What happens if you set the value of v from the consle and call inc()?