Python Forum
Spyder Quirk? global variable does not increment when function called in console
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Spyder Quirk? global variable does not increment when function called in console
#1
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
Reply
#2
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()?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Recommended way to declare global variable? Winfried 1 89 Mar-19-2026, 09:30 PM
Last Post: deanhystad
  not able to call the variable inside the if/elif function mareeswaran 3 1,531 Feb-09-2025, 04:27 PM
Last Post: mareeswaran
  Variable Explorer in spyder driesdep 1 3,344 Apr-02-2024, 06:50 AM
Last Post: paul18fr
  Spyder console zoom in not working? Dionysis 2 2,548 Feb-06-2024, 03:31 PM
Last Post: paul18fr
  Variable for the value element in the index function?? Learner1 8 4,372 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 2,764 Nov-23-2023, 02:53 PM
Last Post: rob101
  Multiple variable inputs when only one is called for ChrisDall 2 1,735 Oct-20-2023, 07:43 PM
Last Post: deanhystad
  It's saying my global variable is a local variable Radical 5 11,325 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Printing the variable from defined function jws 7 11,961 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  Function parameter not writing to variable Karp 5 3,058 Aug-07-2023, 05:58 PM
Last Post: Karp

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020