python 3.7极速入门教程5循环

本文教程目录

5循环

语法基础

for语句

Python的for语句针对序列(列表或字符串等)中的子项进行循环,按它们在序列中的顺序来进行迭代。

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

在迭代过程中修改迭代序列不安全,可能导致部分元素重复两次,建议先拷贝:

>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

range()函数

内置函数 range()生成等差数值序列:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(10) 生成了一个包含10个值的链表,但是不包含最右边的值。默认从0开始,也可以让range 从其他值开始,或者指定不同的增量值(甚至是负数,有时也称"步长"):

>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
>>> range(-10, -100, 30)
[]

如果迭代时需要索引和值可结合使用range()和len():

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

不过使用enumerate()更方便,参见后面的介绍。

break和continue语句及循环中的else子句

break语句和C中的类似,用于终止当前的for或while循环。

循环可能有else 子句;它在循环迭代完整个列表(对于 for)后或执行条件为false(对于 while)时执行,但循环break时不会执行。这点和try...else而不是if...else相近。请看查找素数的程序:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

continue语句也是从C而来,它表示退出当次循环,继续执行下次迭代。通常可以用if...else替代,请看查找偶数的实例:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

pass

pass语句什么也不做。它语法上需要,但是实际什么也不做场合,也常用语以后预留以后扩展。例如:

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...
>>> class MyEmptyClass:
...     pass
...
>>> def initlog(*args):
...     pass   # Remember to implement this!
...

循环技巧

在字典中循环时,关键字和对应的值可以使用 items() 方法同时获取:

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

在序列中循环时 enumerate() 函数同时得到索引位置和对应值:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

同时循环两个或更多的序列,可以使用 zip() 打包:

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

需要逆向循环序列的话,调用 reversed() 函数即可:

>>> for i in reversed(xrange(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

使用 sorted() 函数可排序序列,它不改动原序列,而是生成新的已排序的序列:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print f
...
apple
banana
orange
pear

若要在循环时修改迭代的序列,建议先复制。

>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]

循环

image.png

代码:

# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 (可以加钉钉pythontesting邀请加入) 
# qq群:144081101 591302926  567351477
# CreateDate: 2018-6-12 
# bowtie.py
# Draw a bowtie

from turtle import *

def polygon(n, length):
    """Draw n-sided polygon with given side length."""
    for _ in range(n):
        forward(length)
        left(360/n)

def main():
    """Draw polygons with 3-9 sides."""
    for n in range(3, 10):
        polygon(n, 80)
    exitonclick()

main()

参考资料

条件循环while

image.png

代码:

# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 (可以加钉钉pythontesting邀请加入) 
# qq群:144081101 591302926  567351477
# CreateDate: 2018-6-12 
# spiral.py
# Draw spiral shapes

from turtle import *

def spiral(firststep, angle, gap):
    """Move turtle on a spiral path."""
    step = firststep
    while step > 0:
        forward(step)
        left(angle)
        step -= gap

def main():
    spiral(100, 71, 2)
    exitonclick()

main()

参考资料

links