Variables and Parameters are LocalΒΆ
- An assignment statement in a function creates a local variable for the variable on the left hand side of the assignment operator.
- It is called local because this variable only exists inside the function and you cannot use it outside.
For example, consider again the square
function:
- The variable
y
only exists while the function is being executed – we call this its lifetime. - When the execution of the function terminates (returns), the local variables are destroyed.
- Formal parameters are also local and act like local variables.
- For example, the lifetime of
x
begins whensquare
is called, and its lifetime ends when the function completes its execution. - On the other hand, it is legal for a function to access a global variable.
Although the badsquare
function works, it is silly and poorly written.
- First, Python looks at the variables that are defined as local variables in the function, i.e. the local scope.
- If the variable name is not found in the local scope, then Python looks at the global variables, or global scope.
- Assignment statements in the local function cannot change variables defined outside the function. Consider the following codelens example:
A shadow means that the global variable cannot be accessed by Python because the local variable will be found first.
Analogously, look at the following.