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
| Keyword | Beginner explanation | Example |
|---|---|---|
True | Boolean value representing a true condition. | active = True |
False | Boolean value representing a false condition. | is_valid = False |
None | Represents the absence of a value. | result = None |
Conditions and logical expressions
| Keyword | Purpose | Example |
|---|---|---|
if | Runs a block when a condition is true. | if score >= 50: |
elif | Tests another condition when earlier conditions were false. | elif score == 0: |
else | Runs when no preceding condition matched. | else: |
and | Requires both expressions to be true. | age >= 18 and active |
or | Requires at least one expression to be true. | admin or owner |
not | Reverses a Boolean result. | not completed |
is | Checks object identity, not ordinary value equality. | value is None |
in | Checks 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
| Keyword | Purpose | Example |
|---|---|---|
for | Iterates over values in an iterable. | for item in items: |
while | Repeats a block while a condition remains true. | while count < 3: |
break | Stops the nearest loop immediately. | if found: break |
continue | Skips to the next loop iteration. | if ignored: continue |
pass | Does nothing; useful as a temporary placeholder. | class Draft: pass |
Functions, generators, and classes
| Keyword | Purpose | Example |
|---|---|---|
def | Defines a named function. | def greet(): |
return | Sends a result back from a function. | return total |
yield | Produces a value from a generator and pauses its state. | yield number |
lambda | Creates a small anonymous function expression. | lambda x: x * 2 |
class | Defines 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
| Keyword | Purpose | Example |
|---|---|---|
try | Marks code that may raise an exception. | try: |
except | Handles a matching exception. | except ValueError: |
finally | Runs cleanup code whether an exception occurred or not. | finally: |
raise | Raises an exception intentionally. | raise ValueError() |
assert | Checks 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
| Keyword | Purpose | Example |
|---|---|---|
import | Loads a module. | import math |
from | Selects names from a module or package. | from math import pi |
as | Creates an alias for an imported name or exception. | import pandas as pd |
Scope and namespaces
| Keyword | Purpose | Guidance |
|---|---|---|
global | Allows a function to rebind a module-level name. | Use sparingly; return values are usually clearer. |
nonlocal | Allows a nested function to rebind a name in its enclosing function. | Useful in closures, but avoid unnecessary shared state. |
Context management and asynchronous code
| Keyword | Purpose | Example |
|---|---|---|
with | Uses a context manager to guarantee setup and cleanup. | with open(path) as file: |
async | Defines an asynchronous function or context. | async def fetch(): |
await | Waits 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 andis Noneto check for the singletonNone. - Catch specific exceptions instead of using a broad, silent
except. - Use
withfor resources such as files that must be closed. - Run
keyword.kwlistwhen you need the list for a particular Python installation.
Further Reading
Continue learning with these related Python tutorials:
Continue learning
