30,331
社区成员
发帖
与我相关
我的任务
分享
一、基本理解
使用while循环,只要条件为真,我们就执行一组语句
例如:
只要i小于就打印i
i = 1
while i < 6:
print(i)
i += 1
结果
注意:记住要限制i,否则循环将永远持续下去
二、中断声明
使用break语句,即使while条件为真,我们也可以停止循环
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
结果
1
2
3
三、continue声明
使用continue语句,我们可以停止当前的迭代,并继续下一个:
i=0 while i<6: i+=1 if i==3: continue print(i)
结果:
1
2
4
5
6
注意
返回:可以并没有打印3
四、else语句
使用else语句,当条件不再为真时,我们可以运行一次代码块:
一旦条件为假,打印一条消息
i=1 while i<6: print(i) i+=1 else: print("i is no longer less than 6")
结果:
1
2
3
4
5
i is no longer less than 6