刘心向学(46):for-else 和 while-else —— 循环的“善终”才触发

B站影视 欧美电影 2025-09-29 16:07 1

摘要:Increase knowledge, leave a beautiful!

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是LearningYard新学苑。

今天小编为大家带来文章

“刘心向学(46):for-else 和 while-else —— 循环的“善终”才触发”

Share interest, spread happiness,

Increase knowledge, leave a beautiful!

Dear, this is LearningYard Academy.

Today, the editor brings you an article.

“Liu Xin Xiang Xue (46) – for-else and while-else: Code That Runs Only When the Loop "Completes"”

Welcome to your visit.

二、引言(Introduction)

你可能不知道:Python 中的 for 和 while 循环可以带 else 子句。

但它不是“否则”,而是:

Did you know? In Python, for and while loops can have an else clause.

But it’s not “otherwise”. It means:

“只有正常结束时才执行,被 break 打断就不执行。”

“Run this only if the loop finishes normally — not interrupted by break.”

Python深色版本for item in items:if target == item:print("找到")breakelse:print("没找到") # 仅当未 break 时执行循环走完所有项 → 执行 else遇到 break → 跳过 else

Loop completes → else runs

break triggered → else skipped

Python深色版本for user in users:if user.active:send_message(user)breakelse:print("无活跃用户")

替代 found = False 标志变量。

Eliminates the need for a found = False flag.

else 属于 for,不是最近的 if

else belongs to the for, not the inner if

continue 不影响 else

continue

does not skip else

空循环也会执行 else

适合搜索、验证、重试等场景

Great for searches, validations, retries

语义反直觉,建议加注释

Non-intuitive — add comments if used

避免在复杂逻辑或不熟悉团队中滥用

Avoid in complex logic or unfamiliar teams

for-else 不是语法怪胎,而是一个减少标志变量、提升代码紧凑性的利器。

for-else isn’t a quirk — it’s a clean way to avoid flag variables and make intent clear.

用得好,它就是 Pythonic 的典范;

Used wisely, it’s deeply Pythonic.

用不好,它就是可读性的灾难。

Used poorly, it harms readability.

关键在于:理解意图,合理使用

下次想写 found = False 时,想想 else。

Next time you write found = False, think: Can I use else instead?

今天的分享就到这里了。

如果您对文章有独特的想法,

欢迎给我们留言,

让我们相约明天。

祝您今天过得开心快乐!

That's all for today's sharing.

If you have a unique idea about the article,

please leave us a message,

and let us meet tomorrow.

I wish you a nice day!

参考资料:通义千问

参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.

Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.

本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!

LearningYard新学苑

文字:song

排版:song

审核|hzy

来源:LearningYard学苑

相关推荐