Python Functions and Variable Scope – Local vs Global for GATE CSE 2026
Function Scope is a very tricky topic in GATE CSE. Many students make mistake here.
What is Function in Python?
Function is a block of code that runs only when called. Use def keyword.
def greet():
print("Hello GATE Aspirants")
greet() # Function call
Types of Variable Scope – GATE Favorite
1. Local Scope
Variable defined inside function. Can be used only inside function.
def fun():
x = 10 # Local variable
print(x)
fun()
# print(x) -> ERROR, x not defined outside
2. Global Scope
Variable defined outside function. Can be used everywhere.
x = 10 # Global
def fun():
print(x) # Can access global
fun() # Output: 10
3. LEGB Rule – Very Important for GATE
Python searches variable in this order:
L = Local -> E = Enclosing -> G = Global -> B = Built-in
GATE PYQ on Scope
Q1. GATE CSE 2020 – Global vs Local
x = 5
def fun():
x = 10
print(x)
fun()
print(x)
Ans: 10, 5. Inside function local x=10, outside global x=5.
Q2. GATE CSE 2019 – Using global keyword
x = 5
def fun():
global x
x = 10
print(x)
fun()
print(x)
Ans: 10, 10. Because global keyword changed global x.
Q3. GATE CSE 2022 – Enclosing Scope
def outer():
x = 10
def inner():
print(x)
inner()
outer()
Ans: 10. inner() can access enclosing scope variable x.
Call by Value vs Call by Reference – GATE Concept
| Type | Mutable (List) | Immutable (Int, Tuple) |
|---|---|---|
| Pass to function | Call by Reference – Original changes | Call by Value – Original NOT changes |
# List example - Original changes
def fun(a):
a[0] = 100
l = [1,2,3]
fun(l)
print(l) # [100,2,3] - Changed!
# Int example - Original NOT changes
def fun(a):
a = 100
x = 5
fun(x)
print(x) # 5 - NOT changed
Conclusion
For GATE remember: Local > Global, List changes in function, Int does not change. Practice 10 scope questions.
Next Post: Binary Search Algorithm GATE.
