Changes

Jump to: navigation, search

OPS435 Python Lab 7

1,283 bytes added, 12:35, 3 December 2017
Global Scope
== Global Scope ==
Sometimes you want to have a variable accessible from anywhere in your program, including inside and outside any functions. Here's an example:
 
<source lang="python">
#!/usr/bin/env python3
 
def function1():
print(authorName)
 
def function2():
print(authorName)
 
authorName = 'Andrew'
print(authorName)
function1()
print(authorName)
function2()
print(authorName)
</source>
 
Note that the same thing is printed over and over because the '''authorName''' variable is defined outside a function which makes it global which makes it accessible from whywhere.
 
Python has one weird quirk when it comes to global scope: if you assign something to a variable inside a function - it will assume you want to create a new variable in that function's local scope. That will hide the global variable inside the function unless you declare it explicitly as global:
 
<source lang="python">
#!/usr/bin/env python3
 
def function1():
authorName = 'Andrew 1'
print(authorName)
 
def function2():
global authorName
authorName = 'Andrew 2'
print(authorName)
 
authorName = 'Andrew'
print(authorName)
function1()
print(authorName)
function2()
print(authorName)
</source>
 
Note that the function1() call does not modify the global '''authorName''' variable but function2() does.
== Object Scope ==

Navigation menu