Python Syntax and Structure
Indentation defines blocks, statements end at the line break, and a short set of rules about comments, keywords and identifiers covers everything else.
- Basics
- Data Types
- Operators
- Strings
- Control Flow
- Lists
- Tuples
- Sets
- Dictionaries
- Comprehensions
- Functions
- Advanced Functions
- Recursion
- Exception Handling
- File Handling
- Modules
- Standard Library
- OOP
- Advanced OOP
- Iterators and Generators
- Decorators
- Context Managers
- Descriptors and Dataclasses
- Python Internals
- Concurrency
- Regular Expressions
- Serialization
- Command Line Python
- Testing and Debugging
- Type Hints
- Performance
- Python Security
- DSA with Python
Indentation is the syntax
Most languages mark a block with braces and treat indentation as decoration. Python inverts that: indentation is the block marker and there are no braces. A line ending in a colon opens a block, and every line indented under it belongs to that block.
total = 0
for value in [4, 9, 16]:
total = total + value # inside the loop
print("running", total) # inside the loop
print("final", total) # outside the loopMove that last print four spaces to the right and the program still runs, but it now prints three times instead of once. Indentation changed the meaning, not the appearance.
The rules
- Use four spaces per level. This is a convention, not a requirement, but it is followed almost universally.
- Be consistent within a block. Mixing tabs and spaces raises a
TabError. - Any consistent amount works, but a block cannot be empty. Use
passas a placeholder when you have nothing to put there yet.
def not_written_yet():
passConfigure your editor to insert four spaces when you press Tab. Every Python editor has this setting, and turning it on removes an entire category of error permanently.
Statements and lines
A statement ends at the end of the line. No semicolon is needed, and adding one is legal but unidiomatic.
price = 250
quantity = 3
total = price * quantityContinuing a long line
Two mechanisms exist, and one of them is clearly preferred.
# Implicit continuation: anything inside (), [] or {} may span lines.
totals = [
120,
340,
560,
]
message = (
"This sentence is long enough "
"that splitting it across lines "
"reads better."
)
# Explicit continuation with a backslash. Legal, but fragile.
total = 120 + \
340Prefer brackets. A backslash must be the very last character on the line, and a single trailing space after it is an error that is invisible on screen.
Several statements on one line
a = 1; b = 2 # legal, and discouragedPython allows it. Style guides advise against it, because it hides the second statement from a reader scanning down the left edge.
Comments
# A full line comment explaining why, not what.
rate = 0.18 # an inline comment, two spaces before the hash
# There is no /* block comment */ in Python.
# Comment out several lines by prefixing each one.A triple quoted string on its own is sometimes used as a multi line comment. It is not a comment; it is a string that is created and discarded. In the first position of a module, function or class it becomes a docstring, which is different and useful:
def net_price(amount, rate):
"""Return amount plus tax at the given rate."""
return amount * (1 + rate)
print(net_price.__doc__)Keywords
Keywords are reserved. They cannot be used as names.
False None True and as assert async
await break class continue def del elif
else except finally for from global if
import in is lambda nonlocal not or
pass raise return try while with yieldimport keyword
print(keyword.kwlist) # the definitive list for your version
print(keyword.iskeyword("in")) # TrueIdentifiers
An identifier is any name you choose: variables, functions, classes, modules.
- May contain letters, digits and underscores.
- May not begin with a digit.
- Are case sensitive, so
totalandTotalare two different names. - May not be a keyword.
order_total = 100 # valid
_internal = 5 # valid, the leading underscore signals "private by convention"
total2 = 7 # valid
# 2total = 7 # SyntaxError: cannot start with a digit
# class = "A" # SyntaxError: class is a keywordNaming conventions from PEP 8
PEP 8 is the official style guide. It is not enforced by the interpreter, but following it makes your code look like everybody else's, which is the entire point.
| Thing | Convention | Example |
|---|---|---|
| Variable, function, method | lower_case_with_underscores | order_total, send_invoice() |
| Constant | UPPER_CASE_WITH_UNDERSCORES | MAX_RETRIES |
| Class | CapWords | InvoiceLine |
| Module and package | short lowercase | invoices, report_utils |
| Internal by convention | leading underscore | _cache |
The rest of PEP 8 in brief
- Four spaces per indent level, never tabs.
- Keep lines to a readable width; 79 characters is the classic limit and many teams use a larger one, but a limit exists.
- Two blank lines between top level definitions, one blank line between methods inside a class.
- Spaces around binary operators and after commas, but not just inside brackets:
f(a, b), notf( a,b ). - Imports at the top of the file, one per line, standard library first.
Common mistakes
- Forgetting the colon at the end of an
if,for,while,deforclassline. - Mixing tabs and spaces, usually after pasting code from a web page.
- Leaving a block empty instead of writing
pass. - Using a keyword or a built in name as a variable.
list = [1, 2]is legal and thenlist(...)stops working for the rest of the program. - Trusting a triple quoted string to be a comment. It is a string, and it is evaluated.
Best practices
- Let the editor manage indentation, and turn on the display of whitespace.
- Write comments that explain why. The code already states what it does.
- Give a name that describes the value, not its type.
customersbeatscustomer_list. - Adopt PEP 8 from the first file. Retrofitting style to a finished project is far more work.
Practice
- Take a loop with a
printafter it, shift thatprintinto the loop, and describe how the output changes and why. - Rewrite a 120 character expression using bracket continuation rather than a backslash.
- List five identifiers that are legal and five that are not, giving the reason for each rejection.
- Explain the difference between a comment and a docstring, and demonstrate how to read a docstring at runtime.
Conclusion
Python replaces punctuation with layout. A colon opens a block, indentation defines it, and the line break ends a statement. Combine that with PEP 8 naming and your code will already read the way experienced Python code reads.