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

2023-05-0708:23:24编程语言入门到精通Comments1,213 views字数 1660阅读模式
作者:惰惰猴
Python 基础脚手架:关键字与标识符文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/38676.html

一、Python 关键字

所谓编程语言之关键字,实则就是语言本身定义的字符序列。用以功能实现。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/38676.html

关键字的数量也不是完全固定的,有可能随着语言的发展而增删。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/38676.html

# 使用 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)就是用户编程时,给变量、常量、函数、属性、类、模块、包所起的名字。用以建立名称与程序使用之间的关联。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/38676.html

1、区分大小写

>>> name = 'Python'
>>> Name = 'C' 
>>> NAME = 'Java'
>>> naME = 'C#'
>>> print(name, Name, NAME, naME)
Python C Java C#
>>>

2、不能以数字开头

>>> 123_ = 10
 File "<stdin>", line 1
   123_ = 10
      ^
SyntaxError: invalid decimal literal
>>> 
>>> 我最喜欢的编程语言 = 'Python'
>>> _MyFavoriteProgrammingLanguage = 'python'
>>> _123_Google = 'Google'

3、关键字、运算符不能用于标识符

>>> if = 'IF'
 File "<stdin>", line 1
   if = 'IF'
      ^
SyntaxError: invalid syntax
>>> & = 'hello'
 File "<stdin>", line 1
   & = 'hello'
   ^
SyntaxError: invalid syntax
>>> hello** = 'hello'
 File "<stdin>", line 1
   hello** = 'hello'
           ^
SyntaxError: invalid syntax
>>> hello%hello = 'hello'
 File "<stdin>", 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 "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> 
>>> print = 3
>>> len(print)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> print
3
>>> print('hello')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>

三、后记

任何编程语言所写代码,均由关键字和标识符组成。理清它们的规则和范式,将会让 Coding 过程变得事半功倍。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/38676.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/38676.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/38676.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定