循环¶

循环的作用在于将一段代码重复执行多次。

while 循环¶

  1. while <condition>:
  2. <statesments>

Python会循环执行<statesments>,直到<condition>不满足为止。

例如,计算数字01000000的和:

In [1]:

  1. i = 0
  2. total = 0
  3. while i < 1000000:
  4. total += i
  5. i += 1
  6. print total
  1. 499999500000

之前提到,空容器会被当成 False ,因此可以用 while 循环来读取容器中的所有元素:

In [2]:

  1. plays = set(['Hamlet', 'Macbeth', 'King Lear'])
  2. while plays:
  3. play = plays.pop()
  4. print 'Perform', play
  1. Perform King Lear
  2. Perform Macbeth
  3. Perform Hamlet

循环每次从 plays 中弹出一个元素,一直到 plays 为空为止。

for 循环¶

  1. for <variable> in <sequence>:
  2. <indented block of code>

for 循环会遍历完<sequence>中所有元素为止

上一个例子可以改写成如下形式:

In [3]:

  1. plays = set(['Hamlet', 'Macbeth', 'King Lear'])
  2. for play in plays:
  3. print 'Perform', play
  1. Perform King Lear
  2. Perform Macbeth
  3. Perform Hamlet

使用 for 循环时,注意尽量不要改变 plays 的值,否则可能会产生意想不到的结果。

之前的求和也可以通过 for 循环来实现:

In [4]:

  1. total = 0
  2. for i in range(100000):
  3. total += i
  4. print total
  1. 4999950000

然而这种写法有一个缺点:在循环前,它会生成一个长度为 100000 的临时列表。

生成列表的问题在于,会有一定的时间和内存消耗,当数字从 100000 变得更大时,时间和内存的消耗会更加明显。

为了解决这个问题,我们可以使用 xrange 来代替 range 函数,其效果与range函数相同,但是 xrange 并不会一次性的产生所有的数据:

In [5]:

  1. total = 0
  2. for i in xrange(100000):
  3. total += i
  4. print total
  1. 4999950000

比较一下两者的运行时间:

In [6]:

  1. %timeit for i in xrange(1000000): i = i
  1. 10 loops, best of 3: 40.7 ms per loop

In [7]:

  1. %timeit for i in range(1000000): i = i
  1. 10 loops, best of 3: 96.6 ms per loop

可以看出,xrange 用时要比 range 少。

continue 语句¶

遇到 continue 的时候,程序会返回到循环的最开始重新执行。

例如在循环中忽略一些特定的值:

In [8]:

  1. values = [7, 6, 4, 7, 19, 2, 1]
  2. for i in values:
  3. if i % 2 != 0:
  4. # 忽略奇数
  5. continue
  6. print i/2
  1. 3
  2. 2
  3. 1

break 语句¶

遇到 break 的时候,程序会跳出循环,不管循环条件是不是满足:

In [9]:

  1. command_list = ['start',
  2. 'process',
  3. 'process',
  4. 'process',
  5. 'stop',
  6. 'start',
  7. 'process',
  8. 'stop']
  9. while command_list:
  10. command = command_list.pop(0)
  11. if command == 'stop':
  12. break
  13. print(command)
  1. start
  2. process
  3. process
  4. process

在遇到第一个 'stop' 之后,程序跳出循环。

else语句¶

if 一样, whilefor 循环后面也可以跟着 else 语句,不过要和break一起连用。

  • 当循环正常结束时,循环条件不满足, else 被执行;
  • 当循环被 break 结束时,循环条件仍然满足, else 不执行。
    不执行:

In [10]:

  1. values = [7, 6, 4, 7, 19, 2, 1]
  2. for x in values:
  3. if x <= 10:
  4. print 'Found:', x
  5. break
  6. else:
  7. print 'All values greater than 10'
  1. Found: 7

执行:

In [11]:

  1. values = [11, 12, 13, 100]
  2. for x in values:
  3. if x <= 10:
  4. print 'Found:', x
  5. break
  6. else:
  7. print 'All values greater than 10'
  1. All values greater than 10

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/02-python-essentials/02.15-loops.ipynb