
3.1 标识符与保留字

所谓标识符,可以理解为C、C++、Java、C#等语言中的变量。Python中标识符的命名规则主要有以下三点要求:
◆ 第一个字符必须是字母表中的字母或下画线“_”(在Python 3.X中也可使用非ASCII字母标识符)。
◆ 标识符的其他部分由字母、数字和下画线组成。
◆ 标识符对大小写敏感。
以下变量命名与赋值在Python 3.X中都是合法的:

使用print函数输出上述变量的结果如图3-1所示。

图3-1 Python中的标识符命名
如果在执行print函数输出的时候,错将上述变量a、b、_boolVar变成大写,那么将得到类似以下的错误:

通常,Python语言有以下命名惯例:
◆ 以单一下画线开头的变量名“_X”不会被“from module import*”语句导入。
◆ 前后有下画线的变量名“_X_”是系统定义的变量名,对解释器有特殊意义。
◆ 以双下画线开头,但结尾没有双下画线的变量名“__X”是类的本地(压缩)变量。
◆ 通过交互模式运行时,只有单个下画线的变量名“_X”会保存最后表达式的结果。
与C、C++、Java、C#等语言不同,Python没有定义常量的关键字,意即Python中没有常量的概念。为了实现与其他语言中功能相近的常量,可以使用Python面向对象的方法编写一个“常量”模块。(这里读者可以先参照完成,类与面向对象相关知识详见本书第8章)
将以下代码保存为test-const.py:

上述代码的运行结果如图3-2所示。

图3-2 使用面向对象的方法定义Python“常量”
可以看到,第一次为CONSTANT.TEST赋值后能够成功执行,当尝试为CONSTANT.TEST重新赋值时将会出现错误提示,这相当于起到了常量的作用。
保留字即其他语言中的关键字,是指在语言本身的编译器中已经定义过的单词,具有特定含义和用途,用户不能再将这些单词作为变量名或函数名、类名使用。Python 3.7.2中的保留字主要有False、None等35个。
温馨提示:Python 3.7.2中的35个保留字
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.
Python 2.X中的exec和print等保留字在3.X中已经改为内置函数。
Python 3.7.2中35个保留字的含义及作用如表3-1所示。
表3-1 Python 3.7.2中35个保留字的含义及作用

在Python环境下可以执行以下命令查看当前版本的保留字:


上述代码的运行结果如图3-3所示。

图3-3 查看当前版本Python环境的保留字
若将保留字作为标识符并赋值将会得到语法错误,如图3-4所示。

图3-4 错误使用保留字将引发语法错误