Python Scope 3
Total Page:16
File Type:pdf, Size:1020Kb
Class XII Computer Science : Python (Code: 083) Chapter: Functions Chapter : Functions Topics Covered: 1. Functions: scope Learning Outcomes: In this tutorial, we’ll learn: 1. What scopes are and how they work in Python 2. Why it’s important to know about Python scope 3. What is the LEGB rule 4. Using Python global statement and nonlocal statement Youtube Video Tutorial: 1. https://www.youtube.com/watch?v=07w3KkQqgi0 2. https://www.youtube.com/watch?v=R5uLNhRaGD0 3. https://www.youtube.com/watch?v=NdlWHlEgTn8 Python Scope Scope of a name (variables, functions etc) is the area of code where the name is created and can be used or accessed. A variable is only available from inside the region it is created. This is called scope. The scope of a name or variable depends on the place in our code where we create that variable. The Python scope concept is generally presented using a rule known as the LEGB rule. LEGB stand for Local, Enclosing, Global, and Built-in scopes. These are the names of Python scopes and also the sequence of steps that Python follows when accessing names in a program. Therefore in python there are 4 scopes 1. Local scope 2. Enclosing scope 3. Global scope 4. Built in scope 1 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Local Scope A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. Example A variable created inside a function is available inside that function only: def myfunc(): x= 300 print(x) myfunc() print(x) # error, because x is created inside myfunc(), so it is available inside that function only Enclosing Scope (Function Inside a Function) A variable is available inside that function only in which it is created. It is not available outside the function, but it is available for a function which is created inside the function: Example The local variable can be accessed from a function created inside the function: def myfunc(): x= 300 # inside myfunc() def myinnerfunc(): # function inside myfunc() print(x) # inside myinnerfunc(). x is a outer variable created inside myfunc() myinnerfunc() # inside myfunc() myfunc() # outside 2 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Outer’s variables have a larger scope and can be accessed from the enclosed function myinnerfunc(). This is an Enclosing scope. Global Scope A variable created in the main body (outside of any function) of the Python code is a global variable and belongs to the global scope and available for all the functions. Global variables are available from within any scope, global and local. Example A variable created outside of a function is global and can be used by anyone: x = 300 # global variable, outside of function def myfunc(): print(x) # accessing inside myfunc() myfunc() # calling myfunc(), that will access and print global x print(x) # accessing and printing from outside (main body of program) Output: 300 300 Naming variables If there are the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function): 3 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Example In the below code function will print the local x, and then the code will print the global x: x = 300 # it is global x def myfunc(): x = 200 # it is local x print(x) # print local x created inside function # main body of program start here myfunc() # calling myfunc(), it will print local x (value 200) created inside that function print(x) # print global x (value 300) created outside the function, main body can access only global variables Output: 200 300 Global Keyword Global keyword is a keyword that allows us to modify an outside variable (global variable). It is used to create global variables from a local scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing a global variable inside a function. Rules of global keyword: 1. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. 2. Variables that are only referenced inside a function are implicitly global. 3. We Use global keyword to use a global variable inside a function. 4. There is no need to use global keyword outside a function. 4 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Use of global keyword: To access or print a global variable inside a function there is no need to use global keyword inside a function. It is needed when we change the value of a global variable inside a function. # Python program showing no need to use global keyword for accessing or printing a global value # global variable a = 15 b = 10 # function to perform addition def add(): c = a + b # only using / accessing global variables print(c) # calling a function add() Output: 25 If we need to assign a new value to a global variable then we can do that by declaring the variable as global. Python Code : Without global statement # Python program showing to modify a global value without using global keyword a = 15 # creating global variable a # function to change a global value def change(): 5 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions # increment value of a by 5 a = a + 5 print(a) change() Output: UnboundLocalError: local variable 'a' referenced before assignment This output is an error because we are trying to assign a value to a variable in an outer scope (global scope). This can be done with the use of global variable. Python Code : With global statement # Python program to modify a global value inside a function x = 15 # global variable def change(): global x # using a global keyword # increment value of a by 5 x = x + 5 print("Value of x inside a function :", x) change() print("Value of x outside a function :", x) Output: Value of x inside a function : 20 Value of x outside a function : 20 In the above example, we first define x as global keyword inside the function change(). The value of x is then incremented by 5, ie. x=x+5 and hence we get the output as 20. 6 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions We can see by changing the value inside the function change(), the change is also reflected outside the function. Global Variables in Nested Functions What will happen If we use the global keyword inside nested functions. The following example shows a situation where a variable 'city' is used in various scopes: def outer(): city = "Hamburg" def inner(): global city city = "Geneva" # changing the value of city variable inside inner() print("Before calling inner(): " + city) print("Calling inner() now:") inner() print("After calling inner(): " + city) # main body start here outer() print("Value of city in main body: " + city) Output: Before calling inner(): Hamburg Calling g now: After calling inner(): Hamburg Value of city in main body: Geneva We can see that the global statement inside the nested function inner() does not affect the variable 'city' of the function outer(), i.e. it keeps its value 'Hamburg'. We can also see from this example that after calling outer() a variable 'city' exists in the main namespace and has the value 'Geneva'. 7 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions From this example it is clear that if we use global keyword inside a nested function and make any change to the value of a variable created in its outer function then this change is not reflected in its outer function. But it is reflected in main body of program If we need to reflect this change in its outer function also then we have to use nonlocal keyword instead of global keyword. nonlocal keyword nonlocal keyword have a lot in common with global keyword. But nonlocal keyword is used inside a nested function only and its change is reflected in outer function also. Example-1: def outer(): city = "Hamburg" def inner(): nonlocal city city = "Geneva" # changing the value of city variable inside inner() print("Before calling inner(): " + city) print("Calling inner() now:") inner() print("After calling inner(): " + city) # main body start here outer() print("Value of city in main body: " + city) Output: Before calling inner(): Hamburg 8 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Calling inner() now: After calling inner(): Geneva # now the change is reflected in outer() Value of city in main body: Geneva Example-2: def outer(): city = "Munich" def inner(): nonlocal city city = "Zurich" print("Before calling inner(): " + city) print("Calling inner() now:") inner() print("After calling inner(): " + city) # main body city = "Stuttgart" outer() print("'city' in main: " + city) Output: Before calling inner(): Munich Calling inner() now: After calling inner(): Zurich 'city' in main: Stuttgart # now value of city is from main body 9 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Now see another example using nonlocal keyword inside a function which is not a nested function Example-3 def myfunc(): # it is not a nested function nonlocal city print(city) # main body city = "Frankfurt" myfunc() Output: File "<ipython-input-9-97bb311dfb80>", line 2 nonlocal city ^ SyntaxError: no binding for nonlocal 'city' found The above output shows an error message, this shows that nonlocal keyword can not be used inside myfunc() (which is not a nested function).