For - else 与 while-else

1、For - else

for循环还有⼀个else从句,这个else从句会在循环正常结束 时执⾏。这意味着,循环没有遇到任何break.

str1 = 'Python自学网'
for i in str1:
    print(i)
else:
    print('循环正常结束之后要执行的else的代码')

2、while-else

python中的while后面的else的作用是指,当while循环正常执行,中间没有break的时候,会执else后面的语句。

但是如果while语句中有brerak,那么就不会执行else后面的内容了。

count=0

while count<5:
    print("loop",count)
    if count==3:
            break
    count+=1
else:
        print("loop is done")

print("--------end---------")
posted @ 2023-03-09 21:54  饮一杯天上水  阅读(90)  评论(0)    收藏  举报