Python Syntax

Python's syntax is deliberately minimal, and its most notable rule is that indentation, not braces, defines which lines belong together.

Running your first lines

Python code is executed from top to bottom, one statement at a time. Most simple statements sit on their own line, and you do not need a semicolon or any special character to end them. Pressing Enter is enough.

Example

print("This runs first")
print("This runs second")

Indentation matters

This is the rule that surprises newcomers most. In Python, the leading whitespace at the start of a line is part of the language. When a statement introduces a block of code, such as an if statement or a loop, the lines that belong to that block must be indented further to the right. This is how Python knows where the block begins and ends.

Example

if 10 > 5:
    print("Ten is greater than five")

If you forget to indent the line after the colon, Python stops and reports an error. The amount of indentation is up to you, but you must be consistent within the same block. The community standard, and the style used throughout this tutorial, is four spaces per level.

Example

if 10 > 5:
print("This line is not indented")  # IndentationError
Note: Do not mix tabs and spaces for indentation in the same file. It can look correct on screen yet still cause an error. Pick spaces and stick with them.

Statements, lines, and grouping

  • Each statement normally goes on its own line and needs no terminator
  • A colon (:) at the end of a line signals that an indented block follows
  • Every line inside one block must share the same level of indentation
  • Blocks can be nested, with each deeper level indented further

Case sensitivity

Python treats uppercase and lowercase letters as different. A name like age is not the same as Age or AGE, so be careful to type names exactly the same way each time you refer to them.

Exercise: Python Syntax

How does Python mark the body of a block like an if statement?