Python3.x Python Reserved Keywords
Python keywords (also called reserved words) are words that have special meaning in the Python language. They are reserved by the Python interpreter for specific syntax functions. These keywords cannot be used as variable names, function names, or other identifiers.
Characteristics
- Immutability: Keywords are part of the language specification and their meanings cannot be modified
- Finiteness: The number of Python keywords is fixed (Python 3.8 has 35 keywords)
- Case-sensitive: All keywords are in lowercase form
- Syntax function: Each keyword has a specific syntactic purpose
View All Keywords
You can use Python's keyword module to view all keywords for the current version:
Example
import keyword
print(keyword.kwlist)
In Python 3.8, the output is:
['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']
Keyword Categories and Usage
Python keywords can be divided into the following major categories by function:
1. Value Keywords
These keywords represent specific values:
| Keyword | Description | Example |
|---|---|---|
True |
Boolean true value | flag = True |
False |
Boolean false value | flag = False |
None |
Represents null or no value | result = None |
2. Operator Keywords
Used for logical and boolean operations:
| Keyword | Description | Example |
|---|---|---|
and |
Logical AND | if x > 0 and x < 10: |
or |
Logical OR | if x 100: |
not |
Logical NOT | if not is_valid: |
is |
Object identity comparison | if x is None: |
in |
Membership test | if 'a' in 'apple': |
3. Control Flow Keywords
Control program execution flow:
| Keyword | Description | Example |
|---|---|---|
if |
Conditional statement | if x > 0: print("Positive") |
elif |
Else if | elif x == 0: print("Zero") |
else |
Else | else: print("Negative") |
for |
Loop statement | for i in range(5): |
while |
Loop statement | while x > 0: |
break |
Break out of loop | break |
continue |
Continue to next iteration | continue |
4. Function and Class Related Keywords
Used to define and manipulate functions and classes:
| Keyword | Description | Example |
|---|---|---|
def |
Define function | def my_func(): |
return |
Function return value | return x + y |
lambda |
Anonymous function | f = lambda x: x**2 |
class |
Define class | class MyClass: |
pass |
Null statement placeholder | pass |
5. Exception Handling Keywords
Handle exceptions in programs:
| Keyword | Description | Example |
|---|---|---|
try |
Try to execute code block | try: |
except |
Catch exception | except ValueError: |
finally |
Execute regardless of exception | finally: |
raise |
Raise exception | raise ValueError("Invalid") |
6. Import and Module Keywords
Manage modules and imports:
| Keyword | Description | Example |
|---|---|---|
import |
Import module | import math |
from |
Import specific content from module | from math import sqrt |
as |
Alias | import numpy as np |
7. Variable Scope Keywords
Control variable scope:
| Keyword | Description | Example |
|---|---|---|
global |
Declare global variable | global count |
nonlocal |
Declare nonlocal variable | nonlocal x |
8. Asynchronous Programming Keywords
(Added in Python 3.5+):
| Keyword | Description | Example |
|---|---|---|
async |
Define asynchronous function | async def fetch(): |
await |
Wait for asynchronous operation to complete | await response |
9. Other Keywords
| Keyword | Description | Example |
|---|---|---|
del |
Delete reference | del my_list |
with |
Context manager | with open('file') as f: |
yield |
Generator return value | yield x |
assert |
Assert condition is true | assert x > 0 |
Correct Usage of Keywords
1. Cannot Be Used as Identifiers
Attempting to use keywords as variable names will cause syntax errors:
Example
# Error example
class = "Computer Science" # SyntaxError
2. Pay Attention to Case
Python keywords are all lowercase, but words with different cases can be used as identifiers:
Example
# This is allowed
Class = "Math" # Not a keyword
3. Context Correctness
Each keyword has a specific usage context; incorrect usage will cause syntax errors:
Example
# Error example
def = 5 # SyntaxError
4. Combined Usage
Many keywords need to be combined to function fully:
Example
# if-elif-else combination
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Practical Application Examples
Example 1: Control Flow Keywords Application
Example
# Determine grade level
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print(f"Grade: {grade}")
Example 2: Function and Exception Handling
Example
# Safe square root calculation function
import math
def safe_sqrt(x):
try:
result = math.sqrt(x)
except ValueError:
print("Cannot calculate square root of negative number")
result = None
finally:
print("Calculation complete")
return result
print(safe_sqrt(4)) # 2.0
print(safe_sqrt(-1)) # Cannot calculate square root of negative numbernNone
Example 3: Context Manager
Example
# Using with keyword to automatically manage file resources
with open('example.txt', 'w') as f:
f.write("Hello, Python Keywords!")
# File will be automatically closed, no need to manually call f.close()
Common Errors and Precautions
1. Misusing keywords as variable names
Example
# Wrong
from = "Beijing"
# Correct
origin = "Beijing"
2. Forgetting the colon
Example
# Wrong
if x > 0
print("Positive")
# Correct
if x > 0:
print("Positive")
3. Incomplete control structure
Example
# Wrong - missing else or elif
if x > 0:
elif x == 0:
# Correct
if x > 0:
pass
elif x == 0:
pass
4. Incorrect indentation
Example
# Wrong
if x > 0:
print("Positive") # Missing indentation
# Correct
if x > 0:
print("Positive")
5. Version differences
- Python 2.x has print and exec as keywords
- Python 3.x has print and exec as built-in functions, no longer keywords
- async and await are new keywords added in Python 3.5+
YouTip