Python Tutorial

Python Keywords

Learn Python keywords with beginner-friendly tables and examples for conditions, loops, functions, exceptions, imports, scope, asynchronous code, and pattern matching.

What are Python keywords?

Python keywords are reserved words with a special meaning in the language. They define program structure, control execution, handle exceptions, create functions and classes, and work with modules. You cannot normally use a keyword as a variable, function, or class name.

How to see the keywords in your Python version

The exact keyword list belongs to the Python interpreter you are using. Ask Python instead of relying on a copied list:

import keyword

print(keyword.kwlist)
print(keyword.softkwlist)

kwlist contains hard keywords. softkwlist contains words that act like keywords only in particular syntax, such as pattern matching.

Python keyword reference

Boolean and special values

KeywordBeginner explanationExample
TrueBoolean value representing a true condition.active = True
FalseBoolean value representing a false condition.is_valid = False
NoneRepresents the absence of a value.result = None

Conditions and logical expressions

KeywordPurposeExample
ifRuns a block when a condition is true.if score >= 50:
elifTests another condition when earlier conditions were false.elif score == 0:
elseRuns when no preceding condition matched.else:
andRequires both expressions to be true.age >= 18 and active
orRequires at least one expression to be true.admin or owner
notReverses a Boolean result.not completed
isChecks object identity, not ordinary value equality.value is None
inChecks whether a value is contained in an iterable."py" in "python"
score = 72
if score >= 90:
    grade = "A"
elif score >= 50:
    grade = "Pass"
else:
    grade = "Try again"
print(grade)

Loops and loop control

KeywordPurposeExample
forIterates over values in an iterable.for item in items:
whileRepeats a block while a condition remains true.while count < 3:
breakStops the nearest loop immediately.if found: break
continueSkips to the next loop iteration.if ignored: continue
passDoes nothing; useful as a temporary placeholder.class Draft: pass

Functions, generators, and classes

KeywordPurposeExample
defDefines a named function.def greet():
returnSends a result back from a function.return total
yieldProduces a value from a generator and pauses its state.yield number
lambdaCreates a small anonymous function expression.lambda x: x * 2
classDefines a class used to create objects.class User:
def double(number):
    return number * 2

def numbers(limit):
    for number in range(limit):
        yield number

print(double(4))
print(list(numbers(3)))

Exceptions and error handling

KeywordPurposeExample
tryMarks code that may raise an exception.try:
exceptHandles a matching exception.except ValueError:
finallyRuns cleanup code whether an exception occurred or not.finally:
raiseRaises an exception intentionally.raise ValueError()
assertChecks an assumption and raises AssertionError when it is false.assert total >= 0
try:
    number = int(input("Number: "))
except ValueError:
    print("Enter a whole number")
else:
    print(number)
finally:
    print("Input attempt finished")

Modules and imports

KeywordPurposeExample
importLoads a module.import math
fromSelects names from a module or package.from math import pi
asCreates an alias for an imported name or exception.import pandas as pd

Scope and namespaces

KeywordPurposeGuidance
globalAllows a function to rebind a module-level name.Use sparingly; return values are usually clearer.
nonlocalAllows a nested function to rebind a name in its enclosing function.Useful in closures, but avoid unnecessary shared state.

Context management and asynchronous code

KeywordPurposeExample
withUses a context manager to guarantee setup and cleanup.with open(path) as file:
asyncDefines an asynchronous function or context.async def fetch():
awaitWaits for an awaitable inside asynchronous code.result = await fetch()

Soft keywords: match and case

match and case are soft keywords. They act as keywords in structural pattern matching but can be used as ordinary names in other contexts:

value = 2
match value:
    case 1:
        print("One")
    case 2:
        print("Two")

Helpful rules for beginners

  • Do not use a keyword as a variable or function name.
  • Use == to compare values and is None to check for the singleton None.
  • Catch specific exceptions instead of using a broad, silent except.
  • Use with for resources such as files that must be closed.
  • Run keyword.kwlist when you need the list for a particular Python installation.

Further Reading

Continue learning with these related Python tutorials:

Continue learning