Scope of Variables in Python: Local and Global (Class 12 Computer Science)
Updated 16 October 2026 · Fact-checked
The scope of a variable is the part of a program where it can be used. A global variable is created outside every function and can be read anywhere. A local variable is created inside a function and exists only while that call runs. To assign to a global variable inside a function, declare it with the global keyword.
A function can read a global variable, but a local variable disappears after the call, so using it outside gives NameError.
Illustration drawn for QuestionBuddy.
Understand Scope of Variables: Local and Global
Every name in Python lives in a scope, the region of the program where that name can be used (NCERT Class XI 7.4).
Global variables are created at the top level of the program, outside all functions. They exist from the moment they are assigned until the program ends, and any function can read them.
Local variables are created inside a function, by assignment or as parameters. They exist only while that call is running and are destroyed when the function returns. Using a local name outside its function raises NameError: name '...' is not defined. Two different functions can each have a local variable called x; they are unrelated.
The assignment rule. Python decides a name's scope when it compiles the function: if a name is assigned anywhere inside the function (x = ..., x += 1, or as a loop variable), it is local for the whole function. Three consequences follow:
- A local variable with the same name as a global hides (shadows) the global inside the function; the global keeps its value.
- Reading the name before the local assignment fails with UnboundLocalError (in Python 3.12 the message is
cannot access local variable 'y' where it is not associated with a value). Soy = y + 2inside a function, when y is only global, is an error, not 10. The 2026-27 sample paper asks exactly this. - Merely reading a global (no assignment) works fine.
The global keyword. Writing global count at the start of a function tells Python that count in this function means the global variable, so assignments change it. Without it, the function would create a new local count.
Mutable globals. If a global name refers to a list or dictionary, a function can change its contents without global (L.append(5), D['k'] = 1), because that is not an assignment to the name itself. Rebinding the name (L = [1]) inside the function, however, creates a local unless global L is declared. This is also why the stack functions in Section C can push to a global list without a global statement.
Every recent CBSE sample paper has at least one scope item: an output MCQ with UnboundLocalError, a global counter, or a 2-mark 'define global and local variable with an example'.
Scope of Variables: Local and Global: key facts
- Local versus global
Global variable created outside all functions; usable anywhere until the program ends Local variable created inside a function (including parameters); exists only during that call Lifetime of a local from its assignment in the call until the function returns - A local used outside its function gives NameError.
- The assignment rule
- Assigned anywhere in the function → local for the whole function
- Only read in the function → global value is used
- Read before local assignment → UnboundLocalError
- x += 1 counts as an assignment.
- global keyword
- global x (first line of the function body) → assignments to x change the global x
- Declaring global for a name that is then used as a parameter is a SyntaxError; keep the names different.
- Mutable globals
- L.append(v), L[i] = v, D[k] = v: change the global object, no global needed | L = [...] inside the function: creates a local L unless global L is declared
- This is how push/pop functions work on a global stack list.
How to answer Scope of Variables: Local and Global questions
For any scope output question, decide the scope of each name before tracing.
- 1List the global names and their values at the point of each call.
- 2For each function, scan the whole body: any name assigned there (=, +=, for loop variable, parameter) is local, unless a global statement names it.
- 3If a local name is read before its first assignment in that call, the answer is UnboundLocalError.
- 4Trace the call: changes to locals vanish when the function ends; changes to globals (declared global) remain.
- 5For lists and dictionaries, separate changing the contents (affects the global) from assigning a new object to the name (local unless declared global).
- 6After the call, print the global values as they now stand.
- 7For 'define with an example' questions, give a four-to-six-line program with one global, one local and a comment marking each.
Scope of Variables: Local and Global in real life
The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
A global counter needs the global keyword
Suppose a school website counts visitors with a variable visits = 0 at the top of the program and a function new_visit() that should add 1 each time a page is opened.
Show why visits += 1 alone fails, and write the correct function. What is printed after three visits?
Try it first, then show the solutionSolution
- visits += 1 assigns to visits, so Python treats it as local and reads it before assignment: UnboundLocalError.
- Declare it global:
visits = 0 def new_visit(): global visits visits += 1 for i in range(3): new_visit() print('Visits:', visits)
Answer: Without global: UnboundLocalError. With global: Visits: 3
Memory hook: To write on the notice board outside your classroom, you must say 'global' first.
Local variables are scratch paper
Imagine a billing function that works out the tax in a local variable tax and returns the total. Later, the cashier's program tries to print tax on its own.
What happens, and how should the program get the tax?
Try it first, then show the solutionSolution
- tax is local to the function; it is destroyed when the function returns, so print(tax) outside gives NameError.
- Return what is needed instead:
def total_bill(amount): tax = amount * 0.18 return amount + tax, tax t, tx = total_bill(200) print(t, tx)
Answer: print(tax) outside the function raises NameError; returning it gives 236.0 36.0.
Memory hook: Rough work done inside the exam hall stays there: return the answer, not the rough sheet.
Tricks to remember Scope of Variables: Local and Global
Short memory aids. Say each one aloud once, then use it on a question the same day.
Assign inside = local inside
If the function ever writes to a name, that name is local for the entire function, from the first line.
Use it when: Spotting UnboundLocalError.
Read freely, write with permission
A function may read a global freely; to write to it, it needs the global permission slip.
Use it when: Deciding when global is needed.
Fill the bag, don't swap the bag
Putting items into a global list needs no global; replacing the whole list with a new one does.
Use it when: Lists and dictionaries as globals.
Same name, different rooms
A local x and a global x are two people with the same name in different rooms; changing one does not touch the other.
Use it when: Shadowing questions.
Scope of Variables: Local and Global: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: Shadowing a global · 1 mark · Very short answerBoard level
Write the output:
x = 5
def show():
x = 20
print('inside', x)
show()
print('outside', x)Try it first, then show the solutionSolution
- x = 20 inside show() creates a local x; the global x is untouched.
- After the call, the global x is still 5.
Answer: inside 20
outside 5
Example 2: Reading before assigning · 1 mark · MCQHarder board level
What happens when this code runs?
y = 8
def update():
print(y)
y = 3
update()(a) prints 8 (b) prints 3 (c) UnboundLocalError (d) prints None
Try it first, then show the solutionSolution
- y is assigned inside update(), so it is local for the whole function.
- print(y) reads the local y before it has a value.
Answer: (c) UnboundLocalError
Example 3: global keyword with a running total · 2 marks · Short answerHarder board level
Predict the output:
total = 100
def deposit(amt):
global total
total = total + amt
return total
def withdraw(amt):
total = 50
return total - amt
print(deposit(40), withdraw(20), total)Try it first, then show the solutionSolution
- deposit declares total global: it becomes 140 and 140 is returned. (1 mark)
- withdraw has its own local total = 50 and returns 30; the global is still 140. (1 mark)
Answer: 140 30 140
Example 4: Define with an example · 2 marks · Short answerHarder board level
Define global and local variables. Write a short program that uses one of each and mark them.
Try it first, then show the solutionSolution
- A global variable is declared outside all functions and can be used anywhere in the program; a local variable is declared inside a function and can be used only inside that function, while it runs. (1 mark)
rate = 5 # global variable def interest(p): si = p * rate / 100 # si and p are local variables return si print(interest(2000))- rate is read inside the function without being assigned, so the global is used. (1 mark)
Answer: Definitions as above; the program prints 100.0
Example 5: Global list without the global keyword · 2 marks · Short answerHOTS / competency
Predict the output:
L = [1, 2]
def f():
L.append(3)
def g():
L = [9]
L.append(4)
def h():
global L
L = L + [5]
f(); g(); h()
print(L)Try it first, then show the solutionSolution
- f changes the contents of the global list: [1, 2, 3]. (½ mark)
- g assigns L, so its L is a new local list [9, 4], discarded at the end. (½ mark)
- h declares global and rebinds L to [1, 2, 3] + [5]. (1 mark)
Answer: [1, 2, 3, 5]
Example 6: Case study: a quiz score · 4 marks · Case-basedHOTS / competency
Suppose a quiz program keeps score = 0 at the top. check(ans, key) should add 4 for a correct answer and subtract 1 for a wrong one.
(i) A student writes the function without a global statement. What happens on the first call? (1 mark)
(ii) Write the correct function and show the score after answers ['a', 'c', 'b'] for key ['a', 'b', 'b']. (2 marks)
(iii) Suggest a way to avoid the global variable altogether. (1 mark)
Try it first, then show the solutionSolution
- (i) score += 4 makes score local, and it is read before assignment: UnboundLocalError.
- (ii)
Two correct (+8) and one wrong (-1) give 7.score = 0 def check(ans, key): global score if ans == key: score += 4 else: score -= 1 for a, k in zip(['a', 'c', 'b'], ['a', 'b', 'b']): check(a, k) print(score) - (iii) Pass the score in and return the new score: def check(ans, key, score): ... return score, then call score = check(a, k, score).
Answer: (i) UnboundLocalError (ii) 7 (iii) Pass the score as a parameter and return the updated value.
Where students lose marks in Scope of Variables: Local and Global
The slips examiners see most often, and what to write instead.
Mistake: Answering a number for an UnboundLocalError question
A name assigned anywhere in the function is local throughout, so reading it first fails.
Wrong working
y = 8
def update():
y = y + 2
# output: 10Right working
UnboundLocalError (y is local and has no value yet)
Do this: Scan the whole function for assignments before tracing it.
Usually costs: 1 mark.
Mistake: Putting global after the variable is used
Python raises SyntaxError if a name is used before its global declaration in the same function.
Wrong working
def f():
x = 5
global xRight working
def f():
global x
x = 5Do this: Write the global statement as the first line of the function body.
Usually costs: Half a mark.
Mistake: Thinking a parameter changes the caller's number
Parameters are local names; rebinding them does not change the variable passed in.
Wrong working
n = 1; change(n) → n is now 11
Right working
n stays 1; use m = change(n) to capture the result
Do this: Return the new value and assign it at the call.
Usually costs: 1 mark.
Mistake: Defining scope with no example
The 2-mark question asks for a definition 'with a suitable example'; the program carries half the marks.
Do this: Write a 4-6 line program with comments marking the global and local variables.
Usually costs: 1 mark.
Exam tips
- When an MCQ option says 'Error', check for a name that is assigned inside the function and read before that assignment.
- In stack and file programs, a global list can be appended to without the global keyword; do not add unnecessary global statements, but do add them when you assign the name.
- Keep global names and parameter names different in your answers to avoid SyntaxError and confusion.
- For 'differentiate' questions, compare where each is created, where it can be used and how long it lives, then give an example.
- Prefer passing values and returning results in your own programs; examiners accept global, but a clean return is easier to mark.
Practice questions on Scope of Variables: Local and Global
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
A variable defined inside a function is called a:
(a) global variable (b) local variable (c) built-in variable (d) module variableHint
It lives only inside the function.
Answer
(b) local variable
Q2 · 1 mark · Very short answerBoard level
Write the output:
a = 10 def f(): print(a * 2) f() print(a)Hint
a is only read inside f.
Answer
20
10Q3 · 1 mark · Very short answerBoard level
Which keyword lets a function assign a new value to a variable created outside all functions?
Hint
It names the scope.
Answer
global
Q4 · 2 marks · Short answerHarder board level
Predict the output:
n = 1 def change(n): n = n + 10 return n m = change(n) print(n, m)Hint
A parameter is a local variable.
Answer
1 11 (the parameter n is local; the global n stays 1).
Q5 · 3 marks · Short answerHarder board level
Write a function add_item(item) that appends item to a global list cart and a function clear_cart() that replaces cart with an empty list. Show cart after add_item('pen'), add_item('ink'), then after clear_cart().
Hint
Which of the two functions needs the global keyword?
Answer
cart = [] def add_item(item): cart.append(item) def clear_cart(): global cart cart = [] add_item('pen') add_item('ink') print(cart) clear_cart() print(cart)Output: ['pen', 'ink'] then []. Only clear_cart needs global, because it assigns a new list to the name.
Q6 · 1 mark · Assertion-reasonHarder board level
Assertion (A): A function can append an element to a global list without declaring the list global.
Reason (R): Appending changes the contents of the list but does not assign a new object to its name.
(a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.Hint
Fill the bag or swap the bag?
Answer
(a) Both are true and R explains A.
Q7 · 2 marks · Short answerHOTS / competency
Predict the output, or the error:
c = 0 def count(): for c in range(3): pass return c print(count(), c)Hint
Is a loop variable an assignment?
Answer
2 0. The for loop assigns c, so c is local to count(); it ends as 2. The global c is still 0.
Test your recall
Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.
1.Where is a global variable created?Show answer
Outside all functions, at the top level of the program.
2.When is a local variable destroyed?Show answer
When the function call in which it was created ends.
3.What error comes from using a local variable outside its function?Show answer
NameError.
4.What error comes from reading a local before assigning it?Show answer
UnboundLocalError.
5.Are function parameters local or global?Show answer
Local.
6.Does L.append(1) inside a function need global L?Show answer
No; it changes the contents, not the name.
Scope of Variables: Local and Global: frequently asked questions
What is the difference between local and global variables in Python?
A global variable is created outside all functions and can be read anywhere in the program for as long as it runs. A local variable is created inside a function (including its parameters) and can be used only inside that function during a call.
Why does y = y + 2 inside a function give an error when y is global?
Because y is assigned inside the function, Python treats it as local for the whole function. The right side then reads the local y before it has a value, which raises UnboundLocalError. Add global y, or pass y as a parameter.
When do I need the global keyword?
Only when a function assigns to a global name (=, +=, or rebinding). Reading a global, or changing the contents of a global list or dictionary, does not need it.
Is LEGB or the nonlocal keyword in the Class 12 syllabus?
No. The CBSE 2026-27 syllabus lists only 'scope of a variable (global scope, local scope)'. Questions use one level of functions and the global keyword.