python查询代码可循环执行_Python基础11 循环语句

一、while循环

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

x = 1

while x <= 100:print(x)

x+= 1

二、for循环

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

numbers = [1, 2, 3, 4, 5]for number innumbers: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循环。

三、迭代字典

四、迭代工具

1、并行迭代

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

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

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

[('Mike', 40), ('John', 30), ('Rose', 20)]

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

for name, age inzip(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 inenumerate(names):print(index, name)

0 Mike1John2 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 inlst:if n <0:continue

if n ==0:continuelst2.append(n)print(n)

3

6

5

六、循环中的else字句

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

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

num= 10broken_out=Falsefor n inlst:print('matching...')if n ==num:print('match success')

broken_out=Truebreak

if notbroken_out:print('match failed')

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

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

num= 10

for n inlst:print('matching...')if n ==num:print('match success')break

else:print('match failed')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值