0

I have an attribute named session that is set to 1. In changeSession() I am trying to change its value to 2. In the last step session is printed and it is still 1. You can see the the code below. Doing the following would make us print the value 2:

  • session=changeSession()
  • let changeSession() return the new session value.

    However, is it possible to get the value 2 printed without letting changeSession() return anything?

The code:

session=1

def set_session(s):
    session=s

def changeSession():
    set_session(2)

changeSession()
print session
Filip Eriksson
  • 975
  • 7
  • 30
  • 47
  • Possible duplicate of [How do I pass a variable by reference?](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Łukasz Rogalski Sep 11 '16 at 09:02

1 Answers1

0

To do that just use global session in set_session to indicate to python that you want to use the session that you defined outside of the function scope. If you want to document yourself about this behavior, it is called variable scope. Here is the fixed code :

session=1

def set_session(s):
    global session
    session=s

def changeSession():
    set_session(2)

changeSession()
print session
jadsq
  • 3,033
  • 3
  • 20
  • 32