🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreePython Keywords: A Complete Guide to All 35 Reserved Words

Python keywords are the building blocks of every program you write. If you are learning Python or building projects and hitting confusing errors, understanding these reserved words will save you hours of frustration. I have been writing Python for over a decade, and knowing these keywords deeply has made my code cleaner and my debugging faster. Walking through every Python keyword, this tutorial delivers practical examples you can run today.
What Are Python Keywords?
Python keywords are 35 reserved words that the Python interpreter uses to understand your code. You cannot use these words as variable names, function names, or any identifier in your program. Each keyword has a specific meaning and purpose in the language grammar.
When you try to use a keyword as a variable name, Python throws a SyntaxError immediately. The protection ensures your code remains predictable and the language grammar stays unambiguous.
# This will cause an error class = "MyClass"
The interpreter sees the word class and expects a class definition, not a string assignment. That conflict produces a syntax error.
How to List All Python Keywords
Python ships with a built-in module called keyword that lets you programmatically list every keyword. Use this when you need to validate user input or build tools that work with Python code.
import keyword
print("Total Python keywords:", len(keyword.kwlist))
print(keyword.kwlist)
Running this in Python 3.10 or later gives you the complete list of 35 keywords. The keyword.iskeyword() function lets you check if any string is a reserved keyword.
import keyword
print(keyword.iskeyword("class")) # True
print(keyword.iskeyword("my_var")) # False
The Complete List of Python Keywords
Let me break these 35 keywords into logical groups so you can understand their relationships. I cover each group in detail with real code examples.
Group 1: Control Flow Keywords
These keywords control the execution flow of your program. They decide which code runs, which code repeats, and which code gets skipped.
if, elif, else
The if family of keywords creates conditional branches in your code. Python uses indentation to define blocks, and the if statement is the foundation of decision-making in the language.
temperature = 28
if temperature > 35:
print("It is extremely hot")
elif temperature > 25:
print("It is warm")
else:
print("It is cool")
The elif keyword chains multiple conditions together. The else block catches anything that did not match the previous conditions.
for, while
The for keyword iterates over sequences like lists, strings, dictionaries, and range objects. The while keyword repeats a block as long as a condition stays true.
# for loop over a list
fruits = ["apple", "mango", "banana"]
for fruit in fruits:
print(fruit)
# while loop with a counter
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
The for loop in Python works directly with sequences. You do not need an index variable unless you specifically want one.
break, continue
The break keyword immediately exits the nearest enclosing loop. The continue keyword skips the rest of the current iteration and jumps to the next one.
# break exits the loop entirely
for i in range(10):
if i == 5:
break
print(i) # prints 0, 1, 2, 3, 4
# continue skips to next iteration
for i in range(5):
if i == 2:
continue
print(i) # prints 0, 1, 3, 4
pass
The pass keyword is a null operation. It does absolutely nothing, but it satisfies the Python parser when you need a statement in a block that you have not implemented yet.
def my_function():
pass # TODO: implement this later
class MyPlaceholder:
pass
This is different from leaving the block empty. An empty block produces a IndentationError, but pass makes the block valid and runnable.
Group 2: Loop Helpers
Python 3 introduced two keywords that work specifically with loops and iteration contexts.
for ... else and while ... else
The else keyword also works with loops. The block after the else runs only when the loop completes normally without hitting a break.
numbers = [3, 5, 7, 9]
for n in numbers:
if n % 2 == 0:
print(f"Found even number: {n}")
break
else:
print("No even numbers found")
This pattern is particularly useful for search algorithms where you want to know whether the loop found something or exhausted the search space.
Group 3: Function and Class Definition Keywords
def
The def keyword defines functions. Everything indented under a def line belongs to that function body.
def greet(name):
return f"Hello, {name}!"
result = greet("Ninad")
print(result)
return
The return keyword sends a value back from a function. If a function reaches the end without a return, or if it uses return without a value, the function returns None.
def add(a, b):
return a + b
def process():
return # returns None
print(add(3, 4)) # 7
print(process()) # None
yield
The yield keyword turns a regular function into a generator. Instead of returning all values at once, a generator function yields one value at a time, keeping its state between calls. Memory efficiency is a key advantage for large sequences.
def count_up_to(max_val):
count = 1
while count <= max_val:
yield count
count += 1
for num in count_up_to(3):
print(num) # prints 1, 2, 3
Compare this with return. A function with return stops executing after returning. A function with yield pauses and resumes from where it left off.
lambda
The lambda keyword creates anonymous inline functions. These are single-expression functions without a name. They are useful for short throwaway functions, especially as arguments to higher-order functions like map, filter, and sorted.
square = lambda x: x ** 2 print(square(5)) # 25 numbers = [4, 2, 8, 1] sorted_nums = sorted(numbers, key=lambda x: -x) print(sorted_nums) # [8, 4, 2, 1]
For anything beyond a simple expression, use a regular def function. Lambda functions are limited to a single logical line of code.
class
The class keyword defines a new class. Classes are blueprints for creating objects with shared attributes and methods.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
r = Rectangle(5, 3)
print(r.area()) # 15
self
The self keyword refers to the current instance of a class within method definitions. You must use self explicitly in Python methods, unlike implicit this references in languages like Java or C++.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
d = Dog("Buddy")
print(d.bark()) # Buddy says Woof!
global, nonlocal
These keywords give you controlled ways to modify variables from outer scopes. Python demands that you declare intent before modifying a variable from an enclosing scope.
# global lets you modify a module-level variable
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # 1
# nonlocal lets you modify a variable in an enclosing function scope
def outer():
count = 10
def inner():
nonlocal count
count += 5
inner()
print(count) # 15
outer()
Avoid overusing global. It makes code harder to test and reason about. Passing variables as arguments and returning values produces cleaner code.
Group 4: Exception Handling Keywords
Exception handling keywords let you manage errors gracefully without crashing your program.
try, except, finally
The try block contains code that might raise an exception. The except blocks handle specific exception types. The finally block runs no matter what, whether an exception occurred or not.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
result = None
print("Cannot divide by zero")
finally:
print("Division attempt complete")
return result
print(divide(10, 2)) # 5.0
print(divide(10, 0)) # None
You can also catch multiple exception types in a single except block using a tuple.
try:
value = int("not a number")
except (ValueError, TypeError) as e:
print(f"Error: {e}")
raise
The raise keyword explicitly throws an exception. You can raise built-in exceptions or custom ones you define.
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return age
try:
validate_age(-5)
except ValueError as e:
print(e) # Age cannot be negative
assert
The assert keyword checks a condition and raises an AssertionError if the condition is false. Assertions are debugging aids that document your assumptions about the code.
def square(x):
assert isinstance(x, (int, float)), "x must be a number"
return x * x
print(square(4)) # 16
square("four") # AssertionError
Assertions can be disabled with the -O flag when running Python, so never use them for input validation that must always happen.
Group 5: Module and Import Keywords
import, from, as
The import keyword brings external modules into your program. The from keyword lets you import specific items from a module. The as keyword gives an imported item an alias.
import math
from collections import defaultdict
import numpy as np
print(math.pi) # 3.141592653589793
print(defaultdict(list)) # defaultdict(<class 'list'>, {})
print(np.array([1, 2])) # array([1, 2])
with
The with keyword sets up a context manager. The most common use is for file operations, where with guarantees the file gets closed even if an exception occurs.
with open("example.txt", "w") as f:
f.write("Hello from AskPython")
# File is guaranteed to be closed here
Without with, you would need to manually call f.close() inside a try/finally block. The with statement handles this automatically.
Group 6: Variable and Type Keywords
None
The None keyword represents the absence of a value. It is the default return value of functions that do not have an explicit return statement. It is also the default value for optional function arguments that the caller does not provide.
def greet(name=None):
if name is None:
return "Hello, stranger!"
return f"Hello, {name}!"
print(greet()) # Hello, stranger!
print(greet("Ninad")) # Hello, Ninad!
Never use None to mean something falsy like zero or an empty string. These are legitimately different values. Use explicit checks instead.
True, False
The True and False keywords represent the Boolean truth values. Everything in Python has a truth value, which means you can use any object in a conditional statement.
is_active = True
is_empty = False
if is_active and not is_empty:
print("System is active and has data")
# Falsy values in Python
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool(None)) # False
Group 7: Identity and Comparison Keywords
is
The is keyword checks whether two variables refer to the exact same object in memory. The is operator differs from ==, which checks for value equality.
a = [1, 2, 3] b = [1, 2, 3] c = a print(a == b) # True (same values) print(a is b) # False (different objects) print(a is c) # True (same object)
Use is only for comparing with None, True, or False. For everything else, prefer ==.
in
The in keyword checks whether a value exists within a sequence. It works with lists, tuples, sets, dictionaries, strings, and any object that implements the membership test protocol.
numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # True
print(7 in numbers) # False
name = "Python"
print("th" in name) # True
data = {"key": "value"}
print("key" in data) # True (checks keys)
Group 8: Logical Operator Keywords
and, or, not
These are Python logical operators written as words rather than symbols. The and and or operators short-circuit, meaning Python stops evaluating as soon as the result is determined.
# and - both must be truthy print(True and True) # True print(True and False) # False # or - at least one must be truthy print(True or False) # True print(False or False) # False # not - inverts truth value print(not True) # False print(not False) # True # Short-circuit example x = 0 result = x != 0 and 10 / x > 1 # No ZeroDivisionError because second part is not evaluated print(result) # False
Group 9: Python 3 Specific Keywords
async, await
Python 3.5 introduced async and await for asynchronous programming. These keywords let you write concurrent code that handles I/O-bound tasks without threads.
import asyncio
async def fetch_data():
await asyncio.sleep(1)
return "Data fetched"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
The async keyword marks a function as asynchronous. The await keyword pauses the execution of an async function until the awaited coroutine completes.
match, case (Python 3.10+)
Python 3.10 introduced structural pattern matching using match and case keywords. Pattern matching is more powerful than simple switch statements because it can destructure data as it matches.
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown status"
print(http_status(200)) # OK
print(http_status(404)) # Not Found
# Pattern matching with data structures
def describe_point(point):
match point:
case (0, 0):
return "Origin"
case (x, 0):
return f"Point on x-axis at {x}"
case (0, y):
return f"Point on y-axis at {y}"
case (x, y):
return f"Point at ({x}, {y})"
print(describe_point((3, 4))) # Point at (3, 4)
Group 10: Context Management Keywords
del
The del keyword removes variables, items from collections, or attributes from objects. It does not always free memory immediately, but it unbinds the name from the object.
my_list = [1, 2, 3, 4, 5] del my_list[2] # Remove item at index 2 print(my_list) # [1, 2, 4, 5] del my_list # Remove the variable entirely # print(my_list) # NameError: name 'my_list' is not defined
Group 11: Miscellaneous Keywords
is, as
I covered is above. The as keyword also appears in exception handling and with statements to create aliases.
# Exception alias
try:
int("bad")
except ValueError as err:
print(f"Error type: {type(err).__name__}")
# Context manager alias
with open("file.txt") as f:
content = f.read()
type
Wait, type is not a keyword. type is a built-in function. These are two different things. Built-in functions can be shadowed by your own variables, while keywords absolutely cannot be used as names.
print, input
Similarly, print and input are built-in functions, not keywords. You can technically reassign them, but you should never do this in real code.
Python Keywords vs Built-in Functions
A common point of confusion is the difference between keywords and built-in functions. Python keywords are reserved by the language grammar itself. Built-in functions live in the builtins module and can technically be reassigned, though this is almost never a good idea.
# You cannot do this - SyntaxError
# def = 5
# You CAN do this, but you SHOULD NOT
print = "oops"
print("This will crash") # TypeError: 'str' object is not callable
The safe way to check what is a keyword versus a built-in is to use the keyword module.
import keyword
import builtins
print("print is a keyword:", keyword.iskeyword("print")) # False
print("print is a builtin:", hasattr(builtins, "print")) # True
print("class is a keyword:", keyword.iskeyword("class")) # True
Common Mistakes to Avoid
After years of reviewing Python code, here are the mistakes I see most often related to keywords.
Using keywords as variable names happens to beginners. The error message is clear once you know what to look for. Name your variables descriptively and check the keyword list if you get a mysterious syntax error on a line that looks fine.
# Wrong class = "MyClass" # SyntaxError return = 5 # SyntaxError # Correct my_class = "MyClass" # Fine return_value = 5 # Fine
Confusing is with == causes subtle bugs. Always use == for value comparisons. Reserve is for singleton checks like None.
Forgetting to use return in a function that needs to pass data back. Python functions return None by default, and it is easy to miss this in a long function.
Overusing lambda when a named function would be clearer. If the lambda spans more than one line, define a proper function instead.
Python Keywords Summary Table
| Keyword | Purpose | Group |
|---|---|---|
| False | Boolean false value | Booleans |
| None | Null or missing value | Booleans |
| True | Boolean true value | Booleans |
| and | Logical AND | Logical |
| as | Alias or import renaming | Import |
| assert | Debug assertion | Exception |
| async | Define async function | Async |
| await | Wait for async coroutine | Async |
| break | Exit loop immediately | Loop |
| class | Define a class | Class |
| continue | Skip to next loop iteration | Loop |
| def | Define a function | Function |
| del | Delete a reference | Misc |
| elif | Else-if branch | Control |
| else | Else branch or loop else | Control |
| except | Handle exception | Exception |
| finally | Always execute block | Exception |
| for | For loop | Loop |
| from | Import from module | Import |
| global | Modify global variable | Scope |
| if | Conditional branch | Control |
| import | Import a module | Import |
| in | Membership test | Operators |
| is | Identity comparison | Operators |
| lambda | Anonymous function | Function |
| match | Pattern matching | Control |
| nonlocal | Modify enclosing scope | Scope |
| not | Logical NOT | Logical |
| or | Logical OR | Logical |
| pass | Null operation | Misc |
| raise | Throw an exception | Exception |
| return | Return from function | Function |
| try | Try block for exceptions | Exception |
| while | While loop | Loop |
| with | Context manager | Context |
| yield | Generator yield | Function |
Practical Examples Using Multiple Keywords
Let me show you how multiple keywords work together in real programs. These examples combine several concepts from the table above.
Example 1: Data Validation Pipeline
This function combines try, except, raise, if, else, and return in a practical data validation scenario.
def parse_positive_int(value):
try:
number = int(value)
except (ValueError, TypeError):
raise ValueError(f"Cannot convert '{value}' to integer")
if number <= 0:
raise ValueError(f"Expected positive integer, got {number}")
return number
# Test the function
test_values = [10, -5, "7", "abc", 0]
for val in test_values:
try:
result = parse_positive_int(val)
print(f"'{val}' -> {result}")
except ValueError as e:
print(f"'{val}' -> Error: {e}")
Output:
'10' -> 10 '-5' -> Error: Expected positive integer, got -5 '7' -> 7 'abc' -> Error: Cannot convert 'abc' to integer '0' -> Error: Expected positive integer, got 0
Example 2: Generator Pipeline with Yield
Generators are memory-efficient for processing large datasets. Here I use def, yield, for, in, if, and return together.
def process_numbers(numbers):
for num in numbers:
if num % 2 == 0:
yield num * num
else:
yield num
def sum_results(numbers):
total = 0
for result in process_numbers(numbers):
total += result
return total
data = [1, 2, 3, 4, 5, 6]
print(sum_results(data)) # 4 + 3 + 16 + 5 + 36 = 64
The process_numbers function never builds a full list in memory. It processes one value at a time and yields results as they are ready.
Example 3: Context Manager with Resource Management
The with keyword combined with exception handling creates robust resource management.
class FileCounter:
def __init__(self, filename):
self.filename = filename
self.file = None
self.line_count = 0
def __enter__(self):
self.file = open(self.filename, "r")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
return False # Do not suppress exceptions
def count_lines(self):
if self.file is None:
raise RuntimeError("File not opened. Use 'with' statement.")
self.line_count = sum(1 for _ in self.file)
return self.line_count
# Create a test file first
with open("test_file.txt", "w") as f:
f.write("Line 1\nLine 2\nLine 3\n")
# Use the context manager
with FileCounter("test_file.txt") as counter:
lines = counter.count_lines()
print(f"Total lines: {lines}")
Python Keywords in Different Python Versions
Python has added keywords in recent releases. Here is how the keyword set has evolved.
Python 2 did not have with, as, True, False, or None as keywords. Python 3 corrected a design mistake where True and False were built-in variables that you could technically overwrite in Python 2.
Python 3.5 introduced async and await as keywords. Python 3.10 introduced match and case for structural pattern matching. These are the two most recent keyword additions.
You can check your Python version by running python --version in your terminal. Newer versions give you more expressive syntax, but the core keywords have been stable for years.
How to Remember All Python Keywords
I found it easiest to group keywords by what they do rather than memorize them alphabetically. Think in terms of categories: control flow, data types, functions, exceptions, and scope. Once you understand the category, each keyword makes sense in context.
Practice matters more than memorization. Write programs that use try/except, write generators with yield, use context managers with with. After writing a few real programs, the keywords become natural.
Frequently Asked Questions
How many Python keywords are there?
Python 3 has 35 keywords. The keyword count grows with new language versions. Python 3.10 added two new keywords (match and case) for structural pattern matching.
Can I use Python keywords as variable names?
No. Keywords are reserved by the Python grammar and cannot be used as identifiers. Attempting to do so produces a SyntaxError.
What is the difference between is and ==?
The is operator checks whether two references point to the exact same object in memory. The == operator checks whether two objects have the same value. Always use == for value comparisons and is only for comparing with singletons like None, True, or False.
What does the yield keyword do?
The yield keyword turns a function into a generator. Instead of returning all values at once, the function produces values one at a time, maintaining its internal state between calls. Use this approach for processing large datasets without loading everything into memory.
What is the pass keyword used for?
The pass keyword is a placeholder that does nothing. It satisfies the Python parser when you need a statement in a block that is not yet implemented, such as an empty function body or class definition.
What is the difference between global and nonlocal?
The global keyword lets you modify a variable in the module-level scope from within a function. The nonlocal keyword lets you modify a variable in an enclosing function scope from within a nested function. Neither should be used excessively in production code.
What are async and await keywords?
The async keyword marks a function as asynchronous, meaning it can pause and resume. The await keyword pauses an async function until a given coroutine completes. Together they enable concurrent I/O operations without threads.
What is the match keyword in Python?
The match keyword (Python 3.10+) performs structural pattern matching. You compare a value against several patterns defined with case clauses, and Python extracts data from the value as part of the match.
Conclusion
Python keywords are the foundation of every program you write. I covered all 35 keywords in this tutorial with practical examples for each one. The key takeaway is that keywords are not just words to memorize; they are tools that solve specific problems. Understand what each one does, practice using them in real code, and you will write Python that is clean, correct, and maintainable.
If you are starting with Python, focus first on the control flow keywords (if, for, while, def, return), then gradually incorporate exception handling (try, except, raise), context managers (with), and advanced features like generators (yield) and async code (async, await). The journey is worth it.