What is scope in Python?
Scope is the part of a program where a variable can be used. Python looks for a name in four places, in this order, which is called the LEGB rule.
| Scope | Meaning |
|---|---|
| Local | Names created inside the current function |
| Enclosing | Names in an outer function that wraps the current one |
| Global | Names created at the top level of the file |
| Built-in | Names Python already has, like len and print |
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
print(x)
outer()
print(x)
Output:
Tutorials Class - Output Window
local
enclosing
global
Use the global keyword to change a global variable inside a function, and nonlocal for a variable of the outer function. See Scope of Variables in Python.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |