The scope of a variable is defined by where the variable can be accessed with respect to where the variable is declared. In Python, a variable can have local, non-local, enclosing, and global scope as explained in the below Python variable scope example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
## -------------- ## Variable scope ## -------------- ## local scope del a # remove a variable def my_fun(): # create a function with variable a a = 10 print("a =",a) my_fun() # call the function, print a = 10 print("a =",a) # error, variable is not accessible outside function # since the scope is local ## enclosing scope del a # remove a variable def my_fun1(): # created two nested functions a = 10 print("my_fun1 | a =",a) # local scope def my_fun2(): b = 20 print("my_fun2 | a =",a) # enclosing scope print("my_fun2 | b =",b) # local scope my_fun2() # function call print("my_fun1 | b =",b) # out of scope error my_fun1() # fucntion call ## global scope b = 20 def my_fun1(): # created two nested functions a = 10 def my_fun2(): print("my_fun2 | a =",a) # enclosing scope print("my_fun2 | b =",b) # global scope my_fun2() # function call print("my_fun1 | a =",a) # local scope print("my_fun1 | b =",b) # global scope my_fun1() print(a) # out of scope error print(b) # global scope ## nonlocal & inbuilt scope b = 50 def my_fun1(): # created two nested functions a = 10 c = 100 def my_fun2(): nonlocal c c = 500 print("my_fun2 | a =",a) # enclosing scope print("my_fun2 | b =",b) # global scope print("my_fun2 | c =",c) # nonlocal scope my_fun2() # function call print("my_fun1 | a =",a) # local scope print("my_fun1 | b =",b) # global scope print("my_fun2 | c =",c) # nonlocal scope my_fun1() # function call print(a) # out of scope error print(b) # inbuilt scope print(c) # out of scope error |