“其他"有什么用?在“for"之后在 Python 中循环? [英] What is the use of "else" after "for" loop in Python?

查看:81
本文介绍了“其他"有什么用?在“for"之后在 Python 中循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎下面的两个代码都打印相同,那么python中for"循环之后的else"块有什么需要.

It seems both of the below codes are printing the same, then what is the need of "else" block after "for" loop in python.

代码 1:

for i in range(10):
    print i
else:
    print "after for loop"

代码 2:

for i in range(10):
    print i

print "after for loop"

提前致谢.

推荐答案

来自文档:

Loop 语句可能有一个 else 子句;它在循环因列表耗尽(使用 for)或条件变为假(使用 while)而终止时执行,但不会在循环被 break 语句终止时执行.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

点击链接查看如何使用它的示例.

Follow the link for an example how this can be used.

这篇关于“其他"有什么用?在“for"之后在 Python 中循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆