Python syntax is the set of rules that decides whether a piece of text is a valid Python program. The essentials fit in four sentences: a program is a sequence of statements, usually one per line; statements that introduce a block end with a colon; the lines of that block are indented by the same amount; and a long line can continue onto the next one as long as it is inside brackets.
total = 12 + 8 # a statement containing the expression 12 + 8
if total > 15: # the colon opens a block
print("Large order") # indented: belongs to the ifThis lesson explains each of those rules, shows what Python does when one is broken, and teaches you how to read the resulting SyntaxError and IndentationError messages. The running example is a seed library counting the packets it has available for a seed swap.
Expressions
An expression is any piece of code that produces a value: 14, packets + incoming, name.upper() and available >= 20 are all expressions. A statement is a complete instruction that does something: it stores a value, makes a decision, repeats work or defines a function.
packets + 6 # expression: produces 20, then the value is thrown away
available = packets + 6 # assignment statement: stores the value under a name
print(available) # expression statement: calls a function for its effectThe distinction explains several error messages. You can put an expression anywhere a value is expected, such as inside print() or after return. A plain assignment with = is a statement, not an expression, so if count = 5: is a SyntaxError. Python 3.8 added the walrus operator :=, which assigns and produces a value in one step, if (n := len(items)) > 10:, but beginners rarely need it.
In the interactive shell, typing an expression shows its value straight away. In a script, an expression on its own line is calculated and discarded, which is why scripts use print() to display results.
Indentation
Statements such as if, for, while, def and class end with a colon and are followed by a block: one or more lines indented further than the header. The block ends at the first line that returns to the header's level.
if available >= 20:
print("Ready for the seed swap")
print("Open the sign-up sheet")
print("Inventory checked")The first two print() calls run only when the condition is true; the last one always runs. Other languages mark blocks with braces, but in Python the indentation is the structure, so it isn't optional decoration.
PEP 8, Python's style guide, recommends four spaces per level. The one hard rule is consistency: every line in a block must use the same indentation, and mixing tabs and spaces in a way Python can't resolve raises TabError. Configure your editor to insert four spaces when you press Tab and the problem disappears.
Continuation
Python normally ends a statement at the end of a line. When a calculation, list or function call is too long to read comfortably, wrap it in brackets: inside (), [] or {}, line breaks are ignored until the closing bracket.
available = (
packets_on_shelf
+ packets_donated
- packets_reserved
)
crops = [
"tomato", "bean",
"squash", "chard",
]This is called implicit line joining and is the preferred way to split long lines. A backslash at the end of a line also continues it, but a single invisible space after the backslash breaks it, so most style guides avoid it.
Several short statements can share one line if you separate them with semicolons, a = 1; b = 2, but this hides structure and is discouraged. One statement per line keeps code easy to scan and makes tracebacks point at the exact step that failed.
Parsing
Before running anything, Python parses the whole file: it checks that the text follows the grammar and turns it into an internal structure. If the grammar is broken anywhere, nothing runs at all, not even the lines above the mistake. That is the key difference between a SyntaxError and a run-time error such as NameError, which only appears when the faulty line is reached.
File "inventory.py", line 3
if available >= 20
^
SyntaxError: expected ':'The caret points to where Python realised something was wrong, which is not always where the mistake is. An unclosed bracket or quote on line 2 is often reported on line 3 or later, because Python kept reading in the hope that the bracket would close. Python 3.10 and later give much clearer messages, such as '(' was never closed, so keep your interpreter up to date. When the highlighted line looks fine, check the line above it.
Independent practice and a worked check
Task: build a planting inventory with a multiline expression and two actions inside a condition. Store packets on the shelf, donated packets and reserved packets in three variables, calculate the number available using a bracketed expression over several lines, and, if at least 20 are available, print two messages from inside the if block. Finish with a line that always prints.
One possible solution:
on_shelf = 15
donated = 9
reserved = 4
available = (
on_shelf
+ donated
- reserved
)
if available >= 20:
print(f"{available} packets available")
print("Announce the seed swap")
print("Inventory complete")With these numbers, available is 20, so all three lines print. Change reserved to 6 and only the last line prints. The worked check for this lesson asks what defines a block in Python: the answer is consistent indentation after a line ending in a colon. Indent the second print() by two spaces instead of four and Python raises IndentationError: unindent does not match any outer indentation level.
Reference and next practice
The Python language reference on lexical analysis defines exactly how lines, indentation and brackets are read, and PEP 8 gives the community's layout conventions. Continue with comments to document the code you write, then practise with the Python exercises and Python quiz. The study roadmap shows where this lesson fits in the full course.
Syntax and Statements Summary
- Expressions: Expressions produce values while statements perform actions.
- Indentation: A colon and consistent indentation group statements into a block.
- Continuation: Parentheses allow long expressions to continue across physical lines.
- Parsing: Python checks the source grammar before running ordinary statements.
Syntax and Statements Examples
Each example shows the code, the output it produces and what each part does.
Syntax and Statements in a small program
This short program combines all four rules: two assignment statements, a bracketed expression split across lines, and an if statement whose block is indented.
Try removing the colon on line 6 and run the file again: nothing prints, because the parser rejects the whole program before line 1 runs.
packets = 14
incoming = 6
available = (
packets + incoming
)
if available >= 20:
print("Ready for the seed swap")Ready for the seed swapLine-by-line explanation
- Lines 1 to 2Two assignment statements, one per line.
- Lines 3 to 5The opening bracket lets the expression continue until
); the result, 20, is stored inavailable. - Line 6An
ifheader ends with a colon. - Line 7The indented line is the block. It runs because 20 >= 20 is true.
Nested blocks and a long condition
Blocks can contain other blocks; each level adds four more spaces. A long condition can be wrapped in brackets so it reads clearly over several lines.
packets = {"tomato": 12, "bean": 3, "chard": 0}
for crop, count in packets.items():
if (
count > 0
and crop != "chard"
):
print(f"{crop}: {count} packets")
if count < 5:
print(" low stock")
print("Done")tomato: 12 packets
bean: 3 packets
low stock
DoneLine-by-line explanation
- Line 3The
forblock is everything indented by four spaces below it. - Lines 4 to 7The bracketed condition spans four lines but is a single expression.
- Lines 8 to 10Eight spaces: these lines belong to the
if, which is inside thefor. - Line 11Back at the left edge, so it runs once after the loop finishes.
Common Syntax and Statements Mistakes
Using = where Python expects an expression
packets = 14
if packets = 14:
print("Full shelf")packets = 14
if packets == 14:
print("Full shelf")An if needs an expression that produces True or False. Assignment is a statement, so Python reports SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?. Use == to compare.
Leaving a bracket open on the line above
available = (packets + incoming
print(available)available = (packets + incoming)
print(available)Python keeps reading after an unclosed bracket, so the error points at line 2 even though line 1 is wrong. Recent versions say '(' was never closed; on older versions you may only see invalid syntax on the next line.
Syntax and Statements in Real Projects
Syntax rules in team projects
Professional teams rarely argue about indentation, because tools enforce it. Formatters such as Black rewrite code into one consistent layout, splitting long lines with brackets exactly as shown above, and linters such as Ruff or Flake8 flag mixed tabs and spaces before the code is committed. Continuous integration servers usually parse every file before running tests, so a single missing colon fails the build in seconds instead of crashing a program in production.
For the seed library, this means the inventory script can grow from five lines to five hundred while staying readable: every block is visibly nested, long calculations are wrapped in brackets, and any typo is caught before the swap begins.
Syntax and Statements FAQ
What is the difference between a statement and an expression in Python?
An expression produces a value, like 3 * 4 or name.upper(). A statement is a complete instruction, like total = 3 * 4, if, for or import. Every expression can be used as a statement on its own line, but most statements, including plain assignment, can't be used where a value is expected.
Does Python require semicolons at the end of lines?
No. A newline ends a statement. Semicolons are allowed only to separate several statements on one line, and PEP 8 discourages that. Code copied from Java or JavaScript with trailing semicolons still runs, but they serve no purpose.
How many spaces should I use for indentation in Python?
Four spaces per level is the standard recommended by PEP 8 and used by almost all Python projects. Python accepts any consistent amount, but mixing widths within a block causes IndentationError, and mixing tabs with spaces can cause TabError.
Why does the SyntaxError point to the wrong line?
Python reports the place where the grammar finally became impossible, which is often after the real mistake. Unclosed brackets and quotes are the usual cause: Python keeps reading until it gets confused, possibly several lines later. Check the reported line and the lines just above it.
How do I split a long line of Python code?
Wrap the expression in brackets and break the line inside them; Python ignores line breaks until the closing bracket. Function calls, lists and dictionaries already have brackets, so you can break after any comma. Avoid the backslash continuation, which breaks if any space follows it.
Syntax and Statements Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
What defines a Python statement block?
Which review concern is valid for syntax and statements?
Syntax and Statements Quiz
2 questions to check what you learned.
What defines a Python statement block?
- Curly braces
- Consistent indentation
- Python ignores the distinction
Which statement correctly describes continuation?
- Parentheses allow long expressions to continue across physical lines.
- Only the example output matters, not the rule
- Every operation has the same behavior