Exploring Scopes in Functions in python: A Hands-On Guide

Exploring Scopes in Functions in python: A Hands-On Guide

SCOPE

Suppose you are touring a historical place with many monuments. To visit a monument, you have to buy a ticket. Say, you buy a ticket-1 to go see a monument-A. As long as you are inside monument-A, your ticket-1 is valid. But the moment you come out of the monument the validity of ticket-1 is over. You cannot use ticket-1 to visit any other monument. To visit any other monument-B you have to buy another ticket-2. So we can say that the scope of ticket-1 is monument-A and scope of ticket-2 is monument-B.
To promote tourism, the government has also launched a city-based ticket-3. With ticket-3 a person can visit all the monuments in that city.
So the scope of ticket-3 is whole city and all monuments within the city including monument-A and monument-B.

Let us understand scopes in python.

Global Scope VARIABLES

Global scope variables are variables defined outside of any function or block of code in a programming language. These variables are accessible from anywhere within the codebase, including inside functions, classes, or other blocks of code. In many programming languages, global scope variables are declared at the top level of the program.

(Compare with the real life example given above, we can say that ticket-3 has global scope within the city as it is usable in all blocks(monuments) in the city)

Local Scope VARIABLES

Local scope variables are variables defined inside of any function i.e., it can be used only within this function and other blocks contained under it.

(Let us compare with real-life example given above, we can say that ticket-1 and ticket-2 have local scopes within monument-A and monument-B respectively.)

Let us take one more example and understand scopes with executing code line by line:

Line-2: def encountered; line 3,4 ignored.
Line-7: def encountered; 8,9 ignored.

Line-12 and 13: execution of main program begins; global environment created; num1 and num2 added to it.

Line-14: Average function (avg()) is invoked, so local environment for average is created; arguments c and d are created in local environment.

Line-8: Sum function(numsum()) is invoked, so a local environment for numsum() is created nested within local environment of avg(). It’s arguments a and b are created in it.New argument r is created in numsum().

value of s from numsum() is returned to r in avg().

Line-9: return value is calculated and returned to caller satement (line-14)

Line-14: The print function receives computed value and prints it and program is over.

Leave a Reply

Your email address will not be published. Required fields are marked *