liveBook · Manning

Indentation

As explained in A Pythonic Adventure: From Python basics to a working web app

Indentation is leading whitespace that Python uses to delimit statement blocks and determine control structure.

Indentation is the leading whitespace that shifts code to the right. In Python, it marks which statements belong inside a block, such as a while loop. When a loop begins, indent every line it controls—four spaces is the practical rule. section 4.0 section 4.1

When adding a loop to a menu function:

  • Put the loop-controlled statements four spaces to the right. section 4.0
  • Indent statements nested inside an if or else block farther to the right. section 4.0
  • Use the editor’s Check button to catch a missing indented block before running the program. section 4.0

A correctly indented menu loop

The statements belonging to while True are shifted right, and the statements belonging to if are shifted right again:\n\nwhile True:\n choice = input(prompt)\n if choice in allowed_answers:\n answer = choices[int(choice) - 1]\n break\n else:\n print("Enter a valid choice")\n answer = ''

A missing indentation can stop the program with an “expected an indented block” message. Fix the layout, check again, and then run the menu to confirm that the loop behaves as intended. section 4.0

YOUR TURN

Add a while loop to your own function. Deliberately leave one line unindented, click Check, and then move it into the block. Try making and fixing another indentation error. section 4.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Explains block membership and four-space layout through a while-loop correction, stopping short of deeper whitespace rules.
Examples
Demonstrates nested indentation in Erik’s menu function and practices finding errors with the editor’s Check button.
What it assumes
Assumes basic Python statements and introduces indentation through while, if, and else blocks.
What you can do after
Diagnose missing-indentation errors with the editor’s Check button and apply correctly nested indentation to menu loops.
How it connects
Connects indentation with while loops, for loops, if statements, else statements, and input validation.

Also explained in

Compare how 6 books explain indentation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.