
2.2 保留字与标识符
视频讲解:资源包\Video\02\2.2 保留字与标识符.mp4


2.2.1 保留字
保留字是Python语言中一些已经被赋予特定意义的单词。在开发程序时,不可以把这些保留字作为变量、函数、类、模块和其他对象的名称来使用。Python语言中的保留字如表2.1所示。
表2.1 Python语言中的保留字

注意
在Python中,所有保留字都是区分字母大小写的。例如,if是保留字,但是IF就不属于保留字。如图2.14所示。

图2.14 Python中的保留字区分字母大小写
多学两招
可以在IDLE中输入以下两行代码查看Python中的保留字。

执行结果如图2.15所示。

图2.15 查看Python中的保留字
常见错误
如果在开发程序时,使用Python中的保留字作为模块、类、函数或者变量等的名称,则会提示“invalid syntax”错误信息。下面的代码使用了Python保留字if作为变量的名称:

执行以上程序时,就会出现如图2.16所示错误提示信息。

图2.16 使用Python保留字作为变量名时的错误信息
2.2.2 标识符
标识符可以简单地理解为一个名字,比如每个人都有自己的名字,它主要用来标识变量、函数、类、模块和其他对象的名称。
Python语言标识符命名规则如下:
☑ 由字母、下画线“_”和数字组成。第一个字符不能是数字。
☑ 不能使用Python中的保留字。
例如,下面是合法的标识符:

下面是非法的标识符:

注意
Python的标识符中不能包含空格、@、%和$等特殊字符。
☑ 区分字母大小写。
在Python中,标识符中的字母是严格区分大小写的,两个同样的单词,如果大小写格式不一样,所代表的意义是完全不同的。例如,下面3个变量是完全独立、毫无关系的,就像相貌相似的三胞胎,彼此之间都是独立的个体。

☑ Python中以下画线开头的标识符有特殊意义,一般应避免使用相似的标识符。
➢ 以双下画线开头的标识符(如__add)表示类的私有成员。
➢ 以双下画线开头和结尾的是Python里专用的标识,如__init__( )表示构造函数。
说明
在Python语言中允许使用汉字作为标识符,如“我的名字="明日科技"”,在程序运行时并不会出现错误(如图2.17所示),但是尽量不要使用汉字作为标识符。

图2.17 使用汉字作为标识符