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: And here's what you'll see: 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. And now, when you run it, 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. In this case, even though the variable is declared outside the function, Python can still access (though not change) its value.
blog comments powered by Disqus |