liveBook · Manning

Block

As explained in The Quick Python Book, Fourth Edition

A code block is a sequence of one or more statements grouped as a syntactic unit and executed under a common control structure.

A Python block is one or more statements grouped as the body of a control-flow construct. Indentation defines that grouping instead of braces, so the visual layout reflects execution structure. section 4.1 section 8.10

Use these rules when writing and reading blocks:

  • Indent statements after a compound-statement clause such as if, while, or for. section 8.10
  • Keep statements in the same block at the same indentation level; nested compound statements create nested blocks. section 8.10
  • Prefer spaces and never mix tabs with spaces, because inconsistent indentation raises an exception. section 8.10
  • Although blocks normally use separate lines, a single-line block or semicolon-separated statements are syntactically possible. section 8.10

Conditional blocks

x = 5 if x < 5: y = -1 z = 5 elif x > 5: y = 1 z = 11 else: y = 0 z = 10 print(x, y, z) # 5 0 10 The two statements under else belong to the same block because they share an indentation level. section 3.4.2

# This is Python code.
n = 9
r = 1
while n > 0:
    r = r * n         #1
    n = n - 1         #2

Compare brace-delimited C with Python indentation while calculating a factorial; the equivalent control-flow body is visible directly in the layout. section 4.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines block membership, nesting, single-line cases, and indentation errors, but does not discuss interpreter internals.
Examples
Uses factorial calculation, conditional assignment, nested interactive blocks, and examples of unexpected or mismatched indentation.
What you can do after
Apply indentation to write nested control-flow bodies and diagnose common indentation errors.
How it connects
Connects indentation with statements, compound statements, conditionals, while loops, for loops, and nested blocks.

Also explained in

Compare how 5 books explain block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.