Local Variable
A local variable is a variable that exists only within a function.
Shadowing
It's possible to have a local variable and a global variable with the same name.
What makes a variable local?
A variable is local if it could be assigned to anywhere within the function. When Python first sees the function definition, it scans the whole function to determine which variables are local. If there is any potential assignment to a variable within a function, that variable becomes a local variable.
It does not matter whether assignment to the variable actually occurs at runtime. It is simply the presence of an assignment operation within the function that causes a variable to become local.
Overriding
A function can override Python's decision about whether a variable is local by
using global
(or nonlocal
). This statement accepts a list of variable names
and tells Python that those variables should be considered global (or non-local)
instead of local. (Non-local is a more complex topic, so we won't address it
here.)
Because global
/nonlocal
affect how variable names are interpreted throughout
the whole function, it is best practice to put them at the very top of the
function.
UnboundLocalError
UnboundLocalError
means that your code tried to use a variable before any
value was assigned to it. It's just like NameError
but for local
variables.