(Nov-06-2017, 01:11 PM)CWatters Wrote: Understood it's not good practice to use global variables but just trying to get my head around how python expect them to work.
Hope this example helps
var1 = 1
var2 = 2
var3 = 3
var4 = 4
def foo():
global var1
print('var1 value within foo, before addition is {}'.format(var1))
var1 += 10
print('var1 value within foo, after addition is {}'.format(var1))
def bar():
# variable with same name, but local namespace
var3 = 0 # this is actually local var, there is also 'global' one with different value
print('var3 value within bar, before addition is {}'.format(var3))
var3 += 1
print('var3 value within bar, after addition is {}'.format(var3))
def foo2():
print('var4 value from within foo2 is {}'.format(var4))
def bar2():
var2 += 10 # try to change value of var2 this will rise error
print('var2 value within bar, before addition is {}'.format(var2))
print('var1 value before call of the foo/bar is {}'.format(var1))
print('var2 value before call of the foo/bar is {}'.format(var2))
print('var3 value before call of the foo/bar is {}\n\n'.format(var3))
foo()
print('var1 value after call of the foo is {}\n\n'.format(var1))
bar()
print('var3 value after call of the foo is {}\n\n'.format(var3)) # this refer to the 'global' one, value is still 3.
print('var4 value before call of the foo2 is {}'.format(var4))
foo2()
print('var4 value after call of the foo2 is {}\n\n'.format(var4))
bar2()
Output:
var1 value before call of the foo/bar is 1
var2 value before call of the foo/bar is 2
var3 value before call of the foo/bar is 3
var1 value within foo, before addition is 1
var1 value within foo, after addition is 11
var1 value after call of the foo is 11
var3 value within bar, before addition is 0
var3 value within bar, after addition is 1
var3 value after call of the foo is 3
var4 value before call of the foo2 is 4
var4 value from within foo2 is 4
var4 value after call of the foo2 is 4
Traceback (most recent call last):
File "C:\myfile.py", line 38, in <module>
bar2()
File "C:\myfile.py", line 23, in bar2
var2 += 10 # try to change value of var2 this will rise error
UnboundLocalError: local variable 'var2' referenced before assignment
>>>