Python Syntax: Indentation, Statements and Comments
Most languages group statements with curly braces. Python uses indentation instead: the amount of leading whitespace on a line decides which block the line belongs to. This makes Python code look tidy by necessity, and it is the first rule that trips up newcomers.
Statements and lines
Normally one line holds one statement, and the line break ends it. You do not need a semicolon. A long expression may continue onto the next line if it is inside parentheses, brackets or braces, which is the preferred way to wrap long lines.
Blocks are defined by indentation
A line that ends with a colon, such as if temperature > 30:, introduces a block. Every statement in that block must be indented by the same amount, conventionally four spaces. The block ends at the first line that returns to the outer indentation level. There is no closing keyword.
Expected output
It's hot today. Drink some water. This line always runs.
The two indented print() calls belong to the if statement, so they only run when the condition is true. The last print() is back at the left margin, so it runs every time. Change temperature to 20 and run again: only the final line appears.
Comments
A hash sign # starts a comment that lasts until the end of the line. Python ignores comments completely; they exist for human readers. Good comments explain why the code does something, because the code itself already shows what it does.
There is no special multi-line comment syntax. For longer notes, start several lines with #. A string placed as the first statement of a function, class or module is a docstring; tools such as help() display it. You will write docstrings in the functions chapter.
Common mistakes
- Mixing tabs and spaces. Python may refuse to run with a
TabError. Configure your editor to insert four spaces when you press Tab. - Forgetting the colon at the end of
if,for,whileordeflines, which gives aSyntaxError. - Indenting a line that should not be indented. An unexpected indent is an error, not a style choice.
Summary
- A line break ends a statement; brackets let an expression span lines.
- A colon opens a block, and the block is the group of lines indented beneath it.
- Use four spaces per level, never a mix of tabs and spaces.
#starts a comment that runs to the end of the line.
Quiz: Syntax and comments