n
5

Found out yesterday that Python's 'else' clause can actually go on for loops, not just if statements

I was reading through a beginner Python tutorial on Real Python and discovered that you can use 'else' with for loops to run code only if the loop finishes without hitting a 'break', which honestly feels like a hidden feature nobody told me about; has anyone else found a use for this that actually helps in a real project?
2 comments

Log in to join the discussion

Log In
2 Comments
terry_barnes
honestly the best use i've found for this is in data validation loops. like when i'm looping through a list of user uploads and checking if any of them are corrupted or too big. if i hit a bad file i break out, but if everything passes the else block handles the batch processing. it's way cleaner than having a separate boolean flag you set to track whether you broke or not lol.
5
nina147
nina14723d ago
yeah @terry_barnes nailed it, the else block is basically a silent "all clear
4