Translate in Your language

Thursday, 2 April 2020

Learning Python part-10: Python Indentation

Programming languages like C, C++, Java use braces { } to define a block of code. For example, for loop in c++ will look like 

for (int i = 0; i < 5; i++) {
cout << i << "\n";
}


Unlike other languages, Python uses indentation for code blocks. So the above code can simply be written in python as,

for i in range(5):
        print(i)


So what is a code block?

A block is a combination of statements(discussed in previous part). Code block is written as  group of statements in order to perform specific operation. Usually it consists of at least one statement and of declarations for the block, depending on the programming or scripting language. Generally, blocks can contain other blocks inside as well, this is called as nested block structure.


What is indentation:

Well, in simple words, whitespaces are used for indentation in Python. All statements with the same distance from the right belong to the same block of code. If a block requires nested code block, it is simply indented further to the right. Let us see example of this.


In above example, 

  • Initially we declared variables x and y with their values. This will be our first code block.  
  • Later we started for loop which is a second code block, so anything that is part of this block, we added whitespaces and then wrote the statements. 
  • Furthermore, inside for loop, we added if statement which adds nested code block inside for loop, hence, we added extra whitespaces(indent) to write statements of if statement. 
  • Similarly, we started else nested block and that followed same rules as as if block.

Indentation considerations:

  • Generally 4 whitespaces are used for indentation, but we can also use tabs if required.
  • This results into Python programs look similar and consistent.
  • Indentation in Python makes the code look neat and clean.
  • Incorrect indentation will result into IndentationError.
  • The amount of indentation is up to users choice, but it must be consistent throughout the code block.
Example:

If True:
    print(“Hello”)
    a = 5

   print(a)
  • E.g. above code can also be written on single line as 
if True: print('Hello'); a = 5


No comments:

Post a comment

Followers

Popular Posts This Week