Understanding Python Syntax and Comments

Python's syntax is deliberately small: most of what you need fits on a single reference page. The language is built from statements (which do something) and expressions (which produce a value). A statement is terminated by a newline, not a semicolon. Several statements on one line are legal but discouraged because they reduce readability — the very thing Python's syntax is optimised for.

The most distinctive rule is that indentation is part of the grammar, not decoration. A block of code (the body of an if, for, function or class) is defined by indenting one level deeper than the header line and ending when the indentation returns. The standard indent is four spaces; mixing tabs and spaces produces an IndentationError that is one of the most frustrating bugs to chase. Configure your editor once to insert spaces on Tab and you will never see it again.

Long statements can be split across multiple lines without escape characters as long as the line break falls inside a pair of parentheses, brackets or braces. This is called implicit line continuation and it is strongly preferred over the backslash (\) continuation because it never breaks when a comment is added to the line. Triple-quoted strings ("""...""") likewise span multiple lines and are the idiomatic way to write long literals such as help text or SQL.

Comments begin with # and run to the end of the line. They are ignored by the interpreter and should explain why something is done when the what is not obvious from the code. Docstrings are different: a string literal written as the first statement of a module, function, class or method is attached to that object as its __doc__ attribute. Tools like help(), Sphinx and IDE tooltips all read docstrings, so they are the single best place to describe behaviour.

Finally, Python ships with a coding-style guide called PEP 8. Its rules (snake_case for functions and variables, CapWords for classes, UPPER_SNAKE for constants, two blank lines between top-level functions, one blank line between methods) are so widely adopted that modern editors and formatters such as black or ruff format apply them automatically. Picking up these names on day one makes every later example in this course read like the Python you see in production code.

Indentation, blocks, and line continuation

Every colon-ending header line (if, for, while, def, class, try, with) introduces a block. The block must contain at least one statement; use pass when you need a placeholder. An empty line inside a block is ignored, so you can group related statements with a blank line for readability without closing the block.

When a line gets too long (PEP 8 suggests 79–99 characters), break it inside an existing pair of brackets. For example, result = helper( first_arg, second_arg, ) is clean and composable; result = helper(first_arg, \\ second_arg) works but is easier to get wrong.

Comments vs docstrings

Use a comment to explain a surprising choice: # use a list, not a set, because order matters for the CSV export. Use a docstring to describe the contract of a callable: what it returns, what it raises, and what the parameters mean. Docstrings are strings, not comments, so they appear in help() and in generated documentation.

Special comments drive tooling: # type: ignore silences a type checker on one line; # noqa: E501 silences a linter's line-length rule; # pragma: no cover excludes a line from coverage reports. Use them sparingly and explain why, so a future reader does not simply delete them.

These are the syntactic pieces you meet in almost every Python file. Learning their exact names makes reading errors much faster.

ToolPurpose
indentation
lexical rule
Defines the start and end of a block of code.
# comment
lexical token
Everything after # on a line is ignored by the interpreter.
docstring
string literal
First statement of a module, class or function; stored in __doc__.
\ at end of line
syntax
Explicit line continuation; use only when brackets cannot wrap.
( ) [ ] { }
bracket pairs
Anything inside them may span multiple lines.
PEP 8
style guide
Community style rules for names, spacing and layout.
help()
built-in
Prints the docstring and signature of any object.
keyword
reserved word
Words such as if, for, def that cannot be used as identifiers.

Understanding Python Syntax and Comments code example

The example shows every syntactic feature discussed above in a single small module. Read it with PEP 8 in mind.

# Lesson: Understanding Python Syntax and Comments
# Style: 4-space indent, snake_case names, two blank lines between functions,
# a single trailing newline, and one docstring per callable.
"""Compute a summary line for a short list of scores.

This module-level docstring appears in help(summary_module) and in any
generated documentation. It describes the purpose of the file as a whole.
"""

MAX_SCORE = 100  # named constant, UPPER_SNAKE per PEP 8


def clamp(value: int, low: int = 0, high: int = MAX_SCORE) -> int:
    """Return `value` bounded to the inclusive range [low, high]."""
    # implicit line continuation inside the max(min(...)) call would be fine
    # too; keep this version flat because it is short enough.
    return max(low, min(high, value))


def summary(scores: list[int]) -> str:
    """Return a one-line report for a list of clamped scores.

    Uses implicit line continuation inside the parentheses so the f-string
    stays readable without backslashes.
    """
    clean = [clamp(s) for s in scores]
    return (
        f"n={len(clean)} "
        f"min={min(clean)} "
        f"max={max(clean)} "
        f"avg={sum(clean) / len(clean):.1f}"
    )


# --- main script ---------------------------------------------------------
raw = [42, 120, -3, 88, 55]
print(summary(raw))
help(clamp)

Spot each syntactic feature while reading:

1) Module-level docstring and named constant appear before any def.
2) Each function has its own docstring, preferred over a leading comment.
3) Parentheses around the return expression enable implicit line joining.
4) The final block calls help(clamp) to show the docstring at runtime.

Two short snippets isolating indentation and comment rules.

# Example A: correct vs incorrect indentation
def greet(name):
    if name:
        return f"Hello, {name}"
    return "Hello, stranger"
# The two return lines are at different indent levels on purpose: one is
# inside the if, the other is in the function body.

# Example B: comments and docstrings read by tools
def area(radius: float) -> float:
    """Return the area of a circle with the given radius."""
    # pi is hard-coded to keep the example import-free
    return 3.141592653589793 * radius * radius

print(area.__doc__)

These assertions verify that the clamp/summary helpers respect the rules above.

assert clamp(150) == 100
assert clamp(-4) == 0
assert summary([10, 20, 30]).startswith("n=3 ")
assert clamp.__doc__ is not None, "every public callable should have a docstring"

Running the script prints the summary line and the rendered docstring:

n=5 min=0 max=100 avg=57.0
Help on function clamp in module __main__:

clamp(value: int, low: int = 0, high: int = 100) -> int
    Return `value` bounded to the inclusive range [low, high].