V
23

TIL Python's 'else' on loops is a real thing and it threw me off

I was going through a beginner course on Codecademy and got to a section about for and while loops. Honestly, I never knew you could stick an 'else' block on a loop that runs when the loop finishes normally without a break. It seems useful for search stuff but it feels backwards to my brain. Has anyone else found this confusing or actually use it in real projects?
3 comments

Log in to join the discussion

Log In
3 Comments
fiona_hunt71
Wait, so Python basically added an 'else' on loops just to mess with our heads right? It's like the language is trolling beginners on purpose. I remember learning this and thinking "oh cool, so now my loop has a guilt trip attached to it too." The worst part is it only runs when the loop finishes without breaking, so basically it's for when your loop decides to be a good boy and complete its homework. I've never used it in real code but honestly I just pretend it doesn't exist like the 'pass' statement half the time. Whoever designed this probably sat in a meeting and said "you know what loops need? More existential confusion.
5
the_miles
the_miles10d ago
Gotta push back on this one, actually used for else on a loop yesterday and it saved me a flag variable. Say you're searching a list for something and you want to do something if you never find it, like checking if a username is taken. Instead of setting a found = False and checking that after the loop, you just put your "not found" code in the else block and it runs only if the loop never hit break. It's honestly clean once you wrap your head around it. The pass statement I'll give you though, that one's basically a placeholder for your unfinished thoughts.
4
phoenix_singh25
Three years coding and I still forgot this was a feature until just now reading this... I've written whole programs with a boolean flag and an if statement after the loop like a caveman when Python was just sitting there with a perfectly good else block waiting for me. I actually tried using it once for a password validation loop and spent 20 minutes confused why my "success" message printed when the loop broke early. Turns out I had a typo in my break condition so the loop never actually hit it... classic me debugging my own laziness.
1