python教程(五)之语句(6.跳出循环)

循环会不断执行代码块,直到条件语句为false或执行了全部迭代,为了让循环更灵活,需要能够终止和跳出的方法

1.break直接终止循环

for a in list(range(100)) :
    if a>5 : break
    print(a)
#结果只打印到5就不再打印,因为break直接终止了上层的for循环

2.continue跳出当次循环并开始下一次循环

from math import sqrt
for b in list(range(100)) :
    bPre=sqrt(b)
    if bPre==int(bPre) and bPre!=0 :
        print(bPre,"**2=",b,sep="")
    else : continue        
# 1.0**2=1
# 2.0**2=4
# 3.0**2=9
# 4.0**2=16
# 5.0**2=25
# 6.0**2=36
# 7.0**2=49
# 8.0**2=64
# 9.0**2=81

#这里continue并没有发挥作用,因为没有它也执行一样的结果
#正常来说
# for x in items :
#     if not (condition1 or condition2 or condition3) :
#         do_somethings()
# for x in items :
#     if condition1 : continue
#     if condition2 : continue
#     do_somethings()
#这种才是 continue的常规用法,但通常if就足够了

3.while True 永不结束的循环

x=""
while True and x!="stop":
    x=input("please enter a string:")
    print(x)
# please enter a string:da
# da
# please enter a string:stop
# stop    
#如果我不输入stop那么这个循环将会永远继续下去
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值