Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
65 views

04 - Lab08 - Supplement - ScopeOfVariables in Python

The document discusses variable scope in Python. There are four scopes: local, enclosing, global, and built-in. The LEGB rule determines which variable is used when the same variable name is defined in multiple scopes. Local scope refers to variables defined inside a function. Global variables are defined outside all functions. The built-in scope contains keywords and functions like print(), len(), etc. Enclosing scope provides access to outer function variables from nested inner functions.

Uploaded by

mohammed ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

04 - Lab08 - Supplement - ScopeOfVariables in Python

The document discusses variable scope in Python. There are four scopes: local, enclosing, global, and built-in. The LEGB rule determines which variable is used when the same variable name is defined in multiple scopes. Local scope refers to variables defined inside a function. Global variables are defined outside all functions. The built-in scope contains keywords and functions like print(), len(), etc. Enclosing scope provides access to outer function variables from nested inner functions.

Uploaded by

mohammed ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Scope of Variables in Python

The part of a program where a variable is accessible is called its scope. A variable in Python can have one of
four different scopes: local, enclosing, global, and built-in. These scopes together form the basis for the LEGB
rule (Local -> Enclosing -> Global -> Built-in) used by the Python interpreter when working with variables.

Local Scope
Whenever you define a variable within a function, its scope lies ONLY within the function, i.e., when
a variable is assigned within a function, it is treated as a local variable by default in Python. It is accessible
from the point at which it is defined until the end of the function and exists for as long as the function is
executing. Which means its value cannot be changed or even accessed from outside the function.

Local scope Example01:

def print_number():
first_num = 1
# Print statement 1
print("The first number defined is: ", first_num)

print_number()
# Print statement 2
print("The first number defined is: ", first_num)

Output:
The first number defined is: 1
---------------------------------------------------------------------------
NameError: name 'first_num' is not defined

We were able to print the first_num variable by calling the function print_number() (# Print statement 1). But
when trying to access and then print the same variable from outside the function (# Print statement 2), it raised
a NameError exception. This is because first_num is "local" to the function - thus, it cannot be reached from
outside the function body.

Local scope Example02:

y = 12
def myfunction():
y = 5
print(y)

myfunction()
print(y)

Output:
5
12
---------------------------------------------------------------------------------------------------------------------------------------
y = 12

def myfunction():
print(y)
y = 5
Page 1 of 7
myfunction()
print(y)

Output:
UnboundLocalError: local variable 'y' referenced before assignment

To resolve an UnboundLocalError when the local variable is reassigned after the first use, you can use
the global keyword. The global keyword allows you to modify the values of a global variable from within a
function’s local scope.

y = 12
def myfunction():
global y
print(y)
y = 5

myfunction()
print(y)

Output:
12
5

Enclosing Scope [Optional]


What if we have a nested function (function defined inside another function)? How does the scope change? Let
us see with the help of some examples.

def outer():
first_num = 1
def inner():
second_num = 2
# Print statement 1 - Scope: Inner
print("first_num from outer: ", first_num)
# Print statement 2 - Scope: Inner
print("second_num from inner: ", second_num)

inner()

outer()

Output:
first_num from outer: 1
second_num from inner: 2

Note: The inner function can access first_num; but it cannot modify it. This is an enclosing scope. Outer's
variables have a larger scope and can be accessed from the enclosed function inner(). The following will cause
an error:

def outer():
first_num = 1
def inner():
Page 2 of 7
second_num = 2
# Print statement 1 - Scope: Inner
first_num += 25
print("first_num from outer: ", first_num)
# Print statement 2 - Scope: Inner
print("second_num from inner: ", second_num)

inner()

outer()

Output:
UnboundLocalError: local variable 'first_num' referenced before assignment

Because of the assignment, first_num is now treated as a local variable within the inner function. To resolve this
error, use the nonlocal keyword. The nonlocal keyword allows you to modify the values of a variable defined in
an outer function scope from within a nested function’s local scope:

def outer():
first_num = 1
def inner():
nonlocal first_num
second_num = 2
# Print statement 1 - Scope: Inner
first_num += 25
print("first_num from outer: ", first_num)
# Print statement 2 - Scope: Inner
print("second_num from inner: ", second_num)

inner()

outer()

In the following example, the variable first_num can be accessed within the inner function (but without being
modified). The variable second_num cannot be accessed from the outer scope, because its scope is only within
the inner function:

def outer():
first_num = 1
def inner():
second_num = 2
# Print statement 1 - Scope: Inner
print("first_num from outer: ", first_num)
# Print statement 2 - Scope: Inner
print("second_num from inner: ", second_num)

inner()
# Print statement 3 - Scope: Outer
print("second_num from inner: ", second_num)

outer()
Page 3 of 7
Output:
first_num from outer: 1
second_num from inner: 2
---------------------------------------------------------------------------
NameError: name 'second_num' is not defined
---------------------------------------------------------------------------------------------------------------------------------------
def outer():
first_num = 1
def inner():
first_num = 0 # local first_num that is different from outer first num
second_num = 1
print("inner - second_num is: ", second_num)

inner()
print("outer - first_num is: ", first_num)

outer()

Output:
inner - second_num is: 1
outer - first_num is: 1
---------------------------------------------------------------------------------------------------------------------------------------

def outer():
first_num = 1
def inner():
nonlocal first_num # declare first_num to be the outer one
first_num = 0
second_num = 1
print("inner - second_num is: ", second_num)
inner()
print("outer - first_num is: ", first_num)

outer()

Output:
inner - second_num is: 1
outer - first_num is: 0

Global Scope
Whenever a variable is defined outside any function, it becomes a global variable, and its scope is from the
point it is defined to the rest of the program. This includes variables defined in if, elif, else, for, while blocks
and with statement that are outside functions.

greeting = "Hello"
def greeting_world():
world = "World"
print(greeting, world)

def greeting_name(name):
print(greeting, name)

Page 4 of 7
greeting_world()
greeting_name("Samuel")

Output:
Hello World
Hello Samuel

---------------------------------------------------------------------------------------------------------------------------------------------------
x = 4
y = 5
print("y = ", y)
if y >= 5:
z = 12
y += (x * 2)

print("y =", y)
print("z =", z)

for k in range(3):
print(z, " ", end = " ")

print("\nk =", k)

Output:
y = 5
y = 13
z = 12
12 12 12
k = 2

---------------------------------------------------------------------------------------------------------------------------------------

greeting = "Hello"
def change_greeting(new_greeting):
greeting = new_greeting # creates a new local greeting object
# that is different from the global greeting object

def greeting_world():
world = "World"
print(greeting, world) # uses the global greeting object

change_greeting("Hi")
greeting_world()

Output:
Hello World
---------------------------------------------------------------------------------------------------------------------------------------

greeting = "Hello"
def change_greeting(new_greeting):
global greeting
greeting = new_greeting # Assigning reference of new object to global
# greeting object.

Page 5 of 7
def greeting_world():
world = "World"
print(greeting, world)

change_greeting("Hi")
greeting_world()
Output:
High World

Built-in Scope
This is the widest scope that exists! All the special reserved keywords fall under this scope. We can access the
keywords or call built-in functions anywhere within our program without having to define them before use.
Keywords are simply special reserved words. They are kept for specific purposes and cannot be used for any
other purpose in the program.

Some Python keywords:


 Value Keywords: True, False, None.
 Operator Keywords: and, or, not, in, is.
 Control Flow Keywords: if, elif, else.
 Iteration Keywords: for, while, break, continue, else.
 Structure Keywords: def, class, with, as, pass, lambda.
 Returning Keywords: return, yield.
 Import Keywords: import, from, as.

Some Python built-in functions:

abs() ascii() int() type()

min() ord() float() range()

max() chr() hex() id()

round() str() format()

sum() len() input()

pow() print()

divmod()

Some Python modules:


math, cmath, radom, string, sys, time, calendar

LEGB Rule
LEGB (Local -> Enclosing -> Global -> Built-in) is the logic followed by a Python interpreter when it is
executing your program.

Page 6 of 7
Let us say you are calling print(x) within inner(), which is a function nested in outer(). Then Python will first
look if x was defined locally within inner(). If not, the variable defined in outer() will be used. This is the
enclosing function. If it also was not defined there, the Python interpreter will go up another level - to the global
scope. Above that, you will only find the built-in scope, which contains special variables reserved for Python
itself.

Page 7 of 7

You might also like