Lesson

Python Syntax

10 min reading
Free Course

Python Syntax: Indentation, Blocks, and Statement Rules

Python syntax uses whitespace indentation instead of curly braces {} to define code blocks. Every loop, function, class, and if statement ends its header line with a colon : and indents the lines below it.

This strict layout keeps every Python file readable across teams. If two lines in the same block use different spacing, Python refuses to run and raises an IndentationError.

How Indentation Defines Scope Blocks

A block starts after a colon and continues until a line returns to the previous indentation level. Standard Python style (PEP 8) uses exactly 4 spaces per level.

order_total = 120

if order_total >= 100:
    discount = 15
    final_price = order_total - discount
    print(f"Discount applied: ${final_price}")
else:
    print(f"Standard total: ${order_total}")

Both discount and final_price belong inside the if block because they share the same 4-space indent. The else: line returns to column zero to close the first block.

Multi-Line Statements and Line Breaks

Python treats each physical line as one statement. When an expression grows too wide, wrap it inside parentheses (), brackets [], or braces {} instead of using backslashes.

weekly_sales = [
    1450, 1890, 2100,
    1760, 2340, 2980,
]

message = (
    "Weekly sales exceeded the target "
    "across five of six days."
)
print(sum(weekly_sales), message)

Common Mistakes to Avoid

  • Inconsistent indentation inside a block: Using 4 spaces on one line and 2 spaces on the next triggers IndentationError.
  • Forgetting the trailing colon: Writing if score > 50 without : causes a SyntaxError immediately.
  • Adding unnecessary semicolons: Python allows ; between statements on one line, but putting multiple statements on one line hurts readability.

Frequently Asked Questions

How many spaces should I use for indentation in Python?

PEP 8 recommends 4 spaces per indentation level. Python allows any consistent count above zero, such as 2 spaces, as long as every line in that block matches.

Can I use tabs instead of spaces?

Python 3 forbids mixing tabs and spaces in the same file. Nearly all Python editors convert the Tab key into 4 spaces automatically.

Is Python syntax case-sensitive?

Yes. total, Total, and TOTAL are three separate names, and keywords like if, for, and True must match exact casing.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Python Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum