Python3 基础语法
编码声明、标识符规则、保留关键字、缩进与多行语句、字符串与 import 写法。
编码
Python 3 decodes source files as UTF-8 by default, so Chinese text needs no declaration. Only if the file really uses another encoding do you add # -*- coding: gbk -*- on line one.
s = "中文可以直接写"
print(s)
print(len(s))
print(s.encode('utf-8')[:6])
print(s.encode('utf-8').decode('utf-8') == s)中文可以直接写
7
b'\xe4\xb8\xad\xe6\x96\x87'
True标识符
Identifiers name variables, functions and classes: first character a letter or underscore, the rest may include digits, case-sensitive, and never a keyword. Convention: snake_case for variables and functions, PascalCase for classes.
name = "ok"
_name = "ok"
name2 = "ok"
Name = "different"
print(name == Name)
print(name is _name)
try:
exec('2bad = 1')
except SyntaxError as e:
print("raised:", type(e).__name__)False
True
raised: SyntaxErrorPython 保留关键字
Keywords are part of the grammar and cannot be identifiers. keyword.kwlist lists them for the running version; the count differs between releases, so do not hard-code it.
import keyword
print(len(keyword.kwlist) > 30)
print('if' in keyword.kwlist, 'print' in keyword.kwlist)
print(keyword.iskeyword('class'), keyword.iskeyword('Class'))
print(sorted(keyword.kwlist)[:5])True
True False
True False
['False', 'None', 'True', 'and', 'as']行与缩进
Python marks blocks with indentation instead of braces. Indentation must be consistent within a block (4 spaces recommended); mixing tabs and spaces raises IndentationError.
if True:
print("in block")
if 1 < 2:
print("nested block")
print("out of block")
try:
exec("if True:\nprint('bad')")
except IndentationError as e:
print("IndentationError:", type(e).__name__)in block
nested block
out of block
IndentationError: IndentationError多行语句
Continue a long line with a backslash, but prefer wrapping in parentheses, brackets or braces — a line break inside them continues automatically without any backslash.
total = 1 + \
2 + \
3
print(total)
total2 = (1 +
2 +
3)
print(total2)
items = [
'a',
'b',
]
print(items)6
6
['a', 'b']字符串
Single and double quotes are equivalent; triple quotes span lines. A leading r makes a raw string where backslashes are literal — essential for regex and Windows paths. Adjacent literals concatenate.
print('single', "double")
print("""line1
line2""")
print(r"C:\new\table")
print("py" "thon")
print('it\'s ok')single double
line1
line2
C:\new\table
python
it's ok同一行显示多条语句
Semicolons separate several simple statements on one line. It is legal but hurts readability — avoid it outside quick interactive checks.
a = 1; b = 2; print(a + b)
import sys; print(sys.version_info.major)
if a < b: print("a < b"); print("still same line")3
3
a < b
still same lineimport 与 from...import
import module loads the whole module, from module import name pulls in a single name, and as renames it. Imports conventionally sit at the top of the file.
import math
from math import sqrt
from math import pi as PI
print(math.floor(3.7))
print(sqrt(9))
print(round(PI, 2))
print(math is not None)3
3.0
3.14
True编码
Python 3 的源文件默认按 UTF-8 解码,所以直接写中文不需要声明。若文件确实是别的编码,才需要在第一行写 # -*- coding: gbk -*-。
s = "中文可以直接写"
print(s)
print(len(s))
print(s.encode('utf-8')[:6])
print(s.encode('utf-8').decode('utf-8') == s)中文可以直接写
7
b'\xe4\xb8\xad\xe6\x96\x87'
True标识符
标识符用来命名变量、函数、类。规则:首字符是字母或下划线,其余可含数字;区分大小写;不能用关键字。惯例上变量和函数用 snake_case,类用 PascalCase。
name = "ok"
_name = "ok"
name2 = "ok"
Name = "different"
print(name == Name)
print(name is _name)
try:
exec('2bad = 1')
except SyntaxError as e:
print("raised:", type(e).__name__)False
True
raised: SyntaxErrorPython 保留关键字
关键字是语法的一部分,不能当标识符用。用 keyword.kwlist 可以列出当前版本的全部关键字 —— 不同版本数量不同,代码里不要硬编码数量。
import keyword
print(len(keyword.kwlist) > 30)
print('if' in keyword.kwlist, 'print' in keyword.kwlist)
print(keyword.iskeyword('class'), keyword.iskeyword('Class'))
print(sorted(keyword.kwlist)[:5])True
True False
True False
['False', 'None', 'True', 'and', 'as']行与缩进
Python 用缩进表示代码块,不用大括号。同一代码块内缩进必须一致(推荐 4 个空格),混用 Tab 和空格会直接报 IndentationError。
if True:
print("in block")
if 1 < 2:
print("nested block")
print("out of block")
try:
exec("if True:\nprint('bad')")
except IndentationError as e:
print("IndentationError:", type(e).__name__)in block
nested block
out of block
IndentationError: IndentationError多行语句
一行写不完可以用反斜杠 \ 续行,但更推荐用圆括号、方括号、花括号包起来 —— 括号内的换行是自动续行的,不需要反斜杠。
total = 1 + \
2 + \
3
print(total)
total2 = (1 +
2 +
3)
print(total2)
items = [
'a',
'b',
]
print(items)6
6
['a', 'b']字符串
单引号、双引号等价;三引号可以跨行。r'' 是原始字符串,反斜杠不转义,写正则和 Windows 路径时特别有用。相邻字面量会自动拼接。
print('single', "double")
print("""line1
line2""")
print(r"C:\new\table")
print("py" "thon")
print('it\'s ok')single double
line1
line2
C:\new\table
python
it's ok同一行显示多条语句
用分号可以把多条简单语句写在一行。语法上允许,但可读性差,除了交互式调试外不建议这么写。
a = 1; b = 2; print(a + b)
import sys; print(sys.version_info.major)
if a < b: print("a < b"); print("still same line")3
3
a < b
still same lineimport 与 from...import
import 模块 导入整个模块,from 模块 import 名字 只导入指定名字,from 模块 import 名字 as 别名 顺便改名。导入语句习惯放在文件顶部。
import math
from math import sqrt
from math import pi as PI
print(math.floor(3.7))
print(sqrt(9))
print(round(PI, 2))
print(math is not None)3
3.0
3.14
True