Scope of the variables in python:
we are following the rule: LEGB
L means Local
E means Enclosing
G means Global
B means Builtin
Example:
x="global x"
y="global y"
z="global z"
def f1(x):
y="local y"
z="local z"
x="local x"
print(y)
print(z)
print(x)
f1("enclosing z")
Output:
loacl y
local z
local x
Example:
x="global x"
y="global y"
z="global z"
def f1(z):
y="local y"
print(y)
print(z)
print(x)
f1("enclosing z")
Output:
loacl y
enclosing z
global x
Example:
x="global x"
y="global y"
z="global z"
def f1(z,x):
y="loacl y"
print(y)
z=20
print(z)
print(x)
f1("enclosing z","enclosing x")
Output:
loacl y
20
enclosing x
we are following the rule: LEGB
L means Local
E means Enclosing
G means Global
B means Builtin
Example:
x="global x"
y="global y"
z="global z"
def f1(x):
y="local y"
z="local z"
x="local x"
print(y)
print(z)
print(x)
f1("enclosing z")
Output:
loacl y
local z
local x
Example:
x="global x"
y="global y"
z="global z"
def f1(z):
y="local y"
print(y)
print(z)
print(x)
f1("enclosing z")
Output:
loacl y
enclosing z
global x
Example:
x="global x"
y="global y"
z="global z"
def f1(z,x):
y="loacl y"
print(y)
z=20
print(z)
print(x)
f1("enclosing z","enclosing x")
Output:
loacl y
20
enclosing x
No comments:
Post a Comment