Hacker News
new
|
past
|
comments
|
ask
|
show
|
jobs
|
submit
login
The for/Else Statement in Python
(
theautomatic.net
)
8 points
by
atreadw
on July 9, 2020
|
hide
|
past
|
favorite
|
7 comments
bzb3
on July 9, 2020
|
next
[–]
Surprising. I didn't know this construct and I would naturally assume that the else part would execute if the loop never spun (because the list/etc was empty)
amitutk
on July 9, 2020
|
parent
|
next
[–]
Yes, the else keyword is not intuitive. The best way to remember for/else is for/nobreak
neverartful
on July 9, 2020
|
root
|
parent
|
next
[–]
Right! nobreak would make it much clearer.
Dagger2
on July 10, 2020
|
root
|
parent
|
next
[–]
It would involve adding a new keyword to the language though. I imagine there was some desire to avoid that.
neverartful
on July 9, 2020
|
parent
|
prev
|
next
[–]
This was my guess too.
Doxin
on July 9, 2020
|
prev
|
next
[–]
Relatedly there's also a try/else, where the else block only runs if there wasn't an exception.
All these else variants come in handy from time to time.
rosstex
on July 9, 2020
|
prev
[–]
The most common use case of for/else for me is:
for/len==0
Guidelines
|
FAQ
|
Lists
|
API
|
Security
|
Legal
|
Apply to YC
|
Contact
Search: