Python Syntax and Indentation

Understand how Python uses indentation to group statements, why consistent spacing matters, and the core syntax rules every Python programmer must know.

6 min read

Python looks different from most other programming languages. There are no curly braces wrapping blocks of code, and no end keywords closing statements. Instead, Python uses indentation to show which lines belong together. This is the first thing to understand before writing anything beyond a single line.

If you have already written your first program, you have seen that a simple print() line sits at the left margin. Now you need to understand what happens when you add structure.

Why Python uses indentation

In languages like JavaScript, Java, or C++, you wrap a block of code in curly braces:

javascriptjavascript
if (x > 0) {
    console.log("positive");
}

Python drops the braces and uses the indentation itself to define the block:

pythonpython
if x > 0:
    print("positive")

The colon at the end of the first line says "a block is starting." The indented line underneath is inside that block. When you stop indenting, the block ends.

This approach was an intentional design choice by Python's creator, Guido van Rossum. The idea is that code should look like what it does. If a line is visually inside a block, it is inside that block. There is no way for indentation to lie about structure.

The basic syntax rules

Every Python statement sits on its own line. You do not need a semicolon at the end:

pythonpython
name = "Ada"
print(name)

Statements run in order, top to bottom. A line that starts a block ends with a colon (:). The next line must be indented:

pythonpython
if temperature > 30:
    print("It is hot outside.")
    print("Drink water.")

Both print calls are indented the same amount, so both are inside the if block. The block ends when a line returns to the previous indentation level:

pythonpython
if temperature > 30:
    print("It is hot outside.")
    print("Drink water.")
print("Weather report complete.")  # outside the if block

The last print runs regardless of the condition because it is not indented under the if.

How indentation defines blocks

Blocks can nest. Each level of nesting means one more level of indentation:

pythonpython
if score >= 50:
    print("You passed.")
    if score >= 90:
        print("Outstanding performance!")
    print("Check your email for results.")

Here the first print and the inner if are at the same indentation level (one level deep). The second print is two levels deep, so it only runs when both conditions are true. The last print is back to one level deep, so it runs whenever score >= 50.

Python determines block boundaries by comparing indentation levels. When indentation increases, Python pushes an INDENT token. When it decreases, Python pushes DEDENT tokens. If you want to understand this process in more detail, read how Python runs your code.

Spaces versus tabs

Use spaces. Four spaces per indentation level. This is the recommendation in PEP 8, the official Python style guide, and it is the standard across every Python codebase you will encounter.

Most editors can be configured to insert spaces when you press Tab. In VS Code, this setting is called "Insert Spaces" and is on by default for Python files. In PyCharm, it is under Editor > Code Style > Python.

If you mix tabs and spaces in the same file, Python raises a TabError:

plaintextplaintext
TabError: inconsistent use of tabs and spaces in indentation

This error exists to protect you. Mixing tabs and spaces makes code look different in different editors, which can hide bugs. If you see this error, pick spaces and reformat the file.

Indentation in practice

Here is a function that shows several levels of indentation:

pythonpython
def classify_number(n):
    if n < 0:
        return "negative"
    elif n == 0:
        return "zero"
    else:
        if n % 2 == 0:
            return "positive even"
        else:
            return "positive odd"

Notice the pattern. The body of def is indented once. Inside that, the bodies of if, elif, and else are indented again. The return inside each branch is indented one more level. Every line's position tells you exactly which block owns it.

This is also how loops work:

pythonpython
for item in shopping_list:
    print(f"Checking: {item}")
    if item == "eggs":
        print("  Found eggs, stopping.")
        break

The for block contains everything indented underneath it. The if inside the loop adds another level. The break is inside the if, so it only fires when the condition is met.

Common indentation mistakes

Forgetting the colon. A block header like if, for, def, or class must end with :. Without it, Python does not expect a block:

pythonpython
if x > 0              # missing colon
    print("positive") # IndentationError

Inconsistent indentation within a block. Every line in the same block must use the same number of spaces:

pythonpython
if x > 0:
    print("one")
      print("two")  # IndentationError: unexpected indent

Unindenting too far. When you unindent, you must return to a level that already exists on the indentation stack:

pythonpython
if x > 0:
    print("one")
  print("two")  # IndentationError: unindent does not match

Indenting when there is no block. A line should only be indented if it belongs to a block introduced by a colon on the previous line:

pythonpython
print("hello")
    print("world")  # IndentationError: unexpected indent

When you see an IndentationError, look at the line number in the error message. Check that the line is indented correctly relative to the lines above it. If you need more help with error messages, see reading Python error messages.

Line continuation

Sometimes a single statement is too long to fit on one line. Python gives you two ways to break it up.

Implicit continuation works inside parentheses, brackets, and braces:

pythonpython
total = (item_price + shipping_cost
         + tax - discount)

As long as you are inside (), [], or {}, Python knows the statement continues on the next line. No special character is needed, and the indentation of the continuation line does not matter (though aligning it for readability is good practice).

Explicit continuation uses a backslash at the end of a line:

pythonpython
if score > 50 and time < 60 \
   and not penalty:
    print("Qualified")

The backslash tells Python to ignore the newline. This is less common. Prefer implicit continuation with parentheses when possible because it is cleaner and allows comments on continuation lines.

Blank lines and vertical spacing

Blank lines are ignored by Python. Use them to separate logical sections within your code:

pythonpython
def calculate_total(items):
    subtotal = sum(item.price for item in items)
 
    if subtotal > 100:
        subtotal *= 0.9  # 10% discount
 
    return subtotal

The blank lines separate the calculation, the discount logic, and the return statement. This does not affect how the code runs, but it makes the code easier to read.

A blank line inside the interactive interpreter (REPL) ends a multi-line block. In a .py file, blank lines have no such effect.

Setting up your editor for indentation

The easiest way to avoid indentation problems is to configure your editor once:

  • Set "Tab Size" to 4.
  • Enable "Insert Spaces" so that pressing Tab inserts 4 spaces instead of a tab character.
  • Enable "Render Whitespace" if you want to see dots for spaces, which helps spot inconsistencies.

If you have not set up a workspace yet, follow the Python workspace setup guide for step-by-step editor configuration.

After indentation, the next fundamental skill is adding notes to your code. Continue to writing comments in Python.

Rune AI

Rune AI

Key Insights

Python uses indentation to define code blocks, not braces or keywords; Use 4 spaces per indentation level; Never mix tabs and spaces; A consistent indentation style makes your code readable and error-free; Most editors can auto-indent and highlight indentation mistakes.

RunePowered by Rune AI

Frequently Asked Questions

How many spaces should I use for indentation in Python?

Four spaces per indentation level. This is the recommendation in PEP 8, the official Python style guide. Most editors let you configure the Tab key to insert 4 spaces automatically.

What happens if I mix tabs and spaces?

Python raises a TabError. Mixing tabs and spaces makes the indentation ambiguous. Always pick one and stick with it. Spaces are the community standard.

Can I use 2 spaces instead of 4?

Technically yes, as long as you are consistent throughout the file. But 4 spaces is the universal Python convention. Using 2 spaces will surprise other Python developers and may cause issues with some tools.

Do I need to indent every line?

No. Only lines inside a block need indentation, such as the body of a function, an if statement, or a loop. Top-level statements sit at the left margin with no indentation.

Why does Python enforce indentation when other languages do not?

Python was designed so that code looks like its structure. Indentation makes blocks visually obvious and eliminates entire categories of bugs caused by misleading indentation in languages that use braces.

Conclusion

Indentation is not a style preference in Python. It is how the language defines structure. Use 4 spaces per level, stay consistent, and let your editor handle the spacing. Once you internalize this rule, reading and writing Python becomes much smoother.