Python Syntax
Python's syntax is famously readable. The most distinctive rule: indentation defines blocks. No curly braces, no begin/end.
Indentation = block
PYTHON
if 5 > 2:
print('Five is greater than two') # 4 spaces — same block
print('Still in the if block')
print('Out of the if block')
Pick 4 spaces and stick with it across the whole file. Mixing tabs and spaces is a hard error.
Comments
PYTHON
# Single-line comment """ A triple-quoted string used as a block comment. Technically a string literal, but Python ignores it when it's not assigned to anything. """
Statements end at the newline
No semicolons. To put two statements on one line you'd use a real ; — but almost no Python code does.
Naming
| Kind | Convention |
|---|---|
| Variables, functions | snake_case |
| Classes | PascalCase |
| Constants | UPPER_SNAKE_CASE |
| "Private" (by convention) | _leading_underscore |
| Dunder ("magic") | __double_underscore__ |
Tip: Run
black on your code. It formats Python to a single canonical style so code reviews never argue about whitespace.Example
Example
# Indentation defines blocks (4 spaces by convention)
if 5 > 2:
print('Five is greater than two')
Try it Yourself »
Exercise
Python blocks are defined by…
Answer:
11 letters; the visible whitespace.
Discussion
Loading…