Python If Statement

Watch out! This tutorial is over 1 year old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

Python is quite unusual in that blocks of statements are defined not with the usual markers, { and }, or begin and end, but by the actual indention of the code itself.

Below is a summary of the rules. Note that blank lines and comments are ignored, so “line” in this discussion means only the non-blank, non-comment lines.

  1. The first line starts the first block and must not be indented. Indenting the first line is a syntax error.
  2. A line which is indented the same as the one immediately before belongs to the same block.
  3. A line which is indented more than the one immediately before it starts a new block.
  4. A line y which is indented less than the line x immediately before it closes x‘s block and belongs to an earlier block. Specifically:
    • Line y is matched with the most recent line a which has the same indent.
    • If there is no such line a, or if some line between a and y has a lesser indent, y is a syntax error. Otherwise:
    • Line y belongs to the same block as a.
    • All blocks started between a and y (including the one x belongs to) are closed.
  5. The end-of-file closes all open blocks.