day2.4-4 for-else和while-else的使用(99乘法表)

break和continue的使用
break 代表中断和结束,只要满足条件,直接结束本层循环
continue 结束本次循环,继续的进行下次循环(当continue的条件满足的时候,本次循环剩下的语句将不再执行,后面的循环继续)
这两个关键字只能用在循环中

#break的使用
sum = 0
for item in range(1,51):

    if sum > 100: #如果累加大于100就退出循环
        print('循环执行到%d退出'%item)
        break
    sum = sum + item

print("sum=%d"%sum)

print('-------break的使用案例2----------')

for str in 'i love python':
    #if str == 'e':
    #    break

# continue的使用
    #print(str)
    if str == 'o':
        continue
    print(str,end=' ') #end= ' ' 表示不换行

#continue的使用,打印所有奇数
for items in range(1,100): #用for循环遍历1-100的数据
    if items %2 == 0: #判断这个数是不是偶数
        continue #如果items是偶数,代码不会继续执行,也就是不会执行打印操作
        print('在continue后面会不会执行') #这一行没有打印出来,说明只要满足条件就退出了本层循环
    print(items,end=' ')

#用while来演示
index=1
while index<=100 :
        if index > 20: #如果大于20就停下,所以打印出来是1-20
            break

        print(index)
        index = index +1

while和for循环的区别:
while使用:适用于对未知的循环次数(不知道要循环多少次,根据条件动态地控制要循环多少次),用于判断
for使用:适用于已知的循环次数(可迭代对象的遍历),用于遍历

#用for实现99乘法表
i=1
j=1
for i in range(1,10): #控制行
    for j in range(1,i+1): #i+1是结束的范围,控制列
        print('%d * %d = %d'%(i,j,i*j),end = ' ')
    print() #有换行效果,控制换行
    pass

for--else 结构

for item in range(1,11): #1-10个数
    print(item,end= ' ')
    if item >= 5:
        break
else:
    print('已经执行完了吗') #这里写else和没写一样,else在什么情况下才是会执行的? #当上面的循环出现break时,else的循环将不会执行
print()


#执行for-else语句
account = 'xyz'
pwd = '123'
for i in range(3):
    username = input('please enter your username')
    pd = input('please enter you password')
    if account == username and pwd == pd:
        print('log success')
        break #如果登陆成功,退出本层循环,不会执行else;如果账号密码输入错误3次,就会执行else
else:
    print('your account has been locked')

while -- else结构

index=1
while index <=10:
    print(index)
    if index ==6:
        break
    index = index +1
    pass
else:
    print('else执行了吗')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值