什么是标识符

在Python中,标识符用于命名变量、函数、类等对象。标识符有一定的命名规则和约定

Python 标识符的命名规则

  • 只允许出现**英文、中文(不推荐)、数字和下划线 (_)**,不能包含空格和特殊字符(如 @、#、% 等)。
  • 不能以数字开头,可以以字母或下划线开头。例如,_name 或 name1 是有效的标识符,而 1name 是无效的。
  • 区分大小写,如 name 和 Name 是两个不同的标识符。
  • 不能使用 Python 的关键字(如 if、while、class 等)作为标识符。

合理的命名规范
Python 使用 PEP 8 规范来指导代码的风格和命名习惯

  • 变量和函数名:建议使用小写字母和下划线分隔,采用“蛇形命名法”(例如:total_count、calculate_sum)。
  • 类名:建议首字母大写,每个单词首字母大写,采用“驼峰命名法”(例如:Person, EmployeeRecord)。
  • 常量:建议用全大写字母表示,并用下划线分隔(例如:PI, MAX_VALUE)。

示例

1
2
3
4
5
6
7
8
9
10
# 合法的标识符
name = "A"
_age = 25
total_amount = 1000
PI = 3.14

# 不合法的标识符(会导致语法错误)
1st_value = 10 # 不能以数字开头
my-name = "John" # 不能包含特殊字符
class = "Math" # 不能使用 Python 关键字

Python 关键字列表(部分)

False, True, None, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, if, import, in, is, lambda, not, or, pass, return, while, with, yield

不可被作为标识符命名


小练习

提示

  • 可以使用 str.isidentifier() 方法检查字符串是否是合法标识符。
  • 使用 keyword 模块中的 keyword.iskeyword() 检查字符串是否为关键字。
编写一个 Python 程序,提示用户输入一个字符串,检测该字符串是否是一个有效的标识符。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import keyword

def check_identifier(identifier):
if identifier.isidentifier():
if keyword.iskeyword(identifier):
return "非法标识符:这是一个 Python 关键字"
else:
return "合法标识符"
else:
return "非法标识符:不符合标识符命名规则"

# 用户输入
user_input = input("请输入一个标识符:")
print(check_identifier(user_input))