Python3 基础语法

编码声明、标识符规则、保留关键字、缩进与多行语句、字符串与 import 写法。

Beginner
Key PointsPython 3 源码默认 UTF-8;缩进就是语法,同一块必须一致;标识符区分大小写,关键字不能用作名字。

编码

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.

Python
s = "中文可以直接写"
print(s)
print(len(s))
print(s.encode('utf-8')[:6])
print(s.encode('utf-8').decode('utf-8') == s)
Output
中文可以直接写
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.

Python
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__)
Output
False
True
raised: SyntaxError

Python 保留关键字

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.

Python
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])
Output
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.

Python
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__)
Output
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.

Python
total = 1 + \
        2 + \
        3
print(total)

total2 = (1 +
          2 +
          3)
print(total2)

items = [
    'a',
    'b',
]
print(items)
Output
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.

Python
print('single', "double")
print("""line1
line2""")
print(r"C:\new\table")
print("py" "thon")
print('it\'s ok')
Output
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.

Python
a = 1; b = 2; print(a + b)

import sys; print(sys.version_info.major)

if a < b: print("a < b"); print("still same line")
Output
3
3
a < b
still same line

import 与 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.

Python
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)
Output
3
3.0
3.14
True

Friends & Partners