Reputation: 1706
I'm rather new to Python and trying to create several different definitions that run each other and refer to different variables in each. Could someone help me as to why this code doesn't work like this and what I need to change to make it work?
From what I thought, it defined what the variable testing
was in the test1
definition and then it would pull that in the test2
and run in the run_this
...
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def test1():
... testing = 1
...
>>> def test2():
... print testing
...
>>> def run_this():
... test1()
... test2()
...
>>> run_this()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in run_this
File "<stdin>", line 2, in test2
NameError: global name 'testing' is not defined
>>>
Upvotes: 1
Views: 740
Reputation: 5333
Your code can be easily fixed by changing testing to a global variable:
testing = 7
def test1():
gobal testing
testing = 5
def test2():
print(testing)
if __name__ = "__main__":
test1()
test2()
Note, that it is only required in routines doing write access to declare the variable as global, because otherwise a local variable with same name would be assigned and lost at procedure exit.
Upvotes: 1
Reputation: 18252
Your testing
variable is scoped to test1()
. In Python, variables defined inside functions are local to that function - no other functions or operations can access them.
When test2()
tries to print from some variable called testing
, it first checks for variables defined inside test2()
. If it doesn't find a match, Python looks in the rest of the script for a match - since it's a scripting language, you could have defined testing
outside both functions, in which case you'd get the behavior you're expecting. Since there isn't anything in the global scope, Python raises a NameError
, letting you know that it can't find anything named testing
inside test2()
.
Upvotes: 4