Python3 保留字/关键字

前言

python中的保留字可以使用keyword模块进行查询和验证。

Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import keyword
>>> keyword.kwlist
['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还提供了iskeyword方法来判断变量名是否是关键字。

>>> keyword.iskeyword('pass')
True
>>> keyword.iskeyword('my_pass')
False
>>>

分析

关键字 用途/解释 举例
False

Bool类型,在python中,bool是int的子类(继承int),故 True==1  False==0 是会返回Ture的。

True or False 判定

  以下会被判定为 False :

  • None
  • False
  • zero of any numeric type, for example, 0, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.
 参考链接 
True
None  表示值是一个空对象  
>>>type(None)
<class 'NoneType'>
and

Python逻辑运算符,布尔“与”--连接俩个表达式,如果前表达式为False,返回前表达式的值,否则返回后表达式的值

 
>>> 0 and 1
0
or  Python逻辑运算符,布尔“或”--连接俩个表达式,如果前表达式为True,返回前表达式的值,否则返回后表达式的值  
>>> 0 and 1
1
not  Python逻辑运算符,布尔“非”--连接一个表达式,否定,如果表达式为True,返回False。如果表达式为False,返回True  
>>> not 1
False
>>> not 0
True
async   用于异步编程

  详情可阅读

await
break   break意为结束循环;continue为结束当前循环,进入下一个循环   详情可阅读
continue
class  声明类关键字  
class my_test():
    pass
def 定义函数/方法的关键字。  
def my_def():
    pass
del  删除对象的引用  详情请阅读
if   条件控制语句   详情请阅读(Nice)
elif
else
try   异常处理语法   详情请阅读
except
finally
for  循环语法  详情请阅读
while
from   导入模块/从包中导入模块的关键字   详情请阅读
import
global  内部作用域想要对外部作用域的变量进行修改时的关键字  详情请阅读
nonlocal 引用外部环境的局部变量 参考阅读(网上有许多解释,个人感觉这个好点)
in  在……里,可用于循环或判断  详情请阅读
is  判断左右俩端的数据是否是通一个内存地址;常和“==”做比较,“==”判断左右俩端的数据是否一样  详情请阅读
lambda  匿名函数,语法:lambda arg1,arg2... : expression  详情请阅读
assert  断言,语法:assert expression【, arg】  详情请阅读
with 可以认为with是调用上下文管理器的关键字,使用with需实现__enter__和__exit__(以前读过一个关于文章,很好理解,现在已经找不到了)  详情请阅读
with open('test.py') as my_f:
    pass
  
as  给对象起个别名,常用于from XX import XX as XX,with XX as,except XX as XX
pass  空语句,为了保持程序的完整性,不做任何事,一般用在占位符
raise  抛出异常  raise [exceptionName [(reason)]]  想起请阅读
return 返回对象  
yield  带有 yield 的函数在 Python 中被称之为 generator(生成器)  详情请阅读

整理了些内容仅供参考。

posted @ 2021-07-15 13:43  老徐-lex  阅读(510)  评论(0编辑  收藏  举报