Python 基础脚手架:关键字与标识符

2023年 7月 11日 79.2k 0

一、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 过程变得事半功倍。

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论