Local Scope and Global Scope in Python TRB CSI › Python Programming › local and global scope

Local Scope and Global Scope in Python

Scope என்றால் என்ன? Scope is the region of a program where a variable can be accessed or used. தமிழில்: ஒரு variable-ஐ program-ன் எந்த பகுதியில் access செய்யலாம் என்பதை தீர்மானிக்கும் boundary தான் Scope.

Free Beginner 22 min 172 cards 25 programs 10 MCQs v3

Python-ல் ஒரு variable எங்கே create செய்யப்படுகிறது, அந்த variable-ஐ எந்த இடத்திலிருந்து access செய்யலாம் என்பதைத்தான் Scope என்று சொல்கிறோம்.

இந்த concept-ல் முதலில் இரண்டு முக்கிய scope-கள்:

Algorithm
  1. Local Scope
  2. Global Scope

Simple-ஆ:

Variable எங்கே visible? எங்கே usable? என்பதுதான் Scope.

Definition
Meaning

Scope என்றால் என்ன?

Scope is the region of a program where a variable can be accessed or used.

ஒரு variable-ஐ program-ன் எந்த பகுதியில் access செய்யலாம் என்பதை தீர்மானிக்கும் boundary தான் Scope.

Program
Example
Python 1 lines
1x = 10
Explanation
Core idea

இந்த x எங்கே create செய்யப்பட்டது?

Detail 01

Function வெளியே.

அதனால் இது

Global Variable

Simple Explanation
Core idea

ஒரு college example எடுத்துக்கொள்ளலாம்.

College முழுவதும் பயன்படுத்தக்கூடிய notice

Tomorrow Holiday

Detail 02

அதை எல்லா departments-மும் பார்க்கலாம்.

இதை

Global

Detail 04

என்று நினைத்துக்கொள்ளலாம்.

Detail 05

ஆனால் Computer Science department staff room-ல் மட்டும் இருக்கும் ஒரு note:

Detail 06

CS Meeting at 2 PM

Detail 07

அதை அந்த room / department-க்குள் மட்டும் use செய்வோம்.

இதை

Local

Detail 09

என்று நினைத்துக்கொள்ளலாம்.

So

Global = பெரிய area
Local = குறிப்பிட்ட area

Concept
Main concept
  1. Function வெளியே create
  2. Program-ன் பல பகுதிகளில் access செய்யலாம்
  1. Function உள்ளே create
  2. அந்த function-க்குள் மட்டும் access
Explanation
Python Program
Core idea
│
├── Global Area
│      │
│      └── Global Variables
│
└── Function
       │
       └── Local Area
              │
              └── Local Variables
Program
Example
Python 1 lines
1x = 100
Program
Python 2 lines
1def test():
2    y = 20
Explanation
Here
x
Global
y
Local
Explanation
Local scope
Core idea

Local Scope என்றால் என்ன?

Detail 01

ஒரு variable function உள்ளே create செய்யப்பட்டால், அது பொதுவாக அந்த function-க்கு local variable.

Program
Example
Python 3 lines
1def show():
2    x = 10
3    print(x)
Verified output
10
Learning Run Mode — this is the output the author verified, not a live execution.
Explanation
Core idea

show()

Output
10
Program
இங்கே
Python 1 lines
1x = 10
Verified output
NameError
Learning Run Mode — this is the output the author verified, not a live execution.

function உள்ளே create செய்யப்பட்டது.

So:

x → Local Variable

Important
  1. இந்த x-ஐ function வெளியே access செய்ய முடியுமா?

  2. def show()

    x = 10

  3. show()

  4. print(x)

Output
Result
NameError

ஏன்?

Because:

x exists only inside show() local scope.

Flow
Local scope flow
  1. show() function
  2. x = 10 created
  3. Local scope starts
  4. Function body can use x
  5. Function execution finishes
  6. Local variable no longer directly accessible outside
Program
Python 3 lines
1def student():
2    mark = 90
3    print(mark)
Verified output
90
Learning Run Mode — this is the output the author verified, not a live execution.
Explanation
Core idea

student()

Output
90
Explanation
Core idea

mark = 90

def student()

student() என்ற function define செய்கிறோம்.

Detail 02

mark function உள்ளே create ஆகிறது.

Therefore

mark → Local Variable
print(mark)

Detail 04

Same function-க்குள் இருப்பதால் access செய்ய முடிகிறது.

Common Mistake
mark = 90

student()

print(mark)

Wrong.

ஏனெனில் mark local.

print(mark)

access செய்ய முடியாது.

Explanation
Global scope
Core idea

Global Scope என்றால் என்ன?

Detail 01

Function-க்கு வெளியே, module/program level-ல் create செய்யப்பட்ட variable Global Variable.

Program
Example
Python 1 lines
1x = 100
Program
Python 2 lines
1def show():
2    print(x)
Verified output
100
Learning Run Mode — this is the output the author verified, not a live execution.
Explanation
Core idea

show()

Output
100
Explanation
Why it works
Core idea

x = 100

Detail 01

function வெளியே create செய்யப்பட்டது.

So

x → Global Variable

Detail 03

Function உள்ளே x என்ற local variable இல்லையென்றால் Python outer/global scope-ல் x இருக்கிறதா என்று பார்க்கும்.

Found

x = 100

Detail 05

அதனால் print செய்கிறது.

Flow
  1. x = 100
  2. Global Variable
  1. show()
  2. Need x
  3. Local x இருக்கிறதா?
  4. No
  5. Global x இருக்கிறதா?
  6. Yes
  7. Use 100
Explanation
Core idea

name = "Python"

Program
Python 2 lines
1def display():
2    print(name)
Verified output
Python
Learning Run Mode — this is the output the author verified, not a live execution.
Explanation
Core idea

display()

Output
Python
Concept
Important concept

Global variable-ஐ function உள்ளே read செய்ய normally global keyword தேவையில்லை.

Program
Example
Python 1 lines
1x = 10
Program
Python 2 lines
1def show():
2    print(x)
Verified output
100
50
Learning Run Mode — this is the output the author verified, not a live execution.
Explanation
Core idea

show()

Detail 01

Perfectly valid.

Explanation
Local and global together
Core idea

x = 100

Detail 01
def show():
    y = 50
    print(x)
    print(y)
Detail 02

show()

Output
100
50
  • x → Global
  • y → Local
  • Local variables
  • +
  • Visible global variables
Explanation
Outside function
Core idea

works.

But outside function

print(x)

Detail 02

print(y)

Detail 03

doesn't work.

Reason

?

Detail 05
x = Global
y = Local
Comparison
Local VariableGlobal Variable
Function உள்ளே createFunction வெளியே create
Function-க்குள் accessபல functions access செய்யலாம்
Limited scopeWider scope
Function-specificProgram/module-level
Outside direct access இல்லைFunction உள்ளே read செய்யலாம்
Concept
Most important concept
Context

Same variable name Local + Global

இதுதான் exam/interview-ல் மிகவும் முக்கியம்.

x = 100

x = 20
    print(x)

show()

print(x)
Output
20
100

Confusing-ஆ இருக்கலாம்.

Inch by inch பார்க்கலாம்.

Dry Run
Execution traceRead top to bottom · highlighted cells show the current value10 states
StepxAction
01First100
02Global variableGlobal x = 100
03def show()20Function உள்ளே x create செய்யப்பட்டது.
04SoLocal x = 20
05Insideprint(x) → Python local variable first check செய்கிறது.
06Found20
07So output20 → Function முடிந்தது.
08Outsideprint(x) → இப்போது local scope இல்லை.
09Global x100
10So output100
Important
Very important
  1. Same name இருந்தாலும்

    Global x

  2. மற்றும்

  3. Local x

  4. இரண்டு different variables போல behave செய்யலாம்.

Explanation
Example
Core idea

Global x = 100
Local x = 20

Detail 01

Local variable global variable-ஐ temporarily shadow செய்கிறது.

இதற்கு

Variable Shadowing

Detail 03

என்று சொல்லலாம்.

Memory Trick

Local first → Global next

Simple concept.

LEGB

அதையும் கீழே பார்ப்போம்.

Explanation
Modifying global variable

இப்போது மிகவும் முக்கியமான concept.

Global variable

x = 10

Function உள்ளே

def change()

x = 20

இது global x-ஐ modify செய்கிறதா?

No.

Complete

x = 10

def change()

x = 20

change()

print(x)

Output
10
Explanation
Why
Function உள்ளே

x = 20

என்று assignment செய்ததால் Python அதை new local variable ஆக எடுத்துக்கொள்கிறது.

So

Global x = 10

Local x = 20

Global unchanged.

Explanation
Global keyword
Core idea

keyword use செய்ய வேண்டும்.

Global variable-ஐ function உள்ளே modify செய்ய

global

Detail 02

global variable_name

Program
Example
Python 1 lines
1x = 10
Program
Python 3 lines
1def change():
2    global x
3    x = 20
Explanation
Core idea

change()

Program
Python 1 lines
1print(x)
Verified output
20
Learning Run Mode — this is the output the author verified, not a live execution.
Output
20
Explanation

x = 10

Global x.

def change()

Function starts.

global x

Python-க்கு

"இந்த function-க்குள் வரும் x புதிய local variable இல்லை; வெளியே இருக்கும் global x-ஐ தான் நான் பயன்படுத்தப் போகிறேன்."

என்று சொல்கிறோம்.

Then

x = 20

Global x changes

10 → 20

Flow
  1. Global x = 10
  2. change()
  3. global x
  4. Use global variable
  5. x = 20
  6. Global x becomes 20
Explanation
Global without keyword
Reading

x = 10

def show()

print(x)

global தேவையில்லை.

Reassigning

x = 10

def show()

global x

x = 20

global தேவை.

Easy Memory

Read Global → normally no global needed

Reassign Global → global needed

Common Mistake

x = 10

print(x)
x = 20
test()
இது பல beginners-க்கு confusion.

UnboundLocalError

Explanation
Why error
Function உள்ளே

x = 20

assignment இருப்பதால் Python x-ஐ function-local variable என்று decide செய்கிறது.

So earlier

print(x)

execute ஆகும்போது local x இன்னும் value பெறவில்லை.

Concept

Local x exists conceptually
but value assigned later

அதனால்:

UnboundLocalError

Explanation
Correct with global
Core idea

x = 10

Detail 01
def test():
    global x
    print(x)
    x = 20
Detail 02

test()

Detail 03

print(x)

Output
10
20
Explanation
Function parameters are local

Previous topic-க்கு connection மிகவும் முக்கியம்.

def add(a, b)

result = a + b

return result

இதில்

a

b

Output
result
எல்லாமே function local scope-ல் இருக்கின்றன.

Function parameters generally behave as local names.

Program
Python 3 lines
1def show(name):
2    message = "Hello " + name
3    print(message)
Explanation
Core idea

show("Ravi")

Inside function
name
Local parameter
message
Local variable
Detail 02

Outside:

Program
Python 1 lines
1print(name)
Verified output
10
20
Learning Run Mode — this is the output the author verified, not a live execution.
Explanation
Core idea

normally invalid.

Explanation
Two different functions
Core idea

ஒவ்வொரு function-க்கும் அதன் own local scope இருக்கும்.

Detail 01
def first():
    x = 10
    print(x)
Detail 02
def second():
    x = 20
    print(x)
Detail 03
first()
second()
Output
10
20
Important
  1. இரண்டு functions-லும்

    x

  2. same name இருந்தாலும் conflict இல்லை.

  3. Because

    first() local x = 10

  4. second() local x = 20

  5. Different local scopes.

Flow
first()
  │
  └── Local x = 10

second()
  │
  └── Local x = 20
Explanation
Local variable lifetime
Core idea

Local scope மற்றும் lifetime related ஆனால் exactly same இல்லை.

Program
Example
Python 3 lines
1def test():
2    x = 100
3    print(x)
Explanation
Core idea

Function execute ஆகும்போது local x available.

Detail 01

Function call முடிந்ததும் அந்த local name-ஐ outside function direct-ஆக access செய்ய முடியாது.

Explanation
Global variable lifetime
Core idea

Global variable module/program-level name.

Program
Example
Python 1 lines
1x = 100
Explanation
Core idea

Program/module scope-ல் available இருக்கும்.

Detail 01

பல functions அதை read செய்யலாம்.

Important
Important design point
  1. எல்லா variable-யும் global ஆக வைத்துவிடலாமா?

  2. Technically many cases-ல் முடியும்.

  3. ஆனால் நல்ல programming practice

    தேவையில்லாமல் global variables அதிகமாக பயன்படுத்த வேண்டாம்.

  4. Why?

  5. எந்த function modify செய்தது கண்டுபிடிக்க difficult

  6. Debugging hard

  7. Side effects அதிகம்

  8. Program maintain செய்ய difficult

  9. Large applications-ல் confusion

  10. Prefer

    Function parameters

  11. +

  12. Return values

  13. +

  14. Local variables

  15. when possible.

Explanation
Good style
Instead of

result = 0

def add()

global result

result = 10 + 20

Better

def add(a, b)

return a + b

result = add(10, 20)

இந்த design cleaner.

Explanation
Local to global return
Core idea

Local variable-ஐ outside use செய்ய direct scope change செய்ய வேண்டிய அவசியமில்லை.

Detail 01

return மூலம் value வெளியே அனுப்பலாம்.

Program
Example
Python 3 lines
1def calculate():
2    result = 100
3    return result
Program
Python 1 lines
1x = calculate()
Program
Python 1 lines
1print(x)
Verified output
100
Learning Run Mode — this is the output the author verified, not a live execution.
Output
100

result → local

100

x → global name

Important
Very important connection
  1. Previous topic

    Parameters → data function-க்கு உள்ளே

  2. Return → data function-லிருந்து வெளியே

  3. Scope → variables எங்கே usable?

  4. So function concept

    Arguments

  5. Parameters (Local)

  6. Local Processing

  7. Return Value

  8. Outside variable

Explanation
Legb rule
Core idea

என்று சொல்கிறோம்.

Python variable lookup-க்கு full important rule
  • L → Local
  • E → Enclosing
  • G → Global
  • B → Built-in
இதனை

LEGB Rule

Simple Explanation
Simple legb
Python ஒரு variable name-ஐ தேடும்போது roughly
  1. Local
  2. Enclosing
  3. Global
  4. Built-in
Explanation
Local
Core idea

x = Local.

Current function
def show():
    x = 10
Explanation
Enclosing
Core idea

Nested function-ல் outer function scope.

Program
Example
Python 2 lines
1def outer():
2    x = 10
Program
Python 2 lines
1def inner():
2        print(x)
Verified output
10
Learning Run Mode — this is the output the author verified, not a live execution.
Explanation
Core idea

inner()

Detail 01

outer()

Output
10

inner()-க்கு x local இல்லை.

Outer/enclosing scope-ல் கிடைக்கிறது.

Explanation
Global
Core idea

x = 50

def show()

print(x)

Detail 02

Global x.

Explanation
Built in
Core idea

etc.

Python built-in names
  • print
  • len
  • sum
  • max
  • min
Explanation
Legb memory
Core idea
  • L → Local
  • E → Enclosing
  • G → Global
  • B → Built-in
Easy

Look Everywhere, Get Best என்று memory வைத்துக்கொள்ளலாம்; ஆனால் actual order L-E-G-B.

Concept
Nonlocal brief concept
Context

Local + global scope படிக்கும் போது nonlocal என்ற keyword-யும் தெரிந்திருக்க வேண்டும்.

x = 10

nonlocal x
x = 20
inner()
print(x)
outer()
Output
20

nonlocal என்பது global-க்கு அல்ல.

Nearest enclosing function scope-ல் இருக்கும் variable-ஐ reassign செய்ய.

Comparison
Global vs nonlocal
Core idea
  1. global
  2. Module-level global variablenonlocal
  3. Outer/enclosing function variableஇது advanced exam/interview point.
Important
Mutable object important note
  1. இதைக் கொஞ்சம் carefully புரிந்து கொள்ளுங்கள்.

  2. numbers = [1, 2, 3]

  3. def change()

    numbers.append(4)

  4. change()

  5. print(numbers)

Output
[1, 2, 3, 4]
Context

இங்கே global numbers எழுதவில்லை.

Why?

numbers = ...

என்று name-ஐ reassign செய்யவில்லை.

append()

மூலம் modify செய்கிறோம்.

Explanation
Compare
Core idea

Mutation
numbers.append(4)

Detail 01

Existing object change.

Detail 02

Often global keyword தேவையில்லை.

Detail 03

Reassignment
numbers = [10, 20]

Function உள்ளே global name-ஐ reassign செய்ய வேண்டுமெனில்

global numbers

Detail 05

தேவை.

Detail 06

இது interview-level important concept.

Comparison
Local vs Global
FeatureLocalGlobal
DefinedFunction உள்ளேFunction வெளியே
Accessibleஅந்த local scopeWider module scope
ParametersUsually localNo
Function outside accessNormally noYes
Same name possibleYesYes
Reassign global from function-global keyword
Comparison
global vs returnSuppose function result வெளியே வேண்டும்.
Using global:result = 0
def calculate():global result
result = 50Using return:
def calculate():return 50
result = calculate()Second approach often cleaner.
Important
  1. Scope is about visibility.

  2. எங்கே access செய்யலாம்?

  3. Lifetime is about existence.

  4. எவ்வளவு நேரம் object/name relevant?

  5. Exam questions-ல் இரண்டையும் confuse செய்யக்கூடாது.

Common Mistake
Error 1
Context

Local variable outside access

x = 10
print(x)
Wrong.
Common Mistake
Error 2

Thinking global cannot be used inside function

Wrong.

x = 10

def test():
    print(x)

works.

Common Mistake
Error 3
Context
  • Thinking assignment automatically modifies global
  • x = 10

x = 20

No.

That normally creates local x.

Common Mistake
Error 4
Context
  • Missing global
  • x = 10

x = x + 1

Python considers x local because assignment exists.

But tries to read local x before assigned.

UnboundLocalError

x = 10

global x
x = x + 1
test()
print(x)
Output
11
Common Mistake
Error 5
Context

Overusing global variables

Program work செய்யலாம்.

ஆனால் maintainability குறையும்.

return x + 1

x = 10
x = increment(x)
Memory Trick

Local
Local = Limited

Both start with L.

Local → Limited area

Global
Global = General / wider

Global → Program-level wider access

Global Keyword
READ → global keyword usually வேண்டாம்

REASSIGN → global keyword வேண்டும்

TRB Point

1. Function உள்ளே defined variable?

TRB Point

Local variable

TRB Point

1. Function வெளியே defined variable?

TRB Point

Global variable

TRB Point

1. Global variable-ஐ function உள்ளே read செய்ய முடியுமா?

TRB Point

Yes

TRB Point

1. Global variable-ஐ function உள்ளே reassign செய்ய keyword?

TRB Point

global

TRB Point

1. Function parameter scope?

TRB Point

Usually local scope.

TRB Point

1. Same local/global variable name இருந்தால் function உள்ளே priority?

TRB Point

Local

TRB Point

1. Python variable lookup rule?

TRB Point

LEGB

TRB Point

1. LEGB full form?

TRB Point
  1. Local

  2. Enclosing

  3. Global

  4. Built-in

TRB Point

1. Enclosing variable modify செய்ய keyword?

TRB Point

nonlocal

TRB Point

1. global மற்றும் nonlocal same?

TRB Point

No

Interview Point

Question: What is scope in Python?

Scope defines the region in which a name or variable can be accessed.

Question: What is a local variable?

A variable defined inside a function is generally local to that function.

Question: What is a global variable?

A variable defined at module level, outside functions, belongs to global scope.

Question: Can a function access a global variable?

Yes, for reading it normally can.

Program
Example
Python 1 lines
1x = 10
Program
Python 3 lines
1def show():
2    print(x)
3Question: When is global keyword required?
Verified output
10
Learning Run Mode — this is the output the author verified, not a live execution.
Explanation

When you intend to assign/rebind a global variable from inside a function.

Question

What is variable shadowing?

When a local variable uses the same name as a global variable, the local name hides/shadows the global name within that local scope.

Question

What is LEGB?

Python resolves variable names in approximately this order
LocalEnclosingGlobalBuilt-in
MCQ
152A variable defined inside a function is normally:
Choose one answer
MCQ
153A variable defined outside functions at module level is:
Choose one answer
MCQ
154Which keyword modifies a global name inside a function?
Choose one answer
MCQ
155Output? x = 10 def show(): print(x) show()
Choose one answer
MCQ
15610 1. What is x here? def test(): x = 50
Choose one answer
MCQ
157Parameters normally belong to:
Choose one answer
MCQ
158LEGB begins with:
Choose one answer
MCQ
159Which order is correct?
Choose one answer
MCQ
160Which keyword is associated with enclosing function variables?
Choose one answer
MCQ
161Global variable read inside a function always requires global?
Choose one answer
Practice
Practice 1

Identify Scope
x = 100

def show():
    y = 50
    print(x, y)

Answer:

x
Global
y
Local
Practice
Practice 2

Predict Output
x = 5

def test():
    x = 10
    print(x)

test()
print(x)

Answer:

10
5

Practice
Practice 3

Global Modification
x = 5

def test():
    global x
    x = 10

test()

print(x)
Output
10
Practice
Practice 4

Two Local Scopes
def a():
x = 10
print(x)

def b():
    x = 20
    print(x)

a()
b()
Output
10
20
Practice
Practice 5

Return Local Value
def calculate():
x = 25
return x

result = calculate()

print(result)
Output
25

x local தான்.

ஆனால் its value return மூலம் outside கிடைத்தது.

Summary
  1. Python scope
  2. Scope
  3. ├── Local
  4. │ ↓
  5. │ Function உள்ளேளே
  6. ├── Enclosing
  7. │ ↓
  8. │ Outer function scopepe
  9. ├── Global
  10. │ ↓
  11. │ Function வெளியே / module levelel
  12. └── Built-in
  13. Python built-in names
  14. Main rule
  15. LEGB
  16. Local
  17. Enclosing
  18. Global
  19. Built-in
  20. Most important
  21. Function inside variable → Local
  22. Function outside variable → Global
  23. Global read
  24. print(x)
  25. usuallyworks.
  26. Global reassign
  27. global x
  28. x = 20
  29. needed.
  30. And remember
  31. Local variable same nameஇருந்தால், function உள்ளே local variable-க்கு priority.
Explanation
Short description
Core idea

Scope என்பது ஒரு variable எங்கே accessible என்பதை தீர்மானிக்கும் concept. Function-க்குள் உருவாக்கப்படும் variable பொதுவாக Local Variable; function-க்கு வெளியே module level-ல் உருவாக்கப்படும் variable Global Variable. Global variable-ஐ function உள்ளே read செய்யலாம்; ஆனால் அதை reassign செய்ய global keyword தேவைப்படும். Python variable lookup LEGB - Local, Enclosing, Global, Built-in - என்ற order-ஐ பின்பற்றுகிறது.

Text size
17px
Theme
Contents
Print / PDF
Program