Python Reserved Keywords

Python3 基础语法Python3 Basic Syntax

Python keywords (also called reserved words) are words with special meanings in the Python language. They are reserved by the Python interpreter for specific syntactic functions. These keywords cannot be used as variable names, function names, or other identifiers.

Features

  1. Immutability: Keywords are part of the language specification, and their meanings cannot be modified
  2. Finiteness: The number of Python keywords is fixed (Python 3.8 has 35 keywords)
  3. Case sensitivity: All keywords are in lowercase
  4. Syntactic function: Each keyword has a specific syntactic role

View All Keywords

You can use Python'skeywordmodule to view all keywords of 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 Classification and Usage

Python keywords can be divided into the following 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 < 0 or 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 Otherwise if elif x == 0: print("Zero")
else Otherwise 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 the next loop iteration continue

4. Function and Class Related Keywords

Used to define and operate on 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 Empty statement placeholder pass

5. Exception Handling Keywords

Handle exceptions in programs:

Keyword Description Example
try Attempt to execute a code block try:
except Catch exception except ValueError:
finally Execute whether or not an exception occurs 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 a 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

(New 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[0]
with Context management 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 a keyword as a variable name will cause a syntax error:

Example

# Wrong example
class = "Computer Science"  # SyntaxError

2. Pay Attention to Case Sensitivity

Python keywords are all lowercase, but words with different casing can be used as identifiers:

Example

# This is allowed
Class = "Math"  # Not a keyword

3. Context Correctness

Each keyword has a specific usage context, and incorrect usage will cause a syntax error:

Example

# Wrong example
def = 5  # SyntaxError

4. Combined Usage

Many keywords need to be used in combination to achieve full functionality:

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 Keyword 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 level: {grade}")

Example 2: Functions and Exception Handling

Example

# Safe function to calculate square root
import math

def safe_sqrt(x):
    try:
        result = math.sqrt(x)
    except ValueError:
        print("Cannot calculate the square root of a negative number")
        result = None
    finally:
        print("Calculation completed")
    return result

print(safe_sqrt(4))  # 2.0
print(safe_sqrt(-1)) # Cannot calculate the square root of a negative number\nNone

Example 3: Context Manager

Example

# Use the with keyword to automatically manage file resources
with open('example.txt', 'w') as f:
    f.write("Hello, Python Keywords!")
# The 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 structures

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
  • In Python 3.x, print and exec are built-in functions and are no longer keywords
  • async and await are new keywords added in Python 3.5+

Python3 基础语法Python3 Basic Syntax

Other Extensions