The scope of a variable is the part of the program in which its name can be used. Scope rules decide which variable a name refers to when the same name exists in several places.
Local and global variables
Local variable
Global variable
Created
By assignment inside a function (parameters are local too)
By assignment at the top level of a module
Visible
Only inside that function
Everywhere in the module, including inside functions (for reading)
Lifetime
Created when the function is called, gone when it returns
As long as the program (module) runs
The LEGB rule
When Python meets a name, it looks for it in four scopes, in this order:
LEGB name lookup
L Local names assigned in the current functionE Enclosing names in any outer function (for nested functions)G Global names assigned at the top level of the moduleB Built-in names Python provides: print, len, range, ...
The first match wins; if none matches, NameError is raised.
Changing an outer variable
The key rule: if a function assigns to a name anywhere in its body, that name is local to the whole function, unless it is declared otherwise.
Reading a global inside a function works.
Assigning to the same name inside the function creates a new local variable that hides the global.
Doing x = x + 2 inside a function, without a declaration, fails with UnboundLocalError, because x is local and is read before it has a value.
global x makes x refer to the module’s global variable (and can create it).
nonlocal x makes x refer to the variable of the nearest enclosing function.
Key takeaways
Scope = where a name can be used.
Lookup order: Local, Enclosing, Global, Built-in.
Assignment inside a function creates a local variable.
global and nonlocal let a function rebind outer variables.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a function deposit(amount) that adds amount to a global variable balance, and explain why the declaration is needed.
Show worked answer
balance = 0, then def deposit(amount): global balance followed by balance += amount. Without global balance, the statement balance += amount assigns to balance, which makes it local to the function; it would then be read before having a value and raise UnboundLocalError. The declaration tells Python that balance means the module-level variable.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/functions-and-file-handling-in-python/variable-scope-local-global-and-nonlocal/ to read this page.