My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMSΒ for Enterprise.
Upgrade ✨Learn more
Understanding Python scope and indentation

Understanding Python scope and indentation

Udokaku Ugochukwu
Β·Jun 21, 2020Β·

8 min read

Python codes are clear and concise codes, easy to understand, and beginner-friendly. Nevertheless, there is a twist to this, inasmuch as python codes are the embodiment of simplicity and conciseness, there are rules to always keep abreast while writing functional codes in python.

In this article, I would focus more on two areas: python scope and indentation. You might be wondering:

  • WHAT IS A PYTHON SCOPE AND HOW IS IT USED IN A SIMPLE PYTHON PROGRAM?

  • WHAT IS PYTHON INDENTATION AND HOW IS IT IMPLEMENTED IN A PYTHON PROGRAM?

  • WHY ARE THESE NECESSARY?

    These are the core subjects I would explain in this article. Relax, take a cup of water and allow me to walk you through this.

WHAT IS A PYTHON SCOPE?

I would like to start by explaining to you, what scope is.

  • A scope in programming is an area of coverage for the execution of sets of instructions.
  • Now, a python scope is simply the area of coverage for variables, functions, libraries, reserved words, or you can simply say, sets of instructions used in a Python programming. It is also important to know that python implements two kinds of variables: the local and global variables. Let's look at what these local and global variables are;

    A variable defined in a python code which is accessible by all program parts like function, is a GLOBAL VARIABLE.

    On the other hand, a variable that can be only used in a specific part program, e.g like in a function is a LOCAL VARIABLE.

Also, local variables in a python program can be made accessible by other parts of a program by using the keyword global just before defining that variable.

Let's look at an example, enter these codes below in your PYTHON IDLE;

#Function to display the value assigned into a variable
def test():         #defining a function test
    global nice     #Initializing the variable "nice" using the keyword global to make it accessible to other programs
    nice = 20       #Assigning a value 20 to the variable "nice"
    return nice     #ending the program executing and returning the value in "nice" to the function "test"
print(test())       #outputting the value of the function"test"


#A new program to add values of variables
sum=2               #assigning the value 2 to the variable "sum"
done=sum+nice       #adding the value in "sum" to the value in the global variable "nice" initialized in the function "test" and assigning it to the variable "done" 
print(done)         #outputting the value assigned to "done" after addition

Note: Using a local variable as a global variable without referencing it using the required keyword global would definitely result in an error.

Now, you have seen how a local variable can be declared to make it a global variable. Let's see how the scope of a variable affects the output, using this example:

In your PYTHON IDLE enter the code below;

  • both1.png

you would see from the above code and output that:-

  • The first initialization of n (global variable, n=500) was not displayed on execution, this is because the python interpreter found another initialization of the same variable,n inside the scope of the function. Note: Different functional variables can be used in python with the same variable name as long as they exist in different scopes in the program.

  • The variable n is repeated and initialized twice, and the python interpreter did not give an error message, this is because the first initialization was done outside the scope of the function making it a global variable and the second initialization was done inside the scope of the function making it a local variable.

  • On execution of the program, the result obtained was 43 and not 500, the interpreter on execution has overridden the value of the global variable with that of the local variable because n=43 is in the scope of the function called on execution.

  • You would also notice that after the function definition, the next lines of codes are indented once under the function. This tells the interpreter that the next sequence of codes is in the scope of the function and would be executed as part of the function statement.

  • Finally, you would see that, when calling the function, there was no form of indentation. This clearly states to the interpreter that a new set of instructions in a different scope from the function is executed. If done differently would result in an error.

WHAT IS PYTHON INDENTATION?

  • Python indentation is simply adding white spaces in python code in order to set variables, libraries, functions, and reserved words to their corresponding scope in a program.

Now let’s see a simple implementation of this in a program, enter the following sets of codes to shown in the snippet below, that displays the greatest of 5 numbers in your PYTHON IDLE.

  • res1.png

the output of this program is seen in the snippet below;

  • we.png

From the above example,

  • First, you can see that after the initialization of the for loop, the next two lines of code (line 3 & 4) are indented beneath it, this is simply because the set of indented instructions is a part of the for loop and would be executed by the interpreter as many times as the range of the for loop is initialized to execute.

  • Also, just after the if statement, the code on line 5 is also indented beneath the if statement. As part of the for loop, the sets of instruction under the if statement would execute when the if statement has checked against its' condition for the number of times specified in the for loop. Now, this is simply because the sets of indented instruction is a part of the for loop and would be executed by the interpreter as many times as the range of the for loop is initialized to execute. Then, the greatest value inputted by the user would be assigned to "num" in line 5 at the end of the for loop after the condition check on the if statement validates it as the greatest.

  • Finally, see that the print statement is not indented but on the same line with the for loop. This tells the interpreter that at the end of this loop, display the value stored in the variable "num" after the condition has been tested by the if statement, and a value is assigned to "num" as the greatest.

WHY ARE THESE NECESSARY?

Python scope and indentation are necessary for writing python codes because:

  • In the absence of proper indentation, your code execution gets terminated without completely executing the required instructions, this is because the python interpreter cannot understand your program syntax and sees this as a syntax error {error due to incorrect arrangement of program codes}, terminates the execution process and flags an error message.
  • Also, using a variable in a scope to which it is not defined would result in an error in program output or an error leading to program termination.

Let us see an example to this, using the example used earlier in "PYTHON INDENTATION" section, remember we want our program to give us the greatest of 5 numbers after entering any 5 numbers.

  • nex.png

and contrast it against these,

  • weeee.png

  • Here notice I indented the PRINT STATEMENT below the "num=gig", this causes the interpreter to immediately output the value in "num" when detected as the highest value, even when the program has not finished executing as expected, and might not execute the PRINT STATEMENT at the end of the program execution if the greatest number is not inputted last.

see this also,

  • okkk.png

  • The print statement is indented directly below the if condition and therefore is executed at the end of every check done in the if statement, this is because it is in the scope of the if statement.

Now you can see for yourself, WHY PYTHON SCOPE AND INDENTATION is important.

Yeh!!!!, we got through on this, I hope you got some new ideas here.

You should change that glass of water to a bottle of wine, you did great. πŸ€—

Kudos to you, Now you understand what these concepts really are.πŸ€—πŸ’ƒπŸ’ƒπŸ’ƒ

Feel free to drop your comment(s).