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:
- 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”.
- 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
- 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:
- Press “Tab” to go one indentation level up
- Press “Shift + Tab” to go one indentation level down
- Select one or some lines, press “Tab” to move those lines one indentation level up
- 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:
- Do a “reset” and then indent properly.
- To “reset”, select that section of code, press “Shift + Tab” multiple times so all lines have no indentation.
Good example:
Common errors:
- Unexpected indent. Mixed up “Tab” with “Spaces”. Note that coursera’s jupyter notebook distinguishes a Tab from spaces with an arrow.
- Unexpected indent. Shouldn’t indent the second line.