Python Indentation Rules Handy Guide

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

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

Python Example Source code

Correctly indented Python code

How to Find Indentation Errors in Python.

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 

How to Avoid Indentation Errors in Python

  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 i have created in Ubuntu OS

The Command You Need to Compile Python Script:

$python3 -m py_compile

Use this command to compile Python source 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

Author: Srini

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