Indentation in Python (IndentationError: unexpected indent)

Hello! A demo of identation in Jupyter notebook may be useful, and this thread is tailored to what we usually see in our courses. Comments welcomed for continuous development of this!

Rules/suggestions:

  1. Python style guide recommends using four spaces per indentation level. Suggest to stick with this throughout the notebook and be careful not to mix up a “Tab” with “Spaces”.
  2. We use indentation to group compround statements. Any content belonging to any one of the following statements has one indentation level higher than the statement itself:
    a. def, class
    b. if, elif, else,
    c. for, while, else
    d. with
    e. try, except, else, finally
  3. Suggest to start the first line of a code cell with no indentation, and indent when there are compound statements.

How to indent on coursera’s jupyter notebook:

  1. Press “Tab” to go one indentation level up
  2. Press “Shift + Tab” to go one indentation level down
  3. Select one or some lines, press “Tab” to move those lines one indentation level up
  4. Select one or some lines, press “Shift + Tab” to move those lines one indentation level down

Note that, when you press “Tab”, coursera’s jupyter notebook automatically identifies it as 4 spaces for you. However, if you copy codes from somewhere that contains “Tabs”, you will need to convert those “Tabs” to spaces yourself.

Troubleshoot when indentation problems are everywhere in a section of code:

  1. Do a “reset” and then indent properly.
  2. To “reset”, select that section of code, press “Shift + Tab” multiple times so all lines have no indentation.

Good example:

Common errors:

  1. Unexpected indent. Mixed up “Tab” with “Spaces”. Note that coursera’s jupyter notebook distinguishes a Tab from spaces with an arrow.
    Screenshot from 2022-07-12 10-44-41
  2. Unexpected indent. Shouldn’t indent the second line.
    Screenshot from 2022-07-12 10-47-00
10 Likes