Python Syntax
Python · Getting Started
Theory
Python uses indentation, the spaces at the start of a line, to decide which statements belong together. A line that opens a block (if, for, while, def, class) ends with a colon, and every line inside that block must be indented by the same amount, conventionally 4 spaces. The block ends when the indentation goes back to the previous level. Other languages use curly braces for this; in Python the layout itself is the structure.
Because indentation has meaning, getting it wrong is an error, not a style issue. An unexpected indent or a missing indent raises IndentationError, and mixing tabs and spaces inconsistently raises TabError. Each statement normally sits on its own line with no semicolon, and an expression inside (), [] or {} can safely continue across several lines.
Why we use it
Forcing indentation makes every Python program look structured the same way, so code written by someone else is easy to read. There are no braces to mismatch, and what you see on screen is exactly how the code is grouped.
When to use it
Always indent the body of if, for, while, def, class, with and try blocks. Configure your editor to insert 4 spaces when you press Tab. To split a long line, wrap it in parentheses rather than ending lines with a backslash.
How it works
- Python reads a line ending with a colon, e.g. if 5 > 2:
- Expect the next line to be indented further
- Is the next line indented? Yes: It joins the if block. No: IndentationError: expected an indented block.
- Keep reading lines at the same indentation as part of the block
- A line back at the outer level closes the block
- Execution continues after the block
Syntax
if condition:
do_something()Example
if 5 > 2:
print("Five is greater than two")Key points
- Indentation is mandatory, not optional
- Use 4 spaces per level and never mix tabs with spaces
- Every block-opening line ends with a colon
- No semicolons required at line end
- Lines inside (), [] or {} can continue onto the next line