What is unexpected indent in python?
Situations when you can come across an unexpected indent error in Python.
- def test():
- print("Hello World")
- print("Learning Python")
- 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
- def test():
- print("hello world")
- print("Learning Python")
- 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
- def test():
- print("Hello World")
- test()
Now what is expected is and the correct way to do is
- def test():
- print("Hello World")
- 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
- def test(a):
- print("Hello World")
- if a > 2:
- print("Thanks for each and everything")
- a=3
- 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.
Articoli simili
- Python 'SyntaxError: unexpected character after line continuation character' occurring?
- È consigliabile imparare Tkinter in Python per avanzare la propria carriera o per ottenere una migliore offerta di lavoro come sviluppatore Python?
- Come eseguire uno script Python senza installare Python
- Come azienda tecnologica, Amazon usa più Python che R per i progetti di Data Science?