Scope is the part of a program where a name can be used and the rules Python follows to decide which value that name refers to. A function creates its own scope when called. Its parameters and local variables exist while the function runs, then that function scope disappears when it returns. section 22.1 section 22.2
The same name can mean different values
def fairy_tale(): peter = 5 print(peter) peter = 30 fairy_tale() print(peter) The output is 5 and then 30. The first peter belongs to the function scope; the second belongs to the global scope. Python first looks in the current scope, then checks outer scopes until it reaches the global scope. If no matching name exists, it reports an error. section 22.2
Keep these scope rules in mind when reading or writing functions:
- A function may read a name from an outer scope when that name is not found locally, but a name that does not exist anywhere causes an error. section 22.2
- A function defined inside another function is nested. The inner function is available only within the enclosing function’s scope while that enclosing call is active. section 22.3
Figure 22.1.
A trace of a program that indicates whether a number is odd or even. At each line, you draw the scope you’re in along with all variables existing in that scope. In
you start the program and are at the line with the arrow. After that line executes, the scope of the program contains a function definition and a variable named num. In
you just made the function call print(odd_or_even(num)). You create a new scope. Notice that the global scope still exists but isn’t in focus right now. In the left panel of
, you have the parameter num as a variable with the value 4. In the middle panel of
you’re executing the line num=num%2 inside the function call and reassign, only in the function call scope, the variable num to be 0. In the right panel of
you make the decision and return "even". In
the function returned "even" and the scope of the function call disappeared. You’re back in the global scope and perform the two prints. Printing the function call shows "even" and printing the num shows 4 because you’re using the num variable from the global scope.
Trace the odd_or_even call one line at a time: watch the new function scope appear, the local num change, and the global num remain 4. section 22.2




















