The rules of how Python code is written: indentation instead of braces, comments and docstrings, how lines continue, what you may name things, and the reserved keywords.
Indentation is the block structure
Where C and Java use { }, Python uses a colon : followed by an indented block. Every line in a block must use the same indentation — the convention is 4 spaces.
def classify(n):
if n < 0:
return "negative" # inside the if-block
elif n == 0:
return "zero"
return "positive" # back at the function-block level
print(classify(-3), classify(0), classify(7)) # negative zero positivesrc = "def f():\nreturn 1\n" # body not indented
try:
compile(src, "<demo>", "exec")
except IndentationError as e:
print(type(e).__name__, "-", e.msg) # IndentationError - expected an indented block after function definition on line 1Comments & docstrings
def area(r):
"""Return the area of a circle of radius r.
Uses 3.14159 for pi; pass a float or int.
"""
# the formula is pi * r squared
return 3.14159 * r * r
print(area.__doc__.splitlines()[0]) # Return the area of a circle of radius r.
print(round(area(2), 2)) # 12.57Statements vs expressions
x = 5 # assignment statement
y = (x * 2) + 1 # the right side is an expression
print(y, (z := x + 1), z) # 11 6 6 ← := is an assignment *expression*
print(eval("x * 10")) # 50 ← eval evaluates one expression
exec("w = x + 100") # exec runs statements
print(w) # 105Long lines & multiple statements
total = (1 + 2 +
3 + 4) # implicit continuation inside ( ) [ ] { }
fruits = [
"apple",
"banana", # a trailing comma is allowed — cleaner diffs
]
legacy = 1 + \
2 # explicit backslash continuation (avoid)
a = 1; b = 2 # ; separates statements (discouraged)
print(total, len(fruits), legacy, a + b) # 10 2 3 3Names (identifiers)
| Rule / convention | Example |
|---|---|
Letters, digits, _; can't start with a digit | total_2 ✓ · 2total ✗ |
| Case-sensitive | count, Count and COUNT are three names |
| Can't be a keyword | class = 1 ✗ → class_ = 1 ✓ |
| Unicode letters allowed | π = 3.14159 works (but stick to ASCII in shared code) |
snake_case | variables, functions, modules |
PascalCase | classes |
UPPER_CASE | constants (by convention only — nothing stops reassignment) |
_leading | internal / private by convention |
__dunder__ | reserved for Python's special names |
_ | a throwaway value: for _ in range(3); in the REPL it's the last result |
print("my_var".isidentifier(), "2cool".isidentifier()) # True False
π = 3.14159
print(round(2 * π, 2)) # 6.28Keywords & soft keywords
Keywords are reserved words you can't use as names. Soft keywords (match, case, type, _) are keywords only in specific positions, so old code using match as a variable still works.
import keyword
print(len(keyword.kwlist)) # 35
print(keyword.iskeyword("class"), keyword.iskeyword("match")) # True False
print(keyword.softkwlist) # ['_', 'case', 'match', 'type']
match = "still a valid variable name"
print(match.split()[0]) # still| Purpose | Keywords |
|---|---|
| Values | True False None |
| Logic & tests | and or not in is |
| Branching | if elif else |
| Loops | for while break continue |
| Functions | def return lambda yield global nonlocal |
| Classes & modules | class import from as |
| Errors & resources | try except finally raise assert with |
| Async | async await |
| Misc | pass del |
Placeholders: pass and ...
def todo():
pass # a statement that does nothing
class Config: ... # Ellipsis — a common "fill in later" body
print(todo(), Config.__name__, ...) # None Config EllipsisExploring from the REPL: help, dir, type
print(type(3.0).__name__) # float
print([n for n in dir(str) if n.startswith("st")]) # ['startswith', 'strip']
print(len.__doc__.splitlines()[0]) # Return the number of items in a container.>>> help(str.split) # full documentation (q to quit)
>>> dir([]) # every attribute/method of a list
>>> 2 + 3
5
>>> _ * 10 # _ holds the last REPL result
50Why does Python use indentation instead of braces?
What is the difference between a comment and a docstring?
Is match a keyword?