print

  1. # 打印多个参数
  2. >>> print('Age',42)
  3. 'Age: 42'
  4. # 自定义分隔符(默认是空格)
  5. >>> print('I', 'have', 'a', 'pen', sep='_')
  6. 'I_have_a_pen'
  7. # 自定义结束字符串,以替换默认的换行符
  8. print('Hello,',end='')
  9. print('world!')
  10. # Hello, world!

import

  1. # 模块导入的几种方式
  2. import somemodule
  3. from somemodule import somefunction
  4. from somemodule import somefunction,anotherfunction
  5. from somemodule import *
  6. # 导入时重命名(在语句末尾添加as子句并指定别名。)
  7. import math as foobar
  8. foobar.sqrt(4) # 2.0
  9. from math import sqrt as foobar
  10. foobar(4) # 2.0

赋值

序列解包(可迭代对象解包)

  1. x,y,z = 1,2,3
  2. print(x,y,z) # 1 2 3
  3. #交换多个变量的值
  4. x, y = y, x
  5. print(x, y, z) # 2 1 3
  6. values = 1,2,3
  7. x,y,z = values
  8. print(x) # 1
  9. # 在使用返回元组(或其他序列或可迭代对象)的函数或方法时很有用。
  10. scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}
  11. key, value = scoundrel.popitem()
  12. print(key) # 'girlfriend'
  13. print(value) # 'Marion'
  1. # 可使用星号运算符(*)来收集多余的值,这样无需确保值和变量的个数相同
  2. a, b, *rest = [1,2,3,4]
  3. print(rest) # [3,4]
  4. # 还可将带星号的变量放在其他位置
  5. name = 'Albus Percival Wulfric Brian Dumbledore'
  6. frist, *middle, last = name.split()
  7. print(middle) # ['Percival','Wulfric','Brian']
  8. # 带星号的变量最终包含的总是一个列表,在变量和值的个数相同时也是如此。
  9. a, *b, c = 'abc'
  10. print(a, b, c) # 'a' ['b'] 'c'

链式赋值

用于将多个变量关联到同一个值。

  1. x = y = somefunction()

增强赋值

  1. # 适用于所有标准运算符,如*、/、%等
  2. x = 2
  3. x += 1
  4. x *= 2
  5. print(x) # 6
  6. fnord = 'foo'
  7. fnord += 'bar'
  8. fnord *= 2
  9. print(fnord) # 'foobarfoobar'

代码块:缩进

代码块是通过缩进代码(更佳:每级缩进4空格)来创建的。同一个代码块中,各行代码的缩进量必须相同。
在Python中,使用冒号(:)指出接下来是一个代码块,并将该代码中的每行代码都缩进相同的程度。

条件和条件语句

用作布尔表达式(如用作if语句中的条件)时,下面的值都将被解释器视为假: False None 0 "" () [] {}

布尔值True和False属于类型bool,而bool与list、str和tuple一样,可用来转换其他的值。

  1. bool('I have a pen') # True
  2. bool(42) # True
  3. bool('') # False
  4. bool(0) # False

注意 虽然[]和””都为假(即bool([]) == bool("") == False),但它们并不相等(即[] != "")。 对其他各种为假的对象来说,情况亦如此(一个更显而易见的例子是() != False)。

if…elif…else…

  1. name = input('What is your name')
  2. if name.endswith('Gumby'):
  3. print('Hello, Mr. Gumby')
  4. elif name.endswith('Brian'):
  5. print('Hello, Mr. Brian')
  6. else:
  7. print('Hello, stranger')
  1. # 如果条件(紧跟在if后面)为真,表达式的结果为提供的第一个值(这里为'friend')
  2. # 否则为第二个值(这里为'stranger')。
  3. status = 'friend' if name.endswith('Gumby') else 'stranger'
  1. # 将if语句放在其他if语句块中
  2. name = input('What is your name? ')
  3. if name.endswith('Gumby'):
  4. if name.startswith('Mr.'):
  5. print('Hello, Mr. Gumby')
  6. elif name.startswith('Mrs.'):
  7. print('Hello, Mrs. Gumby')
  8. else:
  9. print('Hello, Gumby')
  10. else:
  11. 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的成员

布尔运算符

andornot

断言

  1. >>> age = 10
  2. >>> assert 0 < age < 100
  3. >>> age = -1
  4. >>> assert 0 < age < 100
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in ?
  7. AssertionError
  8. # 如果知道必须满足特定条件,程序才能正确运行,可在程序中添加assert语句充当检查点
  9. >>> age = -1
  10. >>> assert 0 < age < 100, 'The age must be realistic'
  11. Traceback (most recent call last):
  12. File "<stdin>", line 1, in ?
  13. AssertionError: The age must be realistic

循环

while 循环

  1. x = 1
  2. while x <= 100:
  3. print(x)
  4. x += 1

for 循环

  1. words = ['this','is','an','ex','parrot']
  2. for word in words:
  3. print(word)

提示:只要能够使用for循环,就不要使用while循环。(书上说得,为什么呢?)

迭代字典

  1. # 遍历字典的所有关键字
  2. d = {'x': 1, 'y': 2, 'z': 3}
  3. for key in d:
  4. print(key, d[key])
  5. # for循环的优点之一是,可在其中使用序列解包
  6. for key, value in d.items():
  7. print(key, value)

并行迭代

  1. # 有时候可能需要同时迭代两个序列
  2. names = ['anne', 'beth', 'george', 'damon']
  3. ages = [12,45,32,102]
  4. # 如果要打印名字和对应年龄,可以像下面这么做:
  5. for i in range(len(names)):
  6. print(names[i], 'is', ages[i], 'years old')

一个很有用的并行迭代工具是内置函数zip,将两个序列“缝合”起来,并返回一个由元组组成的序列。返回值是一个适合迭代的对象,要查看其内容,可使用list将其转换成列表。

当序列长度不同时,函数zip将在最短的序列用完后停止“缝合”。

  1. >>> list(zip(names, ages))
  2. [('anne', 12),('beth',45),('george',32),('damon',102)]
  3. for name, age in zip(names,ages):
  4. print(name, 'is', age, 'years old')

迭代时获取索引

  1. # 使用内置函数 enumerate,能够迭代索引-值对。
  2. for index, string in enumerate(strings):
  3. if 'xxx' in string:
  4. strings[index] = '[censired]'

反向迭代和排序后再迭代

reversedsorted,类似于列表方法reversesort,但可用于任何序列和可迭代对象,且不就地修改对象,而是返回反转和排序后的版本。

  1. >>> sorted([4,3,6,8,3])
  2. [3,3,4,6,8]
  3. >>> ''.join(reversed('Hello, world!'))
  4. '!dlrow, olleH'

sorted返回一个列表,而reversed像zip那样返回一个更神秘的可迭代对象。

跳出循环

break

结束(跳出)循环。

  1. from math import sqrt
  2. for n in range(99,0,-1):
  3. root = sqrt(n)
  4. if root == int(root):
  5. print(n)
  6. break

continue

结束当前迭代,并跳到下一次迭代开头。

  1. for x in seq:
  2. if condition1: continue

while True/break 成例

  1. while True:
  2. word = input('Please enter a word: ')
  3. if not word: break
  4. print('The word was ', word)

循环中的else子句

  1. # 在循环中添加一条else子句,它仅在没有调用break时才执行
  2. from math import sqrt
  3. for n in range(99, 81, -1):
  4. root = sqrt(n)
  5. if root == int(root):
  6. print(n)
  7. break
  8. else:
  9. print("Didn't find it!")

列表推导

从其他列表创建列表的方式。有点类似于for循环。

  1. >>> [x * x for x in range(10)]
  2. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  3. # 只想打印那些能被3整除的平方值
  4. >>> [x*x for x in range(10) if x%3 == 0]
  5. [0, 9, 36, 81]
  6. # 添加更多的for部分
  7. >>> [(x,y) for x in range(2) for y in range(2)]
  8. [(0,0), (0,1),(1,0),(1,1)]

使用圆括号代替方括号并不能实现元组推导,而是将创建生成器。 但可使用花括号来执行字典推导。

  1. >>> squares = {i: "{} squared is{}".format(i, i**2) for i in range(10)}
  2. >>> squares[8]
  3. '8 squares is 64'

pass、 del 和 exec

pass:可将其用作占位符。 del:删除名称以及对象引用(不能用于删除值)。

exec

将字符串作为代码执行。

  1. >>> exec("print('Hello world!')")
  2. Hello,world
  3. # 添加第二个参数——字典,用作代码字符串的命名空间——用于放置变量的地方。
  4. # 否则代码将污染你的命名空间,即修改你的变量。
  5. >>> from math import sqrt
  6. >>> scope = {}
  7. >>> exec('sqrt = 1', scope)
  8. >>> sqrt(4)
  9. 2.0
  10. >>> scope['sqrt']
  11. 1
  12. # 可在使用这个命名空间前在其中添加一些值
  13. >>> scope = {}
  14. >>> scope['x'] = 2
  15. >>> scope['y'] = 3
  16. >>> eval('x * y', scope)
  17. 6

实际上,可向exec提供两个命名空间:一个全局的和一个局部的。提供的全局命名空间必须是字典,而提供的局 部命名空间可以是任何映射。这一点也适用于eval。

eval

类似于exec的内置函数。eval计算用字符串表示的Python表达式的值,并返回结果(exec什么都不返回,因为它本身是条语句)。

  1. >>> eval(input('Enter an arithmetic expression: '))
  2. Enter an arithmetic expression: 6 + 18 * 2
  3. 42

与exec一样,也可向eval提供一个命名空间,虽然表达式通常不会像语句那样给变量重新 赋值。