Skip to content
  • Syntax, Comments & Keywords · Python

Syntax, Comments & Keywords

LearnViaNotes @learnvianotes· 5 min read

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.

Python
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 positive
Python
src = "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 1

Comments & docstrings

Python
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.57

Statements vs expressions

Python
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)                                # 105

Long lines & multiple statements

Python
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 3

Names (identifiers)

Rule / conventionExample
Letters, digits, _; can't start with a digittotal_2 ✓ · 2total ✗
Case-sensitivecount, Count and COUNT are three names
Can't be a keywordclass = 1 ✗ → class_ = 1 ✓
Unicode letters allowedπ = 3.14159 works (but stick to ASCII in shared code)
snake_casevariables, functions, modules
PascalCaseclasses
UPPER_CASEconstants (by convention only — nothing stops reassignment)
_leadinginternal / 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
Python
print("my_var".isidentifier(), "2cool".isidentifier())   # True False
π = 3.14159
print(round(2 * π, 2))                                    # 6.28

Keywords & 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.

Python
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
PurposeKeywords
ValuesTrue False None
Logic & testsand or not in is
Branchingif elif else
Loopsfor while break continue
Functionsdef return lambda yield global nonlocal
Classes & modulesclass import from as
Errors & resourcestry except finally raise assert with
Asyncasync await
Miscpass del

Placeholders: pass and ...

Python
def todo():
    pass                  # a statement that does nothing

class Config: ...         # Ellipsis — a common "fill in later" body

print(todo(), Config.__name__, ...)   # None Config Ellipsis

Exploring from the REPL: help, dir, type

Python
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.
REPL
>>> help(str.split)       # full documentation (q to quit)
>>> dir([])               # every attribute/method of a list
>>> 2 + 3
5
>>> _ * 10                # _ holds the last REPL result
50

Why does Python use indentation instead of braces?

What is the difference between a comment and a docstring?

Is match a keyword?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report