Master Python Keywords: Complete List, Usage, and Common Pitfalls
This article explains what Python keywords are, shows how to list all keywords in Python 3.x, describes the most common keywords with their typical uses, provides extensive code examples for various language constructs, and offers practical guidelines to avoid common mistakes.
Introduction
In Python, keywords are reserved words that have special meaning in the language syntax and cannot be used as identifiers such as variable names, function names, or class names.
Listing All Keywords in Python 3.x
import keyword
print("Python keywords list:")
print(keyword.kwlist)Running the code prints the complete list of keywords for the current Python version.
Common Keywords and Their Typical Usage
and – logical AND operator.
as – creates an alias or renames an imported module.
assert – asserts that an expression is true.
async – defines an asynchronous function (available from Python 3.5).
await – waits for the result of an asynchronous operation.
break – exits a loop.
class – defines a class.
continue – skips the rest of the current loop iteration.
def – defines a function.
del – deletes an object.
elif – additional condition in an if statement.
else – default branch in an if statement.
except – catches exceptions.
False – boolean value False.
finally – block that always executes after a try block.
for – creates a loop.
from – imports specific parts of a module.
global – declares a global variable.
if – conditional statement.
import – imports a module.
in – membership test.
is – identity comparison.
lambda – creates an anonymous function.
None – represents the absence of a value.
nonlocal – references a variable in an enclosing function.
not – logical NOT operator.
or – logical OR operator.
pass – placeholder that does nothing.
raise – raises an exception.
return – returns a value from a function.
True – boolean value True.
try – starts a block that may raise an exception.
while – creates a loop.
with – manages resources such as files.
yield – defines a generator function.
Code Examples Demonstrating Keyword Usage
Class definition and __init__
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
person = Person("Alice", 30)
person.display()Conditional statements with if‑elif‑else
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print(f"The grade is: {grade}")Loops
# Print numbers 1 to 10
for i in range(1, 11):
print(i)
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)While loop
count = 0
while count < 5:
print(count)
count += 1Exception handling with try‑except‑finally
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This will always execute.")File handling with with
# Write to a file
with open("example.txt", "w") as file:
file.write("Hello, World!")
# Read from the file
with open("example.txt", "r") as file:
content = file.read()
print(content)Function definition
def greet(name):
return f"Hello, {name}!"
print(greet("Bob"))Lambda function
# Simple lambda
square = lambda x: x * x
print(square(5))
# Lambda as argument to map
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x * x, numbers))
print(squared_numbers)Generator with yield
def number_generator():
for i in range(5):
yield i
gen = number_generator()
for num in gen:
print(num)Global and nonlocal
# Global variable
x = 10
def modify_global():
global x
x = 20
modify_global()
print(x) # 20
# Nonlocal variable in nested function
def outer():
y = 10
def inner():
nonlocal y
y = 20
inner()
print(y) # 20
outer()Asynchronous programming with async / await
import asyncio
async def say_hello(name):
await asyncio.sleep(1)
print(f"Hello, {name}!")
async def main():
task1 = asyncio.create_task(say_hello("Alice"))
task2 = asyncio.create_task(say_hello("Bob"))
await task1
await task2
asyncio.run(main())Class methods and static methods
class MyClass:
class_variable = "I am a class variable"
def __init__(self, instance_variable):
self.instance_variable = instance_variable
@classmethod
def class_method(cls):
print(f"Class method: {cls.class_variable}")
@staticmethod
def static_method():
print("Static method")
MyClass.class_method()
MyClass.static_method()Properties with @property
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value
person = Person("Alice", 30)
print(person.name)
person.age = 35
print(person.age)Best Practices and Usage Considerations
Python keywords are case‑sensitive and must be written in lower case; using a different case (e.g., And or AND) results in a syntax error. Avoid using keywords as identifiers, and be aware of reserved words that are not yet keywords but may become so in future releases. Modern IDEs and code editors highlight keywords and can warn you when you accidentally reuse them as identifiers. Consulting the official Python documentation is the most reliable way to verify whether a term is a keyword or a reserved word.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
