python基础-循环语句while

本文详细介绍了Python中的循环语句,包括while循环、for循环及它们的嵌套使用,并解释了循环控制语句break和continue的功能及用法。此外,还探讨了如何在循环中使用else语句。

循环语句:while\for\嵌套

循环控制语句:break\continue

  break:跳出整个循环,不会再继续循环下去

  continue:跳出本次循环,继续下一次循环

 

while循环:

 

1 count = 0
2 while (count < 9):
3     print("count=",count)
4     count += 1
5 print("while循环结束")

 

结果:

count= 0
count= 1
count= 2
count= 3
count= 4
count= 5
count= 6
count= 7
count= 8
while循环结束

continue语句:

i = 1
while i<10:
    i+=1
    if i%2>0: #如果i%2的值大于0,则跳出本次循环,后面的语句不会执行,直接继续下一次循环,
        continue
    print(i)

 

结果:

2
4
6
8
10

break语句:

i = 1
while 1: #死循环
    print(i)
    i += 1
    if i>10:#循环到i=11的时候,执行break,跳出整个while循环
        break

 

结果:

1 2 3 4 5 6 7 8 9 10

 

else语句:

while-else 与 if-else一样

count = 0
while count <5:
    print(count,"小于5")
    count = count + 1
else:
    print(count,"大于等于5")

 

结果:

0 小于5
1 小于5
2 小于5
3 小于5
4 小于5
5 大于等于5

 

转载于:https://www.cnblogs.com/R-bear/p/6954370.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值