Wednesday, August 21, 2019

Python : IndentationError: expected an indented block

Initial learning of Python in IDLE, while executing While or For Loop examples like below, you will end up with "IndentationError: expected an indented block".

Example Error:

>>> z = ['a','b','c','d','e']
>>> i = 0
>>> while i < len(z):
... print(i, z[i])
  File "<stdin>", line 2
    print(i, z[i])
        ^
IndentationError: expected an indented block

>>> z = ['a','b','c','d','e']
>>> for i in range(0, len(z)):
... print(i, z[i])
  File "<stdin>", line 2
    print(i, z[i])
        ^
IndentationError: expected an indented block


Solved Example :

>>> z = ['a','b','c','d','e']
>>> i = 0
>>> while i < len(z):
...    print(i, z[i])
...    i += 1
...
0 a
1 b
2 c
3 d
4 e

>>> z = ['a','b','c','d','e']
>>> for i in range(0, len(z)):
...     print(i, z[i])
...
0 a
1 b
2 c
3 d
4 e

Solution :

 Should use Minimum 2 spaces or 4 Spaces on highlighted area in examples.
 

No comments:

Post a Comment