What every reserved word in Python does, how to avoid common mistakes with None and is, and quick exercises to cement control flow and async syntax.
Python reserves certain words for language syntax. You cannot use them as variable names, function names, or class names. If you are learning Python—or switching from JavaScript or Java—knowing what each keyword does prevents confusing errors and helps you read other people’s code faster.
How to see the full keyword list
In any Python 3 environment:
import keyword
print(keyword.kwlist)
The exact list grows slowly between minor versions (for example, match and case arrived with structural pattern matching in 3.10). Your installed version is authoritative.
Control flow
| Keyword | Role |
|---|---|
if, elif, else | Conditional branches |
for, while | Loops |
break, continue | Exit or skip loop iterations |
match, case | Pattern matching (3.10+) |
try, except, else, finally | Exception handling |
raise | Throw an exception |
with, as | Context managers (files, locks) |
Example:
for item in items:
if item is None:
continue
process(item)
Functions and classes
| Keyword | Role |
|---|---|
def | Define a function |
return | Send a value back to the caller |
yield | Produce a generator value |
lambda | Anonymous one-expression function |
class | Define a class |
pass | No-op placeholder |
Generators often use yield instead of building large lists in memory:
def read_lines(path):
with open(path) as f:
for line in f:
yield line.strip()
Imports and modules
| Keyword | Role |
|---|---|
import, from | Load modules |
as | Alias imports (import numpy as np) |
Prefer explicit imports over wildcard from module import * in production code—it keeps namespaces clear.
Logic and comparisons
| Keyword | Role |
|---|---|
and, or, not | Boolean operators |
in, is | Membership and identity tests |
True, False, None | Singleton constants |
Use is only for None and other singletons; use == for value equality.
Scoping and namespaces
| Keyword | Role |
|---|---|
global | Assign to a module-level name inside a function |
nonlocal | Assign to an enclosing (non-global) scope |
These are easy to misuse. Often refactoring to pass parameters or use a small class is clearer than sprinkling global.
Async (3.5+)
| Keyword | Role |
|---|---|
async, await | Coroutines and asynchronous I/O |
async def fetch(session, url):
async with session.get(url) as resp:
return await resp.text()
Other reserved words
| Keyword | Role |
|---|---|
del | Delete a reference |
assert | Debug-time condition check |
elif | Already covered with if |
Soft keywords and builtins (not on kwlist)
Names like print, len, and type are built-in functions, not keywords—you can shadow them (but should not in shared libraries). Type hint syntax uses words such as int and str, which are builtins, not reserved keywords.
Common mistakes
Using a keyword as a variable name
class = "Intro" # SyntaxError
Rename to course_name or similar.
Confusing is and ==
if user_input is "yes": # often wrong for strings
Use == for string content.
Forgetting that True and False are capitalized
Unlike JavaScript’s true/false, Python’s booleans are title-cased.
Study tips for interviews and day-to-day work
- Reimplement small scripts using only concepts from the table above before reaching for heavy libraries.
- Read the standard library docs for one module per week (
pathlib,dataclasses,typing). - When code fails with
SyntaxError: invalid syntax, check whether a new variable name collides with a keyword.
FAQ
Do I need to memorize every keyword before writing apps?
No. Learn control flow, functions, classes, and imports first; add async and match when your projects need them.
Are True, False, and None keywords?
Yes in Python 3—they are reserved and cannot be reassigned (though you technically could in Python 2 for True/False).
What about self?
Convention, not a keyword. The first parameter of instance methods is usually named self.
How do keywords differ from JavaScript?
Python uses indentation for blocks instead of {}, and has no var/let/const—assignment creates names in the current scope.
Iteration protocol: for without indexing
Python’s for loop iterates over any iterable—lists, dict keys, file handles, database cursors—not only numeric ranges. When you need indices, use enumerate:
for index, value in enumerate(["a", "b", "c"]):
print(index, value)
range(len(items)) works but is less idiomatic.
Comprehensions (not keywords, but paired with for)
List and dict comprehensions reuse for and if in a compact expression:
squares = [n * n for n in range(10) if n % 2 == 0]
They are not separate keywords but show up constantly alongside them in tutorials and interviews.
async pitfalls
Mixing blocking I/O inside async def functions stalls the event loop. Use async-native libraries (httpx.AsyncClient, asyncpg) or run blocking code in asyncio.to_thread when unavoidable.
Version-specific keywords
Track release notes when upgrading Python in CI. New syntax can break parsers in older linters. Running python -m compileall on your codebase after a version bump catches keyword collisions early.
Contrasts with other languages
| Concept | Python | JavaScript |
|---|---|---|
| Block delimiter | Indentation | { } |
| Variable declaration | assignment only | let / const |
| Equality | == value, is identity | === strict |
| Null-like | None | null / undefined |
Java developers notice Python has no public / private; naming conventions (_leading underscore) signal intent instead.
Mini exercises
- Rewrite a
while Truemenu loop usingbreak. - Implement a context manager with
with open(...)and explain what happens if an exception fires mid-block. - Write a
matchstatement that routes HTTP status codes to log levels (3.10+).
Interview angles
Interviewers sometimes ask:
- Difference between
isand== - What
yielddoes versusreturn - How
try/finallybehaves whenreturnappears intry
Answer with short examples, not textbook paragraphs.
Working with __future__ and syntax upgrades
Some features arrive behind from __future__ import annotations for forward-compatible type hints. Keywords themselves rarely need future imports, but release notes mention when new reserved words appear—upgrade CI images before developers paste tutorial code that uses match on an old interpreter.
Docstrings and comments vs keywords
Triple-quoted strings immediately after a def or class line are docstrings, not comments. They do not use a keyword, yet they sit beside def and class in almost every module you will read in open source.
Keywords are the grammar of Python. Once they feel familiar, you spend less time fighting syntax and more time modeling problems—which is where the language earns its keep.
Comments
Loading comments…