# 打印多个参数
>>> print('Age',42)
'Age: 42'
# 自定义分隔符(默认是空格)
>>> print('I', 'have', 'a', 'pen', sep='_')
'I_have_a_pen'
# 自定义结束字符串,以替换默认的换行符
print('Hello,',end='')
print('world!')
# Hello, world!
import
# 模块导入的几种方式
import somemodule
from somemodule import somefunction
from somemodule import somefunction,anotherfunction
from somemodule import *
# 导入时重命名(在语句末尾添加as子句并指定别名。)
import math as foobar
foobar.sqrt(4) # 2.0
from math import sqrt as foobar
foobar(4) # 2.0
赋值
序列解包(可迭代对象解包)
x,y,z = 1,2,3
print(x,y,z) # 1 2 3
#交换多个变量的值
x, y = y, x
print(x, y, z) # 2 1 3
values = 1,2,3
x,y,z = values
print(x) # 1
# 在使用返回元组(或其他序列或可迭代对象)的函数或方法时很有用。
scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}
key, value = scoundrel.popitem()
print(key) # 'girlfriend'
print(value) # 'Marion'
# 可使用星号运算符(*)来收集多余的值,这样无需确保值和变量的个数相同
a, b, *rest = [1,2,3,4]
print(rest) # [3,4]
# 还可将带星号的变量放在其他位置
name = 'Albus Percival Wulfric Brian Dumbledore'
frist, *middle, last = name.split()
print(middle) # ['Percival','Wulfric','Brian']
# 带星号的变量最终包含的总是一个列表,在变量和值的个数相同时也是如此。
a, *b, c = 'abc'
print(a, b, c) # 'a' ['b'] 'c'
链式赋值
用于将多个变量关联到同一个值。
x = y = somefunction()
增强赋值
# 适用于所有标准运算符,如*、/、%等
x = 2
x += 1
x *= 2
print(x) # 6
fnord = 'foo'
fnord += 'bar'
fnord *= 2
print(fnord) # 'foobarfoobar'
代码块:缩进
代码块是通过缩进代码(更佳:每级缩进4空格)来创建的。同一个代码块中,各行代码的缩进量必须相同。
在Python中,使用冒号(:)指出接下来是一个代码块,并将该代码中的每行代码都缩进相同的程度。
条件和条件语句
用作布尔表达式(如用作if语句中的条件)时,下面的值都将被解释器视为假:
False
None
0
""
()
[]
{}
布尔值True和False属于类型bool,而bool与list、str和tuple一样,可用来转换其他的值。
bool('I have a pen') # True
bool(42) # True
bool('') # False
bool(0) # False
注意 虽然[]和””都为假(即
bool([]) == bool("") == False
),但它们并不相等(即[] != ""
)。 对其他各种为假的对象来说,情况亦如此(一个更显而易见的例子是() != False)。
if…elif…else…
name = input('What is your name')
if name.endswith('Gumby'):
print('Hello, Mr. Gumby')
elif name.endswith('Brian'):
print('Hello, Mr. Brian')
else:
print('Hello, stranger')
# 如果条件(紧跟在if后面)为真,表达式的结果为提供的第一个值(这里为'friend')
# 否则为第二个值(这里为'stranger')。
status = 'friend' if name.endswith('Gumby') else 'stranger'
# 将if语句放在其他if语句块中
name = input('What is your name? ')
if name.endswith('Gumby'):
if name.startswith('Mr.'):
print('Hello, Mr. Gumby')
elif name.startswith('Mrs.'):
print('Hello, Mrs. Gumby')
else:
print('Hello, Gumby')
else:
print('Hello, stranger')
比较运算符
名称 | 表达式 | 描述 |
---|---|---|
相等运算符 | x == y |
x 等于y |
x < y``x > y |
x小于y,x大于y | |
x >= y``x <= y |
x小于等于y,x大于等于y | |
x != y |
x不等于y | |
is:相同运算符 | x is y |
x和y是同一个对象 |
x is not y |
x和y是不同的对象 | |
in:成员资格运算符 | x in y |
x是容器(如序列)y的成员 |
x not in y |
x不是容器(如序列)y的成员 |
布尔运算符
and
、or
、not
断言
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
# 如果知道必须满足特定条件,程序才能正确运行,可在程序中添加assert语句充当检查点
>>> age = -1
>>> assert 0 < age < 100, 'The age must be realistic'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: The age must be realistic
循环
while 循环
x = 1
while x <= 100:
print(x)
x += 1
for 循环
words = ['this','is','an','ex','parrot']
for word in words:
print(word)
提示:只要能够使用for循环,就不要使用while循环。(书上说得,为什么呢?)
迭代字典
# 遍历字典的所有关键字
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, d[key])
# for循环的优点之一是,可在其中使用序列解包
for key, value in d.items():
print(key, value)
并行迭代
# 有时候可能需要同时迭代两个序列
names = ['anne', 'beth', 'george', 'damon']
ages = [12,45,32,102]
# 如果要打印名字和对应年龄,可以像下面这么做:
for i in range(len(names)):
print(names[i], 'is', ages[i], 'years old')
一个很有用的并行迭代工具是内置函数zip,将两个序列“缝合”起来,并返回一个由元组组成的序列。返回值是一个适合迭代的对象,要查看其内容,可使用list将其转换成列表。
当序列长度不同时,函数zip将在最短的序列用完后停止“缝合”。
>>> list(zip(names, ages))
[('anne', 12),('beth',45),('george',32),('damon',102)]
for name, age in zip(names,ages):
print(name, 'is', age, 'years old')
迭代时获取索引
# 使用内置函数 enumerate,能够迭代索引-值对。
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censired]'
反向迭代和排序后再迭代
reversed
和sorted
,类似于列表方法reverse
和sort
,但可用于任何序列和可迭代对象,且不就地修改对象,而是返回反转和排序后的版本。
>>> sorted([4,3,6,8,3])
[3,3,4,6,8]
>>> ''.join(reversed('Hello, world!'))
'!dlrow, olleH'
sorted返回一个列表,而reversed像zip那样返回一个更神秘的可迭代对象。
跳出循环
break
结束(跳出)循环。
from math import sqrt
for n in range(99,0,-1):
root = sqrt(n)
if root == int(root):
print(n)
break
continue
结束当前迭代,并跳到下一次迭代开头。
for x in seq:
if condition1: continue
while True/break 成例
while True:
word = input('Please enter a word: ')
if not word: break
print('The word was ', word)
循环中的else子句
# 在循环中添加一条else子句,它仅在没有调用break时才执行
from math import sqrt
for n in range(99, 81, -1):
root = sqrt(n)
if root == int(root):
print(n)
break
else:
print("Didn't find it!")
列表推导
从其他列表创建列表的方式。有点类似于for循环。
>>> [x * x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 只想打印那些能被3整除的平方值
>>> [x*x for x in range(10) if x%3 == 0]
[0, 9, 36, 81]
# 添加更多的for部分
>>> [(x,y) for x in range(2) for y in range(2)]
[(0,0), (0,1),(1,0),(1,1)]
使用圆括号代替方括号并不能实现元组推导,而是将创建生成器。 但可使用花括号来执行字典推导。
>>> squares = {i: "{} squared is{}".format(i, i**2) for i in range(10)}
>>> squares[8]
'8 squares is 64'
pass、 del 和 exec
pass:可将其用作占位符。 del:删除名称以及对象引用(不能用于删除值)。
exec
将字符串作为代码执行。
>>> exec("print('Hello world!')")
Hello,world
# 添加第二个参数——字典,用作代码字符串的命名空间——用于放置变量的地方。
# 否则代码将污染你的命名空间,即修改你的变量。
>>> from math import sqrt
>>> scope = {}
>>> exec('sqrt = 1', scope)
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
# 可在使用这个命名空间前在其中添加一些值
>>> scope = {}
>>> scope['x'] = 2
>>> scope['y'] = 3
>>> eval('x * y', scope)
6
实际上,可向exec提供两个命名空间:一个全局的和一个局部的。提供的全局命名空间必须是字典,而提供的局 部命名空间可以是任何映射。这一点也适用于eval。
eval
类似于exec的内置函数。eval计算用字符串表示的Python表达式的值,并返回结果(exec什么都不返回,因为它本身是条语句)。
>>> eval(input('Enter an arithmetic expression: '))
Enter an arithmetic expression: 6 + 18 * 2
42
与exec一样,也可向eval提供一个命名空间,虽然表达式通常不会像语句那样给变量重新 赋值。