This week, Python 101 discusses how to abstract out parts of yourPython code into reusable functions, add flexibility to them by allowingthem to accept different arguments, and make them return specific values.Also included: a discussion of variable scope and functions to help youwrite your own functions. Confused? All is explained within...
Let's now talk a little bit about the variables used within a function, and their relationship with variables in the main program. Unless you specify otherwise, the variables used within a function are local - that is, the values assigned to them, and the changes made to them, are restricted to the function space alone.
For a clearer example of what this means, consider this simple example:
#!/usr/bin/python
# set a variable outside the function
flavour = "tangerine"
# alter the variable within the function
def changeFlavour():
flavour = "raspberry"
# before invoking function
print "(before) Today's flavour is", flavour
# invoke function
changeFlavour()
# after invoking function
print "(after) Today's flavour is", flavour
And here's what you'll see:
(before) Today's flavour is tangerine
(after) Today's flavour is tangerine
As you can see, assignment to a variable within a function does not alter the same variable outside the function...unless you declare it with the "global" keyword.
#!/usr/bin/python
# set a variable outside the function
flavour = "tangerine"
# alter the variable within the function
def changeFlavour():
global flavour
flavour = "raspberry"
# before invoking function
print "(before) Today's flavour is", flavour
# invoke function
changeFlavour()
# after invoking function
print "(after) Today's flavour is", flavour
And now, when you run it,
(before) Today's flavour is tangerine
(after) Today's flavour is raspberry
The "global" keyword tells Python that changes made to the variable should be applied globally, and should not remain localized to the function space alone.
Note, however, that the "global" keyword is only used when you plan to alter a global variable; if all you need to do is read a global variable, Python can access its value without any requirement to first declare it global.
#!/usr/bin/python
# set a variable outside the function
flavour = "tangerine"
# use the variable within the function
def whatFlavour():
print "Today's flavour is", flavour
# invoke function
whatFlavour()
In this case, even though the variable is declared outside the function, Python can still access (though not change) its value.