Python Keywords Explained for Developers Learning the Language

Stackademic

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

KeywordRole
if, elif, elseConditional branches
for, whileLoops
break, continueExit or skip loop iterations
match, casePattern matching (3.10+)
try, except, else, finallyException handling
raiseThrow an exception
with, asContext managers (files, locks)

Example:

for item in items:
    if item is None:
        continue
    process(item)

Functions and classes

KeywordRole
defDefine a function
returnSend a value back to the caller
yieldProduce a generator value
lambdaAnonymous one-expression function
classDefine a class
passNo-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

KeywordRole
import, fromLoad modules
asAlias imports (import numpy as np)

Prefer explicit imports over wildcard from module import * in production code—it keeps namespaces clear.

Logic and comparisons

KeywordRole
and, or, notBoolean operators
in, isMembership and identity tests
True, False, NoneSingleton constants

Use is only for None and other singletons; use == for value equality.

Scoping and namespaces

KeywordRole
globalAssign to a module-level name inside a function
nonlocalAssign 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+)

KeywordRole
async, awaitCoroutines and asynchronous I/O
async def fetch(session, url):
    async with session.get(url) as resp:
        return await resp.text()

Other reserved words

KeywordRole
delDelete a reference
assertDebug-time condition check
elifAlready 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

ConceptPythonJavaScript
Block delimiterIndentation{ }
Variable declarationassignment onlylet / const
Equality== value, is identity=== strict
Null-likeNonenull / undefined

Java developers notice Python has no public / private; naming conventions (_leading underscore) signal intent instead.

Mini exercises

  1. Rewrite a while True menu loop using break.
  2. Implement a context manager with with open(...) and explain what happens if an exception fires mid-block.
  3. Write a match statement that routes HTTP status codes to log levels (3.10+).

Interview angles

Interviewers sometimes ask:

  • Difference between is and ==
  • What yield does versus return
  • How try/finally behaves when return appears in try

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.