Python Code Indentation

Python uses whitespace (eg spaces and tabs) to group together lines of code that belong together.  Any time a line ends with a colon, you are telling Python "hey, a block of code follows" and Python expects to see some indented code.

Example

Python
if x = 1:
   call_functionA()
   call_functionB()
   
next_function()

The code call_functionA and call_functionB will be executed if x equals 1, so they are grouped together with the same indenting.  The code next_function() isn't part of the "if" block so it will be always be executed next, regardless of whether x equals 1 or not.

Example of bad indentation:

In the following code, the second line is not a block.

Python
print('Sane math.')
    print('foobar')

Therefore Python will tell you:

File "test.py", line 2
   print('foobar')
   ^
IndentationError: unexpected indent

Notice how Python tells you the file and line where the indentation problem occurred. Instead you need to do

Python
print('Sane math.')
print('foobar')

Example error when a block not being indented

If you have this code, which defines a function:

Python
def foo():
print('foo')

Python will tell you:

File "main.py", line 2
   print('foo')
   ^
IndentationError: expected an indented block

Here, Python is expecting at least one line of real code -- it can't be just a comment.

Instead you need to do

Python
def foo():
    print('foo')

Notes

Four spaces for indentation is preferred.

Python's indentation is similar to functional programming language syntax but takes a while to get used to if you have used other programming languages that use curly braces { } to indicate a code block. 

Python does not use the semi-colon ; character at the end of code line, unlike many other programming languages.

For readability, the end of a code block should be followed by a blank line, just like you use a blank line between paragraphs:

Example - less readable:

Python
if 1 == 2:
    print('Wow, what kind of math are you using?')
if 2 == 2:
    print('Sane math.')

Example - more readable:

Python
if 1 == 2:
  print('Wow, what kind of math are you using?')

if 2 == 2:
  print('Sane math.')