Lexical Structure and Style

This section documents the current Python release line as published at the official Python documentation, which is the reference these pages are written and verified against. No specific patch version is pinned.

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

This section’s bibliography lists the reference material consulted while preparing these pages.

Python has no \{ \} block delimiters and no statement-terminating ; — indentation itself is syntax, and a style guide, PEP 8, is close to normative for how the community writes code.

Indentation-Based Blocks

C-family languages group statements with braces and largely ignore whitespace; Python instead uses the indentation of a line to mark which block it belongs to, described in the language reference’s Indentation section. A block (the reference calls it a suite) is every consecutive line indented further than the : header that opens it — removing braces removes the possibility that indentation and block structure disagree:

def classify(n):
    if n > 0:
        sign = "positive"
    elif n < 0:
        sign = "negative"
    else:
        sign = "zero"
    return sign             # back at the function's own indentation: outside the if/elif/else

print(classify(-3))         # negative

Indentation must be consistent within a block — every line of the same suite is indented by the same amount, and a nested suite is indented further than its parent. Mixing tabs and spaces in a way that makes the indentation ambiguous is a hard error, not a style nit:

>>> exec("if True:\n\tx = 1\n        y = 2\n")
Traceback (most recent call last):
  ...
TabError: inconsistent use of tabs and spaces in indentation

PEP 8 resolves the ambiguity before it can happen: use spaces only, four per level, and never mix tabs into space-indented code — see PEP 8: The Style Guide below.

Comments and Statement Separators

A # starts a comment that runs to the end of the physical line; there is no block-comment syntax. Statements normally end at a newline (the reference’s implicit line joining and explicit joining rules cover the exceptions below), and ; chains multiple statements onto one physical line:

# Adjust for tax, then round to the nearest cent.
price = 19.99
total = price * 1.08; total = round(total, 2)   # two statements, one line
print(total)

Putting more than one statement per line with ; is legal but discouraged by PEP 8 outside of throwaway scripts — prefer one statement per line.

A long logical line can be split across physical lines two ways. Explicit continuation uses a trailing \:

total = 1 + 2 + 3 + \
        4 + 5 + 6
print(total)   # 21

Implicit continuation happens automatically inside any unclosed (, [, or \{ — this is the preferred style, since nothing breaks if a line is reordered and a trailing space after \ cannot silently break the continuation:

totals = [
    1 + 2 + 3,
    4 + 5 + 6,
]
config = {
    "host": "localhost",
    "port": 5432,
}
print(totals, config)

Note that the \{ \} above are dict literal delimiters, not block syntax — Python does use braces for dict and set literals and for f-string placeholders, just never to mark a block of statements.

PEP 8: The Style Guide

PEP 8 is the standard library’s own style guide and the de facto convention for almost all Python code. It is short and worth reading directly rather than restated in full here; the highlights that show up in nearly every file:

Naming

  • snake_case for functions, methods, variables, and modules.

  • PascalCase (PEP 8 calls it CapWords) for classes.

  • UPPER_CASE for constants.

  • A leading underscore (name) signals "internal use"; a trailing underscore (name) avoids clashing with a keyword.

MAX_RETRIES = 3               # constant: UPPER_CASE

class HttpClient:              # class: PascalCase
    def send_request(self, url):   # method: snake_case
        attempt_count = 0           # variable: snake_case
        while attempt_count < MAX_RETRIES:
            attempt_count += 1
        return attempt_count

print(HttpClient().send_request("https://example.com"))

Line Length and Whitespace

PEP 8 recommends limiting lines to 79 characters (72 for flowing text like docstrings and comments), one space around binary operators, no space just inside parentheses/brackets, and no space before a , ; or ::

# PEP 8 style
result = (first_value + second_value) * scale_factor
items = [1, 2, 3]
lookup = {"a": 1, "b": 2}

# discouraged: cramped and inconsistent spacing
result=(first_value+second_value)*scale_factor
items = [1,2,3]
lookup = {"a" :1,"b":2}

Import Ordering

Imports go at the top of the file, one per line, grouped in this order with a blank line between groups: standard library, third-party packages, then local application imports:

import os
import sys

import requests

from mypackage import utils

import this: The Zen of Python

Python ships an actual Easter egg that doubles as a one-page design-philosophy summary: importing the this module prints the Zen of Python (PEP 20), referenced from the tutorial’s own Intermezzo: Coding Style section as the spirit behind PEP 8 itself:

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
...
Readability counts.
...
There should be one-- and preferably only one --obvious way to do it.
...

The indentation rule and PEP 8 are direct expressions of a few of those lines: readability counts, and there should be one obvious way to lay out a block — rather than the many equivalent brace-and-indent styles other languages tolerate.

See Also