什么是for / while else子句 [英] for what are for/while else clauses

查看:86
本文介绍了什么是for / while else子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




今天我翻遍了语言规范,看看为什么......其他:

对我来说。我有点失望地得知其他条款只是简单地在循环体之后执行
- 无论是否输入循环




那么该功能的实际用例在哪里?


我想象只有循环体才会执行else子句

没有输入,所以我可以写这个


的结果:

print r

else :

打印没有找到,伙计!


而不是


如果len(结果) :

for r结果

打印r

其他:

打印没有找到,伙计! ;


等待启示,


Diez

Hi,

today I rummaged through the language spec to see whats in the for ... else:
for me. I was sort of disappointed to learn that the else clauses simply
gets executed after the loop-body - regardless of the loop beeing entered
or not.

So where is an actual use case for that feature?

I imagined that the else-clause would only be executed if the loop body
wasn''t entered, so I could write this

for r in result:
print r
else:
print "Nothing found, dude!"

instead of

if len(result):
for r in result
print r
else:
print "Nothing found, dude!"

waiting for enlightment,

Diez

推荐答案

Diez B. Roggisch写道:
Diez B. Roggisch wrote:

今天我翻遍了语言规范,看看为什么......其他:
对我来说。我有点失望地得知其他条款只是在循环体之后被执行 - 无论是否输入循环
Hi,

today I rummaged through the language spec to see whats in the for ... else:
for me. I was sort of disappointed to learn that the else clauses simply
gets executed after the loop-body - regardless of the loop beeing entered
or not.




我没有意识到...对于其他存在,但根据语言

引用,else子句被执行,除非循环体退出

。休息声明。


David



I didn''t realize that for...else existed, but according to the language
reference, the else clause gets executed unless the loop body exited due
to a break statement.

David




" David C 。福克斯 <哒******* @ post.harvard.edu>在消息中写道

news:nr9tb.200590

"David C. Fox" <da*******@post.harvard.edu> wrote in message
news:nr9tb.200590


Fm2.189136@attbi_s04 ...
Fm2.189136@attbi_s04...
Diez B. Roggisch写道:
Diez B. Roggisch wrote:


今天我翻遍了语言规范,看看for ...
else:对我来说。我有点失望地得知其他条款只是在循环体之后被执行 - 无论循环是否输入

我没有意识到这一点。 ..else存在,但根据语言
引用,else子句被执行,除非循环体退出到break语句。
Hi,

today I rummaged through the language spec to see whats in the for ... else: for me. I was sort of disappointed to learn that the else clauses simply
gets executed after the loop-body - regardless of the loop beeing entered or not.
I didn''t realize that for...else existed, but according to the language
reference, the else clause gets executed unless the loop body exited due
to a break statement.




是的。它是循环的三个终止条件之一。问题

是它的名字真的很糟糕,终止条件我最喜欢
感兴趣

捕获的是一个循环根本没有执行的地方。


John Roth

David



Yep. It''s one of the three termination conditions for a loop. The problem
is that it''s a really bad name, and the termination condition I''m most
interested
in catching is the one where the loop didn''t execute at all.

John Roth

David


这篇关于什么是for / while else子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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