Sitemap
CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Member-only story

LEGB — Variable Scope in Python

5 min readJul 25, 2021

--

Press enter or click to view image in full size
Photo by James Lee on Unsplash

Each programming language has its own variable scope. For python, we could simply follow the LEGB rule that includes

Local, Enclose, Global, and Built-in.

In this article, we will use a few examples to understand their feature and how to access objects of different scopes.

Local; Enclose; Global Variable

We start from this example first

There are three variables with the same name called x, which represent different scopes.

x = 'global var'def outer():
# y is local variable for outer(), enclose variable for inner()
x = 'enclose var'
def inner():
x = 'local var'
print('inner: {}'.format(x))
inner()
print('outer: {}'.format(x))
outer()
print(x))
>>>>>>>>>>>>>>>>>>>>>>>>>
inner local var
outer enclose var
global var

Any variable outside a function is a global variable, and a variable inside a function is a local variable. If there is an outer function and an inner function, then the x in the inner function is a local variable, and the x in the outer function is an enclose variable of the internal…

--

--

Allie Hsu
Allie Hsu

Written by Allie Hsu

A tech enthusiast who is keen to develop new skills

CodeX
CodeX

Published in CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers