1. Python 基础教程
  2. 在 SublimeEditor 中配置 Python 环境
  3. Python 代码中添加注释
  4. Python 中的变量的使用
  5. Python 中的数据类型
  6. Python 中的关键字
  7. Python 字符串操作
  8. Python 中的 list 操作
  9. Python 中的 Tuple 操作
  10. Pythonmax()和 min()–在列表或数组中查找最大值和最小值
  11. Python 找到最大的 N 个(前 N 个)或最小的 N 个项目
  12. Python 读写 CSV 文件
  13. Python 中使用 httplib2–HTTPGET 和 POST 示例
  14. Python 将 tuple 开箱为变量或参数
  15. Python 开箱 Tuple–太多值无法解压
  16. Pythonmultidict 示例–将单个键映射到字典中的多个值
  17. PythonOrderedDict–有序字典
  18. Python 字典交集–比较两个字典
  19. Python 优先级队列示例

Python 中的关键字

Python 关键字Python 编程语言的保留字。这些关键字具有特定的语法含义,不能用作变量名或其他标识符。

Python 中共有 35 个关键字,以下是它们的用法详解。


逻辑与控制流

and
逻辑与运算符。如果两个语句都为 True,则返回 True

x = (5 > 3 and 5 < 10)
print(x)   # True

or
逻辑或运算符。如果两个语句中任意一个为 True,则返回 True;如果两个都为 False,则返回 False

x = (5 > 3 or 5 > 10)
print(x)   # True

not
逻辑运算符,用于反转 TrueFalse 的值。

x = False
print(not x)   # True

if
用于创建条件语句,仅当条件为 True 时执行代码块。

x = 5

if x > 3:
    print("it is true")

elif
用于条件语句,是 else if 的缩写。

i = 5

if i > 0:
    print("Positive")
elif i == 0:
    print("ZERO")
else:
    print("Negative")

else
决定在 if..else 语句中条件为 False 时执行的操作。也可用于 try...except 块。

i = 5

if i > 0:
    print("Positive")
else:
    print("Negative")

try...except 中的用法:

x = 5

try:
    x > 10
except:
    print("Something went wrong")
else:
    print("Normally execute the code")

for
用于创建 for 循环,可遍历序列(如列表、元组等)。

for x in range(1, 9):
    print(x)

while
用于创建 while 循环,只要条件语句为 True,循环就会继续。

x = 0

while x < 9:
    print(x)
    x = x + 1

break
用于跳出 for 循环或 while 循环。

i = 1

while i < 9:
    print(i)
    if i == 3:
        break
    i += 1

continue
用于结束当前迭代(在 forwhile 循环中),并继续下一次迭代。

for i in range(9):
    if i == 3:
        continue
    print(i)

函数与类定义

class
用于创建类。

class User:
    name = "John"
    age = 36

def
用于创建或定义函数。

def my_function():
    print("Hello world !!")

my_function()

lambda
用于创建小型匿名函数。它可以接受任意数量的参数,但只能有一个表达式。

x = lambda a, b, c : a + b + c

print(x(5, 6, 2))

return
用于退出函数并返回值。

def myfunction():
    return 3 + 3

yield
用于结束函数,返回一个生成器(generator)。


异常处理

try
定义一个代码块以测试是否包含错误。

except
定义当 try 块引发错误时要运行的代码块。

try:
    x > 3
except:
    print("Something went wrong")

finally
定义一个代码块,无论 try 块是否引发错误,该块都会被执行。

try:
    x > 3
except:
    print("Something went wrong")
finally:
    print("I will always get executed")

raise
用于手动引发异常。

x = "hello"

if not type(x) is int:
    raise TypeError("Only integers are allowed")

assert
用于调试代码。它测试一个条件,如果条件为 False,程序将抛出 AssertionError

x = "hello"

assert x == "goodbye", "x should be 'hello'"  # AssertionError

with
用于简化异常处理(常用于资源管理,如文件操作)。


变量与作用域

as
用于创建别名。

import calendar as c
print(c.month_name[1])  # January

del
用于删除对象。在 Python 中一切皆对象,因此 del 也可用于删除变量、列表或列表的一部分等。

x = "hello"

del x

global
用于在非线性作用域(例如函数内部)创建全局变量。

def myfunction():
    global x
    x = "hello"

nonlocal
用于声明变量不是局部的。它用于嵌套函数内部,表示该变量不属于内部函数。

def myfunc1():
    x = "John"
    def myfunc2():
        nonlocal x
        x = "hello"
    myfunc2()
    return x

print(myfunc1())

pass
用作未来代码的占位符。执行 pass 语句时不会发生任何操作,但可以避免在空代码块不允许的地方(如循环、函数定义、类定义或 if 语句中)出现错误。

for x in [0, 1, 2]:
    pass

导入模块

import
用于导入模块。

import datetime

from
用于从模块中导入指定的部分。

from datetime import time

运算符与值

in

  1. 用于检查值是否存在于序列(列表、范围、字符串等)中。
  2. 用于在 for 循环中遍历序列。

    fruits = ["apple", "banana", "cherry"]
    
    if "banana" in fruits:
     print("yes")
    
    for x in fruits:
     print(x)

is
用于测试两个变量是否引用同一个对象。

a = ["apple", "banana", "cherry"]
b = ["apple", "banana", "cherry"]
c = a

print(a is b)  # False
print(a is c)  # True

True
布尔值,等同于 1。

False
布尔值,等同于 0。

None
用于定义空值或无值。None 不同于 0、False 或空字符串。None 是其自己的数据类型(NoneType),只有 None 可以是 None

x = None

if x:
    print("Do you think None is True")
else:
    print("None is not True...")   # 打印此语句

学习愉快!

参考:W3 Schools

说明:本文基于常见的 Python 3 版本整理(关键字数量约为 35 个)。不同 Python 版本(如 3.10+ 引入 match/case)的关键字列表可能略有差异,请以实际运行环境为准。