Python基础11 循环语句

一、while循环

while语句非常灵活,可用于在条件为真时反复执行代码块。

x = 1
while x <= 100:
    print(x)
    x += 1

二、for循环

为序列(或其他可迭代对象)中每个元素执行代码块。

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)

Python提供了一个创建范围的内置函数。

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

范围类似于切片,包含起始位置(默认为0),但不包含结束位置。

for number in range(1, 101):
    print(number)

只要能够使用for循环,就不要使用while循环。

三、迭代字典

参考:Python基础08 字典

四、迭代工具

1、并行迭代

同时迭代两个或多个序列。

一个很有用的并行迭代工具是内置函数zip,它将两个序列"缝合"起来,并返回一个由元组组成的序列。

>>> names = ['Mike', 'John', 'Rose']
>>> ages = [40, 30, 20]
>>> list(zip(names, ages))
[('Mike', 40), ('John', 30), ('Rose', 20)]

"缝合后",可在循环中将序列解包:

for name, age in zip(names, ages):
    print(name, 'is', age, 'years old')

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

>>> list(zip(range(5), range(100)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

2、迭代时获取索引

在有些情况下,你需要在迭代序列的同时获取当前对象的索引。

这里介绍一种比较简洁的操作,使用内置函数enumerate。

names = ['Mike', 'John', 'Rose']
for index, name in enumerate(names):
    print(index, name)

0 Mike
1 John
2 Rose

3、反向迭代和排序后再迭代

函数sorted返回排序后的序列。

函数reversed返回反转后的序列,如果调用列表的方法需要先使用list对返回的对象进行转换。

>>> lst = [4, 3, 6, 1, 5, 2]
>>> sorted(lst)
[1, 2, 3, 4, 5, 6]
>>> list(reversed(lst))
[2, 5, 1, 6, 3, 4]

五、跳出循环

1、break

要结束(跳出)循环,可使用break。

num = 10
for n in range(100):
    if n == num:
        print('match')
        break

print('finished')

2、continue

语句continue结束当前迭代,并调到下一次迭代开头。这意味着跳过循环体中余下的语句,但不结束循环。

lst = [-4, 3, 6, 0, 5, -2]
lst2 = []
for n in lst:
    if n < 0:
        continue
    if n == 0:
        continue

    lst2.append(n)
    print(n)

3
6
5

六、循环中的else字句

通常用在判断循环是否正常结束。

lst = [-4, 3, 6, 0, 5, -2]
num = 10

broken_out = False
for n in lst:
    print('matching...')

    if n == num:
        print('match success')
        broken_out = True
        break

if not broken_out:
    print('match failed')

一种更简单的办法是在循环中添加一条else字句。它仅在没有调用break时才执行。

lst = [-4, 3, 6, 0, 5, -2]
num = 10

for n in lst:
    print('matching...')

    if n == num:
        print('match success')
        break
else:
    print('match failed')

猜你喜欢

转载自www.cnblogs.com/mazhiyong/p/12462383.html