QNA > W > What Is Unexpected Indent In Python?

What is unexpected indent in python?

Situations when you can come across an unexpected indent error in Python.

  1. def test(): 
  2. print("Hello World") 
  3. print("Learning Python") 
  4.  
  5. test() 

Now, Ideally what is expected was the print statement in Line No. 3 should have started from exactly the place from where print statement in Line No. 2 has started. Which means

  1. def test(): 
  2. print("hello world") 
  3. print("Learning Python") 
  4.  
  5. test() 

But, now that we gave an indentation that was not needed in line No. 3. On running the program we would get a error message saying

IndentationError: Unexpected Indent.

Try mixing the tabs and spaces while you indent the code. You will come across the same error. Or an error which explicitly states something similar to mixed usage of tabs and spaces.

Other possible Indentation error include

IndentationError: Expected an indented block.

This error comes when it was expected to give indentation but you ended up missing out on giving the indentation. Like in the below mentioned example

  1. def test(): 
  2. print("Hello World") 
  3.  
  4. test() 

Now what is expected is and the correct way to do is

  1. def test(): 
  2. print("Hello World") 
  3.  
  4. test() 

As per Python style guide PEP8. It is recommended to use spaces over tabs. Indent using spaces in multiple of 4. PEP 8 -- Style Guide for Python Code

So, the next time you code try doing

  1. def test(a): 
  2. print("Hello World") 
  3. if a > 2: 
  4. print("Thanks for each and everything") 
  5. a=3 
  6. test(a) 

So, line 2, 3 uses 4 space for indentation. While line 4 uses 8 spaces (multiple of 4).

It’s clean.

Hope it’s useful.

Di Milstone Jovanovic

Come mostrare il mio talento :: Come funziona la gestione dei talenti in India?
Link utili