一、Python 关键字
所谓编程语言之关键字,实则就是语言本身定义的字符序列。用以功能实现。
关键字的数量也不是完全固定的,有可能随着语言的发展而增删。
# 使用 keyword 标准库的 kwlist,可以把 Python 所有关键字放入列表
>>> from keyword import kwlist
>>>
>>> python_keywords = kwlist
>>> python_keywords
['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']
>>>
>>> len(python_keywords) # 测量关键字数量
35
>>>
二、Python 标识符规范
在计算机编程语言中,标识符(identifier)就是用户编程时,给变量、常量、函数、属性、类、模块、包所起的名字。用以建立名称与程序使用之间的关联。
1、区分大小写
>>> name = 'Python'
>>> Name = 'C'
>>> NAME = 'Java'
>>> naME = 'C#'
>>> print(name, Name, NAME, naME)
Python C Java C#
>>>
2、不能以数字开头
>>> 123_ = 10
File "", line 1
123_ = 10
^
SyntaxError: invalid decimal literal
>>>
>>> 我最喜欢的编程语言 = 'Python'
>>> _MyFavoriteProgrammingLanguage = 'python'
>>> 我_123_Google = 'Google'
3、关键字、运算符不能用于标识符
>>> if = 'IF'
File "", line 1
if = 'IF'
^
SyntaxError: invalid syntax
>>> & = 'hello'
File "", line 1
& = 'hello'
^
SyntaxError: invalid syntax
>>> hello** = 'hello'
File "", line 1
hello** = 'hello'
^
SyntaxError: invalid syntax
>>> hello%hello = 'hello'
File "", line 1
hello%hello = 'hello'
^^^^^^^^^^^
SyntaxError: cannot assign to expression here. Maybe you meant '=='instead of '='?
>>>
4、标识符不能和 Python 内置函数名冲突
>>> len = 2
>>> len
2
>>> len(len)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'int' object is not callable
>>>
>>> print = 3
>>> len(print)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'int' object is not callable
>>> print
3
>>> print('hello')
Traceback (most recent call last):
File "", line 1, in
TypeError: 'int' object is not callable
>>>
三、后记
任何编程语言所写代码,均由关键字和标识符组成。理清它们的规则和范式,将会让 Coding 过程变得事半功倍。