In this video, we look at a lesser known feature of Python for and while loops: they have an "else" clause.
You can use the else on a loop to indicate whether a loop completed successfully or not.
We give some practical examples so you see how to leverage this structure in your Python code.
Additionally, we learn how to utilize the Abstract Syntax Tree (AST) to quickly identify this construct in Python files.
We use it in a script - linked below - to find use cases of our own as well as examples from 3rd party libraries (e.g. Django + Pillow).
Links:
for-else.py gist to search for this construct in code using AST: https://gist.github.com/bbelderbos/f4...
Raymond Hettinger on the history of the for ... else construct: • Transforming Code into Beautiful, Idi... (found via https://stackoverflow.com/a/23748240 / watch his whole talk, it's really good! Notes: https://pybit.es/beautiful-python.html)
For vs while beginner video on this channel: • For vs while loops in Python: when to...
---
Learn more about Pybites / what we do: https://pybit.es
Get our weekly developer / mindset emails: https://pybit.es/friends/
Join our Slack community: https://pybit.es/community/
And last but not least, we appreciate any feedback to make our YouTube content better 💡
https://form.jotform.com/230941798741062 🙏
On this page of the site you can watch the video online Python Loop Mastery: Demystifying the Else Clause in For and While Loops with a duration of hours minute second in good quality, which was uploaded by the user Pybites 22 May 2023, share the link with friends and acquaintances, this video has already been watched 199 times on youtube and it was liked by 13 viewers. Enjoy your viewing!