← Back to Python Course | Chapter 1: Basics | Lesson 5 of 14

Python Syntax & Indentation

Line Statements

Python statements end at the newline character rather than a semicolon, so a print("hi") line is complete the moment the line ends — no trailing punctuation required. You can still use a semicolon to cram two statements onto one line, but it's rarely idiomatic Python.

Example: Line Statements

python
print("hi")
print("no semicolon needed")
print("a"); print("b")

Indentation Rules

Where C-family languages use { } to group statements into a block, Python uses consistent indentation instead — the interpreter parses whitespace as structural syntax, not just cosmetic formatting. Getting this wrong doesn't just look messy, it changes which code belongs to which if, loop, or function.

Example: Indentation Rules

python
if True:
    print("Indented block belongs to the if")
print("Back to outer level")

Block Structure

All statements at the same indentation level are treated as one block belonging to whatever if, loop, or function opened it; the block ends the moment a line returns to a shallower indent. Mixing indentation depths within what should be one block raises an IndentationError rather than silently misgrouping code.

Example: Block Structure

python
if True:
    print("first line of block")
    print("second line, same indent")
print("outside the block")

Multi-line Statements

A trailing backslash \ at the end of a line tells Python the statement continues on the next line, useful for breaking up a long expression so it stays readable without exceeding a sensible line length. Expressions already inside parentheses, brackets, or braces can also wrap across lines without needing a backslash at all.

Example: Multi-line Statements

python
total = 1 + 2 + \
    3 + 4
print(total)

total2 = (1 + 2 +
          3 + 4)
print(total2)

Syntax Errors

The two most common indentation mistakes are mixing tabs and spaces (which can look identical in an editor but differ to the interpreter) and forgetting to indent a new block after a colon. Configuring your editor to insert spaces for the Tab key sidesteps the first problem entirely.

Example: Syntax Errors

python
# Common mistakes:
# 1. Mixing tabs and spaces in the same block
# 2. Forgetting to indent after a colon
if True:
    print("correctly indented")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.