Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python reserved keywords

Python reserved keywords

Python3 Basic Syntax Python3 Basic Syntax

Python keywords (also called reserved words) are words with 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.

Feature

  1. Immutability: Keywords are part of the language specification and their meaning cannot be changed
  2. Finiteness: The number of Python keywords is fixed (Python 3.8 has 35 keywords)
  3. Case Sensitive: All keywords are lowercase
  4. Syntax function: Every keyword has a specific syntactic role

View all keywords

You can use Python's keyword module 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 categories and uses

Python keywords can be divided into the following broad categories by function:

1. Value keywords

These keywords represent specific values:

The keyword Description Example
True Boolean true value flag = True
False Boolean false value flag = False
None Represents an empty or absent value result = None

2. Operator keywords

Used for logical and Boolean operations:

The 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 the flow of program execution:

The 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 the next loop iteration continue

4. Function and class keywords

Used to define and work with functions and classes:

The keyword Description Example
def Defining a function def my_func():
return Function return value return x + y
lambda Anonymous functions f = lambda x: x**2
class Define a class class MyClass:
pass Placeholder for an empty statement pass

5. Exception handling keywords

Handle exceptions in a program:

The keyword Description Example
try Try to execute a block of code try:
except Catching an Exception except ValueError:
finally Executed whether or not an exception occurs finally:
raise Throwing an Exception raise ValueError("Invalid")

6. Import and module keywords

Manage modules and imports:

The keyword Description Example
import Import the 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:

The keyword Description Example
global Declare a global variable global count
nonlocal Declare a nonlocal variable nonlocal x

8. Asynchronous programming keywords

(new in Python 3.5+):

The keyword Description Example
async Define an asynchronous function async def fetch():
await Wait for an asynchronous operation to complete await response

9. Other keywords

The keyword Description Example
del Delete a reference del my_list[0]
with Context management with open('file') as f:
yield Return a value from a generator yield x
assert Assert that a condition is true assert x > 0

Correct use of keywords

1. Cannot be used as identifiers

Trying to use a keyword as a variable name causes a syntax error:

Example

Incorrect Example

class

=

"Computer Science"

 

SyntaxError

2. Watch the case

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

Example

This is allowed

Class

=

"Math"

 

Not a keyword

3. Contextual correctness

Every keyword has a specific context of use; incorrect use causes a syntax error:

Example

Incorrect Example

def

=

5

 

SyntaxError

4. Combined use

Many keywords need to be combined to be fully functional:

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

Example

Determine the 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: functions and exception handling

Example

A safe function to compute the square root

import

math

def

safe_sqrt

(

x

)

:

   

try

:

        result

=

math

.

sqrt

(

x

)

   

except

ValueError

:

       

print

(

"Cannot compute the square root of a negative number"

)

        result

=

None

   

finally

:

       

print

(

"Computation complete"

)

   

return

result

print

(

safe_sqrt

(

4

)

)

 

2.0

print

(

safe_sqrt

(

1

)

)

Cannot compute the square root of a negative number\nNone

Example 3: context managers

Example

Use the with keyword to manage file resources automatically

with

open

(

'example.txt'

,

'w'

)

as

f:

    f.

write

(

"Hello, Python Keywords!"

)

The file is closed automatically; there is no need to call f.close() manually


Common errors and caveats

1. Misusing a keyword as a variable name

Example

Error

from

=

"Beijing"

   

Correct

origin

=

"Beijing"

2. Forgetting the colon

Example

Error

if

x

0

   

print

(

"Positive"

)

   

Correct

if

x

0

:

   

print

(

"Positive"

)

3. Incomplete control structure

Example

Error - missing else or elif

if

x

0

:

elif

x

==

0

:

   

Correct

if

x

0

:

   

pass

elif

x

==

0

:

   

pass

4. Incorrect indentation

Example

Error

if

x

0

:

print

(

"Positive"

)

 

Missing indentation

   

Correct

if

x

0

:

   

print

(

"Positive"

)

5. Version differences

Python3 Basic Syntax Python3 Basic Syntax