命名规则:
- 可以由字母、数字、下画线(_)组成,其中数字不能打头。
- 不能是 Python 关键字,但可以包含关键字。
- 不能包含空格。
-
Python3 可以给变量命名中文名
-
因为Pyhton3 源码文件默认使用utf-8编码(支持中文)
例如下面变量,有些是合法的,有些是不合法的:
- abc_xyz:合法。
- HelloWorld:合法。
- abc:合法。
- xyz#abc:不合法,标识符中不允许出现“#”号。
- abc1:合法。
- 1abc:不合法,标识符不允许数字开头。
Python 的关键字和内置函数
Python 还包含一系列关键字和内置函数,一般也不建议使用它们作为变量名:
- 如果使用关键字作为变量名,Python 解释器会报错。
- 如果使用内置函数的名字作为变量名,Python 解释器倒不会报错,只是该内置函数就被这个变量覆盖了,该内置函数就不能使用了。
Python 包含的关键字:
False | None | True | and | as |
assert | 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 |
内置函数名:
abs() | all() | any() | basestring() | bin() |
bool() | bytearray() | callable() | chr() | classmethod() |
cmp() | compile() | complex() | delattr() | dict() |
dir() | divmod() | enumerate() | eval() | execfile() |
file() | filter() | float() | format() | frozenset() |
getattr() | globals() | hasattr() | hash() | help() |
hex() | id() | input() | int() | isinstance() |
issubclass() | iter() | len() | list() | locals() |
long() | map() | max() | memoryview() | min() |
next() | object() | oct() | open() | ord() |
pow() | print() | property() | range() | raw_input() |
reduce() | reload() | repr() | reversed() | zip() |
round() | set() | setattr() | slice() | sorted() |
staticmethod() | str() | sum() | super() | tuple() |
type() | unichr() | unicode() | vars() | xrange() |
Zip() | __import__() | apply() | buffer() | coerce() |
intern |
上面这些内置函数的名字也不应该作为标识符,否则 Python 的内置函数会被覆盖。