Keywords are reserved words in Python with predefined meanings and functions. They are part of the Python syntax and cannot be used as variable names, function names, or identifiers. Each keyword serves a specific purpose and helps define the structure of a Python program.
Here’s an overview of Python keywords:
1. Characteristics of Keywords:
- Reserved Words: Cannot be used for naming variables, functions, or classes.
- Case-Sensitive: All keywords are lowercase; using uppercase letters will lead to a syntax error.
- Predefined Role: Each keyword has a fixed role and usage.
2. List of Python Keywords:
As of Python 3.10, there are 35 keywords. To get the latest list, you can use the following code:
import keyword
print(keyword.kwlist)
Example list:
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except,
finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
3. Categories of Keywords:
a. Logical Keywords:
- True, False, None: Represent boolean values and a null value.
is_active = True
result = None
b. Conditional and Loop Control:
- if, elif, else: Conditional statements.
if x > 0:
print(“Positive”)
elif x == 0:
print(“Zero”)
else:
print(“Negative”)
- for, while, break, continue: Loop control.
for i in range(5):
if i == 3:
break
print(i)
c. Exception Handling:
- try, except, finally, raise: Manage errors in code.
try:
x = 10 / 0
except ZeroDivisionError:
print(“Cannot divide by zero”)
finally:
print(“Execution complete”)
d. Function and Class Declaration:
- def, return, lambda: Define functions.
def add(a, b):
return a + b
- class: Define classes.
class MyClass:
pass
e. Import and Context Management:
- import, from, as: Import modules.
import math as m
print(m.sqrt(16))
- with: Context management.
with open(‘file.txt’, ‘r’) as file:
data = file.read()
f. Logical Operators:
- and, or, not, is, in: Logical comparisons.
if x > 0 and y > 0:
print(“Both are positive”)
g. Variable Scope:
- global, nonlocal: Scope control.
def outer():
x = 10
def inner():
nonlocal x
x += 1
inner()
print(x)
h. Asynchronous Programming:
- async, await: Work with asynchronous code.
import asyncio
async def main():
await asyncio.sleep(1)
i. Miscellaneous:
- assert: Debugging tool to check conditions.
assert x > 0, “x must be positive”
- del: Delete an object or variable.
del x
4. Best Practices with Keywords:
- Avoid naming variables or functions with keywords.
# Incorrect
def if(): # SyntaxError
pass
- Use keywords for their intended purpose to enhance code readability.
5. Checking Keywords in Your Version:
To confirm keywords specific to your Python version:
import keyword
print(keyword.iskeyword(‘if’)) # True
Keywords are fundamental to Python’s syntax and essential for building structured, functional, and efficient programs. Mastering their usage is key to becoming proficient in Python!