语句简介
- 所有的python复合语句都有相同的一般形式,也就是首行以冒号结尾,首行下一行嵌套的代码统一缩进,并且类似if的判断条件的括号是可选的,行终止不需要以封号结尾,缩进的结束就是代码块的结束。python唯一需要用封号的时候是希望一行放多个语句,此时用封号充当分隔符。利用()、[]、{}可以让一个语句跨越多行。简单的单行语句可以直接跟在复合语句的冒号后面。
赋值、表达式和打印
>>> v = v1 = []
>>> v.append(1)
>>> v, v1
([1], [1])
运算 |
解释 |
结果 |
v = 1 |
基本形式 |
v = 1 |
v, v1 = 1, 2 |
元组赋值运算 |
v = 1, v1 = 2 |
[v, v1] = [1, 2] |
列表赋值运算 |
v = 1, v1 = 2 |
v, v1 = '12' |
序列赋值运算 |
v = '1', v1 = '2' |
v, *v1 = 'abcd' |
扩展的序列解包 |
v = 'a', v1 = ['b', 'c', 'd'] |
v = v1 = 1 |
多目标赋值运算 |
v = 1, v1 = 1 |
v = 1 v += 1
|
增强赋值运算 |
v = 2 |
>>> v, *v1 = 'a'
>>> v, v1
('a', [])
>>> v, *v1 = 'ab'
>>> v, v1
('a', ['b']) #扩展的序列解包结果总是一个列表
>>> v = 1; v1 = 2
>>> v, v1 = v1, v #右侧的组会自动记住原来的值
>>> v, v1
(2, 1)
>>> (v, v1), v2 = [(1, 2), 3]
>>> v, v1, v2
(1, 2, 3)
>>> v, *v1, v2 = "Hello Python"
>>> v, v1, v2
('H', ['e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o'], 'n')
>>> v = [1, 2, 3]
>>> while v:
f, v = v[0], v[1:]
print(f, ',', v)
1 , [2, 3]
2 , [3]
3 , []
>>> v = [1, 2, 3]
>>> while v:
f, *v = v
print(f, ',', v)
1 , [2, 3]
2 , [3]
3 , []
>>> v = []
>>> v1 = v
>>> v += [1]
>>> v, v1
([1], [1])
>>> v = []
>>> v1 = v
>>> v = v + [1]
>>> v, v1
([1], [])
False |
class |
finally |
is |
return |
None |
continue |
for |
lambda |
try |
True |
def |
from |
nonlocal |
while |
and |
del |
global |
not |
with |
as |
elif |
if |
or |
yield |
assert |
else |
import |
pass |
|
break |
except |
in |
raise |
|
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
if测试和语法规则
- if后面跟着一个或多个可选的elif,以及一个最终的else块
>>> if True:
pass
elif True:
pass
else:
pass
- 任何非零或非空对象都为真
数字零、空对象以及None为假
比较和相等测试会递归的应用在数据结构中
比较和相等测试会返回True或False
and和or会返回真或假的操作对象
#python实现类似三目运算还有以下无聊、烂的破语法
>>> [1, 2][bool(True)]
2
>>> [1, 2][bool(False)]
1
while和for循环
>>> v = [1, 2]
>>> while v:
f, *v = v
print(f, v)
else:
print('done') #只有当循环正常离开时才会执行(没遇到break)
1 [2]
2 []
done
- 三个连续点号可以当做pass的替代方案:
if True:...
>>> v = ...
>>> if v:
print('Hello')
Hello
>>> while v = 1:
SyntaxError: invalid syntax
>>> v = [1, 2]
>>> for x in v:
print(x)
else:
print('没遇见break')#只有当循环正常离开时才会执行(没遇到break)
1
2
没遇见break
- 显然任何序列都支持for循环。for循环甚至还可以用于文件和字典
>>> v = {'a' : 1, 'b' : 2}
>>> for k in v:
print(v[k])
2
1
>>> fp = open(r'D:\1.txt', 'w')
>>> fp.write('abc')
3
>>> fp.close()
>>> fp = open(r'D:\1.txt')
>>> for x in fp:
print(x)
abc
>>> list(range(0, 5))
[0, 1, 2, 3, 4]
>>> list(range(3, 10, 2))
[3, 5, 7, 9]
>>> list(range(5, -5, -1))
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
- zip会取得一个或多个序列,然后返回元组的列表,并将这些序列的并排的元素配成对,且会以最短序列长度做截断
>>> list(zip('szn', '1234'))
[('s', '1'), ('z', '2'), ('n', '3')]
>>> list(zip('ABC', '1234', ('a', 'b', 'c')))
[('A', '1', 'a'), ('B', '2', 'b'), ('C', '3', 'c')]
>>> v = {}
>>> v0 = ['a', 'b']
>>> v1 = "szn"
>>> for x, y in zip(v0, v1):v[x] = y
>>> v
{'b': 'z', 'a': 's'}
- enumerate返回一个生成器对象,每次迭代返回(index, value)的元组
>>> v = enumerate('szn')
>>> next(v)
(0, 's')
>>> next(v)
(1, 'z')
>>> next(v)
(2, 'n')
>>> next(v)
Traceback (most recent call last):
File "<pyshell#522>", line 1, in <module>
next(v)
StopIteration
>>> for x, y in enumerate('szn'):
print(x, y)
0 s
1 z
2 n
迭代和解析第一部分
- 有
__next__
方法的对象会前进到下一个结果,而在一系列的末尾时,会引发StopIteration
异常
- python3.0提供了next内置函数,他会自动调用对象的
__next__
方法
- 对于文件来说,文件对象就是自己的迭代器,每次迭代返回一行。列表以及很多内置对象不是本身的迭代器,因为他们支持多次打开迭代器,对于这样的对象,必须调用iter来启动迭代
- 字典的迭代器会自动返回下一个键
>>> v = "szn"
>>> it = iter(v)
>>> while True: #手动迭代
try:
print(it.__next__())
except StopIteration:
print('done')
break
s
z
n
done
>>> v = "szn"
>>> for x in v: #自动迭代
print(x)
s
z
n
>>> fp = open(r'D:\1.txt', 'rb')
>>> str = fp.read()
>>> str
b'abc\r\n123'
>>> fp = open(r'D:\1.txt')
>>> for line in fp: #利用for每次自动调用__next__进行迭代
print(line, end = '')
abc
123
>>> d = {'a' : 'b', 1 : 2}
>>> for k in d:
print(k, d[k])
1 2
a b
文档
- python支持自动附加在对象上的文档,而且在运行时还可以保存查看。从语法上来看,这类注释是写成字符串,放在模块文件、函数以及类语句的顶端,就在任何可执行程序代码前(#注释在其之前也可以)。python会自动封装这个字符串,也就是所谓的文档字符串,使其成为对象的
__doc__
属性
>>> def Fun():
'''
Print Hello World
'''
print('Hello World')
>>> Fun.__doc__
'\n\tPrint Hello World\n\t'
>>> class CTest:
'CTest'
pass
>>> CTest.__doc__
'CTest'
>>> import sys
>>> sys.path.append(r'D:')
>>> import Test
Hello
>>> Test.__doc__
'1.py'
>>> fp = open(r'D:\Test.py', 'rb')
>>> for line in fp:
print(line)
b"'1.py'\r\n"
b'\r\n'
b"print('Hello')"