Python 3: Print Global and Local Variables

nick3499
1 min readAug 13, 2016

--

In Python 3, only use global variables at their highest conveniences. Since a larger program can inherit global variables from each .py file. For variables added to the global namespace. The interpreter example below may be used to demonstrate how the lifetime of that local variable ends after the local_var() function runs. For variables added to the local namespace.

Also note that the local variable does not replace the global variable. Instead, a new local variable is assigned, leaving the global variable intact. In other words, there are two unique variables with the same name. One in the global namespace, and one in the local namespace.

>>> a = 0 # initialize global var; adds var to global namespace
>>> def local_var():
... a = 3 # initialize local var; adds var to local namespace
... print('local var: a = %s' % a)
...
>>> local_var()
local var: a = 3
>>> print('global var: a = %s' % a)
global var: a = 0

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet