Functions
Scope of variables
Tell where a variable can be used.
The scope of a variable is the part of the program where it can be used. A variable is either global or local.
- A global variable is defined outside all functions. It can be used (read) inside any function defined after it.
- A local variable is defined inside a function (or block). It can be used only there, and it exists only while the function is running. Trying to use it outside the function gives a NameError (Program 7-14).
If a function assigns a value to a variable with the same name as a global one, Python treats it as a new local variable inside that function. The local one hides the global one, and the global variable is not changed.
To change a global variable from inside a function, declare it first with the keyword global:
- count = 0
- def addOne(): global count; count = count + 1
After addOne() is called, count is 1 everywhere in the program (the book's Program 7-15 does the same with num).
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.