while & for循环

while循环语句

counter =1
while counter <=10:	#打印出1-10的数字
    counter +=1 	#+1
    print(counter)
else:
    print("EOF")	#上面循环结束后打印“EOF”

for循环语句
#主要用来遍历/循环 序列或者集合、字典

#基本用法
a=['apple','orange','banana','grape']
for x in a:
    print(x)
a=[['apple','orange','banana','grape'],(1,2,3)]	#a列表中加一个元组
for x in a:	#x为自定义根据排序区分
    for y in x: 	#y在x列表中
        print(y,end='')	#end='' 横向打印
else:
    print('fruit is gone')	#for语句全部执行结束后执行else语句

跳出循环 break停止循环
⚠️注意:如果使用break强制停止,则不会执行else语句

a = [1,2,3]
for x in a:
    if x==2:
        break	#当x=2时强制停止当前循环
    print(x)

跳过当前循环continue 继续执行
⚠️注意:如果使用continue跳过继续执行语句是可以执行else语句的

a = [1,2,3]
for x in a:
    if x==2:
        continue		#跳过x=2继续执行
    print(x)

break 跳出循环不再执行下面的程序

a = [1,2,3]
for x in a:
    if x==2:
        break	#跳出循环不再向下执行程序
    print(x)
else:
    print('END')

continue 跳过循环继续往下执行程序

a = [1,2,3]
for x in a:
    if x==2:
        continue	#跳过循环继续往下执行程序
    print(x)
else:
    print('END')

break跳出最里面的循环,继续执行外侧循环;

a = [['apple','orange','banana','grape'],(1,2,3)]
for x in a:
    for y in x:
        if y == 'orange':
            break	#跳出最里面的循环;
        print(y,end="-->")
else:
    print('ENG')

重复指定次数循环

for x in range(0,10,2): # 0表示起始数字;10表示偏移量;2表示步长
    print(x,end='|')
倒序:
for x in range(10,-9,-2): # 0表示起始数字;10表示偏移量;2表示步长
    print(x,end='|')

打印出间隔的数字

#方法一
a = [1,2,3,4,5,6,7,8]
for x in range(0,len(a),2):
    print(a[x])
#方法二
a = [1,2,3,4,5,6,7,8]
b = a[0:len(a):2]
print(b)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值