Python indentation rules handy guide

Indentation means formatting the source code of Python. The code is the main source in any programming language.

The programming language like Python needs indentation in its source code. Else during compilation it throws an errors. The purpose of this post is to explain indentation rules.

Python Example Source code

Correctly indented Python code

Python Code With Indentation Errors

    def perm(l):         
           # Compute the list of all permutations of l
      if len(l) <= 1:
  return [l]
r = []   
   for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
  for x in p:
    r.append(l[i:i+1] + x)     
return r 

Rules For Indentation

  1. Check first line starts at position ‘1’
  2. Next line starts at first TAB, usually at 4th position
  3. The lines inside logical statements, must start after TAB
  4. This way you can fix all your indentation errors

Syntax Errors

Let us take an example of Python script.

Python py_compile command helps to validate both Indentation and Syntax Errors.

Python script with .py
myscripts.py i have created in Ubuntu OS

Command to compile myscripts.py

$python3 -m py_compile myscripts.py

The above command you can use to find Syntax errors and to compile the code into byte code.

The byte code is platform independent.

You can run the compiled Python code in Windows, Linux, Mac or any.

How Can you check Indentation Errors

py compile in python

Related Posts

Advertisements

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.