Code: Select all
#start of code snippet: def foo(): x = 20 def bar(): global x x = 25 print("Before calling bar: ", x) print("Calling bar now") bar() print("After calling bar: ", x) foo() print("x in main : ", x) #end of code snippet
This results in the following output:
Before calling bar: 20
Calling bar now
After calling bar: 20
x in main : 25
I thought the fact that “x” is not changing after calling the bar function might have something to do with nesting the bar function within the foo function, so I moved it from within the foo function to the outside at the same level as the foo function. But running the modified version still generated the same result.
So why, after declaring x as global in the bar function, is its value not changed on return? And why is it then changed in the main program?
Any help appreciated!