Python indentation 2 or 4 spaces

If you're the only coder working on your source file and there are no coding standards that enforce a particular style, use whatever you're comfortable with. Personally (and in line with our coding standard), I use hard tabs so that whoever is looking at the code can use their own preference.

To make a change, you simply need to change all start-of-line spaces to ones that are twice as large. There are many ways to do this; in the Vim text editor, I can think of two: firstly:

:%s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)

This is a simple regular expression that looks for one or more pairs of spaces at the start of the line and replaces them with twice as many spaces as were found. It can be extended to do all files by opening vim with:

vim *.py

(or the equivalent), followed by (untested):

:argdo %s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)/ | w

Alternatively:

" Switch to hard tabs:
:set noexpandtab
" Set the tab stop to the current setting
:set tabstop=2
" Change all spaces to tabs based on tabstop
:retab!
" Change the tab stop to the new setting
:set tabstop=4
" Go back to soft tabs
:set expandtab
" Replace all the tabs in the current file to spaces
:retab

Of course, many other tools will offer similar features: I would be surprised if something like sed, awk, perl or python couldn't do this very easily.

I'm currently reading the Python introduction by google, and I'm intrigued as to why the standard spacing is recommended to be 4 but google uses 2:

A common question beginners ask is, "How many spaces should I indent?" According to the official Python style guidelines (PEP 8), you should indent with 4 spaces. (Fun fact: Google's internal style guideline dictates indenting by 2 spaces!)

Why would their internal style guideline recommend a standard of two spaces instead of the normal 4? Is it related to how using * and + are "overload" operators as the introduction says? Would a py script that uses 2 spaces instead of 4 run quicker, or am I on the wrong hunch?

In the code comment, we hinted that * works faster than +, the reason being that * calculates the size of the resulting object once whereas with +, that calculation is made each time + is called. Both + and * are called "overloaded" operators because they mean different things for numbers vs. for strings (and other data types).

https://developers.google.com/edu/python/introduction

Learn about Indentation in Python.

Overview

Indentation in Python Programming is simply the spaces at the beginning of a code line. Indentation in other languages like c, c++, etc., is just for readability, but in Python, the indentation is an essential and mandatory concept that should be followed when writing a python code; otherwise, the python interpreter throws IndentationError.

To understand this topic, you should have some knowledge of the following Python Programming topics:

  • Python Syntax
  • Comments in Python
  • Scope of Variable in Python

Scope of article

  • In this topic, we are going to learn about Indentation in Python.
  • We will learn a few rules on indentation with some example codes.
  • Then, we will discuss some advantages and disadvantages of indentation.

What is Indentation in Python

Indentation is the leading whitespace ( spaces and tabs ) before any statement in Python. The reason why indentation is important in python is that the indentation serves another purpose other than code readability. Python treats the statements with the same indentation level (statements with an equal number of whitespaces before them) as a single code block. So whereas in languages like c, c++, etc. a block of code is represented by Curly braces { }, in python a block is a group of statements that have the same Indentation level i.e same number of leading whitespaces.

Python indentation 2 or 4 spaces

Below are some of the observations that can be made from the above figure:
  • All the statements which are on the same level of Indentation(Same no of whitespaces before them) belong to a single block, so from the above diagram, statements in line 1, line 2, and line 7 belong to a single block, and the block has the zero or lowest level of indentation. Statements 3 and 5 are indented one step, forming another block at the first level of indentation. Similarly, statements 4 and 6 are indented two steps, so they together form another block at the second level of indentation.
  • Below the line 2 statement, which is an if statement, statements 3 and 5 are indented one step; hence, they belong to a single block. And since line 2 is an if statement, the block indented below the if forms the body of if. So here, the body of the if statement at line 2 includes all the lines that are indented below it, i.e., lines 3,4,5 and 6.
  • Now that we know that statement at line numbers 3,4,5 and 6 forms the body of the if statement at line 2. Let us understand the indentation for them. Statements at 3 and 5 are uniformly indented, so they belong to a single block (block2 from the interpretation), and they will be executed one by one.
  • Statement at line 4 makes up the body of the if statement at line 3, as we know any statements that are indented below an if form the body of if statement, similarity the statement at line 6 makes up the body of else statement at line 5.
  • This is how the indentation helps define the blocks and also to identify to which statements the block belongs.
  • The execution starts at line 1 followed by the statement at line 2; if the condition is evaluated and in case it returns true, then control goes inside the body of the if statement, which brings statements 3,4, 5, and 6 to the picture.
    • Now, the statement at line 3 is executed, and if the condition is evaluated, in case it returns true, then line 4 is executed, after which control goes to line 7. If the condition at line 3 returns false, then control goes to another statement that is line 5, and then line 6 is executed, followed by the statement at line 7.
  • In case condition at line number 2 returns false, the control skips lines 3, 4, 5, and 6 and goes to the statement at line 7.

Examples

Example 1: Below is an example code snippet with the correct indentation in python.

name = 'Rahul'
  
if name == 'Rahul':
   print('WelCome Rahul..')
   print('How are you?')
else:
   print('Dude! whoever you are ')
   print('Why you here?')
 
print('Have a great day!')

Output:

WelCome Rahul..
How are you?
Have a great day!

Explanation:

  • The name variable gets assigned to Rahul in the first statement
  • Now the statement if name == ‘Rahul’: is evaluated, it returns true, so it executes the body of the if, which is the indented next two statements below the if statement. The two statements inside the body are print(‘WelCome Rahul..’) and print(‘How are you?’) and they get executed.
  • Once the statement gets executed the else part is skipped and control goes to the next statement which is print(‘Have a great day!’), which is executed.
  • In this program, the statements inside the bodies of if and else are indented.

Example 2: Below is an example code snippet with correct indentation.

i = 1
while(i <= 6):
    print("Value is " + str(i))
    i = i + 1

Output:

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is 6

Explanation:

  • Variable i is initialized to 1 in the first statement
  • Now while(i <= 6) is executed which is true, so the body of the while is executed. The body of the while is all the statements that are indented below the while loop.
  • So print (“Value is” + str(i)) and i = i + 1 are executed.
  • This process is repeated till the while condition returns false.
  • Here the statements print (“Value is ” + str(i)) and i = i + 1are uniformly indented to form a block and also the body of the while statement.

How to indent your python code

Let us walk through how to indent a python code by taking a simple example.

Example: Check if a given number is even or odd and if it’s zero print neither even nor odd

Let us discuss the approach step-wise:

  • The first step is to assign an integer variable with the input number.
  • Write an if-else block to check if the input number is 0,
    • If It is not zero, Inside the if block, write another if-else (inner if-else) block to check the condition number % 2 == 0(This is the even check for a given number)
      • If the condition number % 2 == 0 is true, print that the number is even.
      • If the condition number % 2 == 0 is false, then the number is odd in the else block print.
  • If the number is zero, Inside the outer else block print that the given number is neither even nor odd.

Program:

number = 50

if(number != 0):
 if(number % 2 == 0):
   print("Given number is Even")
 else:
   print("Given number is Odd")
else:
 print("Given number is neither even nor odd")

Output:

Explanation:

  • At the first level of the indentation line, numbers 1, 3, and 8 belong to a single block.
  • Execution starts from line 1 and is followed by line 3.
  • At line 3, the if condition is evaluated, and since the number != 0 returns True, control goes inside the if condition, which is the indented block of statements below the if at line 3.
  • Inside the if block
    • Line no 4 and 6 are on the same indentation level( Second indentation level), so they belong to a single block
    • The if condition at line no 4 is evaluated, and since 50 % 2 == 0 returns True, control goes inside the if statement at line 4. So control goes to line 5, and the print statement is executed.
  • Control late skips the else block inside the inner if-else and the else block of the outer if-else and goes to the statement below line 9.

How to avoid python indentation errors

  1. Python will throw an indentation error if you skip the indentation. For Example, the below code would throw IndentationError: expected an indented block error:

Wrong Indentation(Error):

if( 1 == 1):
print("This is test code")

With Correct Indentation:

if( 1 == 1):
  print("This is test code")

  1. The number of whitespaces in indented code should be the same for the same block of code. Otherwise, Python will throw IndentationError: unexpected indent.

Wrong Indentation(Error):

if( 1 == 1):
 print("This is test code")
     print("This is test code1")

With Correct Indentation:

if( 1 == 1):
 print("This is test code")
 print("This is test code1")

  1. Indentation on the first line of code is not allowed. Python will throw IndentationError: unexpected indent.

Wrong Indentation(Error):

if( 1 == 1):
print("This is test code")
print("This is test code1")

With Correct Indentation:

if( 1 == 1):
 print("This is test code")
 print("This is test code1")

  1. Indented statements should have an attaching statement; for instance, all the statements indented below form a block and belong to the if statement. This is applicable for while, for, functions , classes, etc in python. The below example makes this point clear.

Wrong Indentation(Error):

if( 1 == 1):
   print("This is test code")
 
 print("This is test code1")

The above program will throw the “IndentationError: unindent does not match any outer indentation level” error because the last print statement, which is indented, does not match with any other indentation(no attaching outer statement). In the program, hence this will throw an error.

Correct Indentation:

if( 1 == 1):
   print("This is test code")
 
   print("This is test code1")

Here the last print statement’s indentation matches with the indentation of the print statement below if block. Hence here, the outer attaching statement is the if statement.

Python Indentation Rules

  • Python uses four spaces as default indentation spaces. However, the number of spaces can be anything; it is up to the user. But a minimum of one space is needed to indent a statement.
  • The first line of python code cannot have an indentation.
  • Indentation is mandatory in python to define the blocks of statements.
  • The number of spaces must be uniform in a block of code.
  • It is preferred to use whitespaces instead of tabs to indent in python. Also, either use whitespace or tabs to indent; intermixing of tabs and whitespaces in indentation can cause wrong indentation errors.

Benefits of Indentation in Python

  • Indentation of code leads to better readability, although the primary reason for indentation in python is to identify block structures.
  • Missing { and } errors that sometimes popup in c,c++ languages can be avoided in python; also the number of lines of code is reduced.

Disadvantages of indentation in Python

  • Code must be carefully indented with proper no of whitespace and ensure that whitespaces' uniformity is maintained in a single block. If the number of lines in python code is huge, sometimes this can become tedious if the indentation is corrupted by chance.
  • Without the use of good editors/Ide’s that help with the indentation, writing a python code, especially huge lines of code, is sometimes a tedious task because, for each line, we should make a type in the indentation as well.

Conclusion

We have reached the end of the article. Python indentation is something that is a foundation concept for any new python programming, understanding how indentation works are the first step before you can start writing code in python.

How many spaces do I indent in Python?

Note: Python uses 4 spaces as indentation by default. However, the number of spaces is up to you, but a minimum of 1 space has to be used.

Should a tab be 2 or 4 spaces?

If you represent the indents using space characters (ASCII SP), then 2 spaces is 2 characters fewer than 4 spaces. If you allow TAB characters to be used, then (on Windows) a TAB indents by up to 4 spaces, so TAB characters result in fewer characters.

What does indent 4 mean in Python?

Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code.

How many spaces should be left for indentation?

Standard paragraph indentation is about five spaces or one-quarter to one-half of an inch, depending on which style guide you follow. In online writing, if your software doesn't allow indentation, insert a line space to indicate a new paragraph.

Does Python prefer tabs or spaces?

Tabs or Spaces? Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs. Python disallows mixing tabs and spaces for indentation.

Why does the code under the if need to be indented four spaces in Python?

The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python. In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to.