循环可以和else配合使用,else下方缩进的代码指的是当循环正常结束之后要执行的代码
while...else
语法:
while 条件:
条件成立重复执行的代码
else:
循环正常结束之后要执行的代码
体验
i = 0
while (i <= 5):
print("大磊程序员")
i += 1
else:
print("程序正常结束")
#输出结果
#大磊程序员
#大磊程序员
#大磊程序员
#大磊程序员
#大磊程序员
#大磊程序员
#程序正常结束
break对于else代码影响
break结束之后不执行else代码
i = 0
while (i <= 3):
print("大磊程序员")
if(i==2):
break
i += 1
else:
print("程序正常结束")
#输出结果
# 大磊程序员
# 大磊程序员
# 大磊程序员
continue对于else代码影响
continue结束之后执行else代码
i = 0
while (i <= 3):
print("大磊程序员")
if (i == 1):
i += 2 ##加上计数器,否则陷入死循环
continue
i += 1
else:
print("程序正常结束")
#输出结果
# 大磊程序员
# 大磊程序员
# 大磊程序员
# 程序正常结束
for循环与while类似
最后
以上就是现代柚子最近收集整理的关于Python基础语法(else与循环(for、while)结合使用)while...else的全部内容,更多相关Python基础语法(else与循环(for、while)结合使用)while内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复