Python Tutorial · Python Basics · Lesson 3 of 42

Python Syntax

Indentation, statements and how Python decides where a block starts and ends.

Indentation matters

Most languages use { } to group code. Python uses indentation (spaces at the start of a line). The standard is 4 spaces per level.

Example 1Try it yourself
if 5 > 2:
    print("Five is greater than two!")
    print("This line is in the same block")
print("This line runs after the if block")

Output

Five is greater than two!
This line is in the same block
This line runs after the if block

Lines that belong to the same block must be indented by the same amount. Forgetting to indent is an error:

if 5 > 2:
print("Five is greater than two!")   # IndentationError: expected an indented block

One statement per line

Each line is usually one statement — no semicolons needed. A colon : ends the line that starts a block (if, for, def, class…).

Example 2Try it yourself
x = 10
y = 20
print(x + y)

Output

30

Case sensitivity

Python is case-sensitive: name, Name and NAME are three different variables.

Test yourself

How many spaces does PEP 8 (Python's style guide) recommend per indentation level?

  1. 1
  2. 2
  3. 4
  4. 8
Show answer

Answer: 4