🎓 Welcome back to Digital Academy, the Complete Python Development Tutorial for Beginners, which will help you Learn Python from A to Z!
🖥️ ELSE in Python FOR Loops
The common construct is to run a loop, and search for an item. If the item is found, we break out of the loop, using the break statement. But, there are 2 scenarios in which the loop may end:
– The first one is when the item is found and break is encountered.
– The second scenario is that the loop ends without encountering a break statement.
Now we may want to know which one of these, is the reason for a loop’s completion. One method is to set a flag, and then check it once the loop ends. Another, is to use an optional else clause, at the end of for loop.
The ELSE clause in Python will be executed only if the loop terminates naturally, through the exhaustion of the iterable object. On the other hand, if the loop terminates prematurely, with break, the else clause will not be executed – at all.
Here is the basic structure, of a for-else loop. First, let’s assume you declared a list, with some colours inside. Now, you want to search for a specific item – which in that case, is the colour blue. If you find it, you want to break this loop, then continue with the next statements after the loop. But on the other hand, if you didn’t find that item, you want to execute some code first, then and only then, execute the same code that if you found it, and proceed with the rest of your code.
colours = ['red', 'green', 'blue', 'yellow']
for colour in colours:
if colour == 'blue':
# Found it!
found(item)
break
else:
# Didn't find anything!
not_found_in_iterable()
always_executed()
Let’s play this video, stick around and watch until the end of this video! 👍🏻
– Digital Academy™ 🎓
***
☞ WATCH NEXT:
○ Data Types in Python – https://youtu.be/cweUByxBWiU
○ Operators in Python – https://youtu.be/-wDaVLkKOiU
○ IF Statements in Python – https://youtu.be/CC5seZ6OBJ4
○ FOR Loops in Python – https://youtu.be/JgH-D5DSTho
☞ WATCH MORE:
○ HOW TO Learn Python? Python Tutorial for Beginners [FULL Course] https://youtu.be/9hvnSZPMtuw
📖 Blog: http://digital.academy.free.fr/blog/
📖 Complete Python Development Course for Beginners [PLAYLIST]: http://digital.academy.free.fr/playlist/python-development-for-beginners
🛒 Shopping and Discounts: http://digital.academy.free.fr/store/
#Python #Tutorial #Beginners #Shorts
***
♡ Thanks for watching and supporting ♡
Please Subscribe. Hit the notification bell.
Like, Comment and Share.
***
♡ FOLLOW US ♡
✧ http://digital.academy.free.fr/
✧ https://twitter.com/DigitalAcademyy
✧ https://www.facebook.com/digitalacademyfr
✧ https://www.instagram.com/digital_academy_fr/
✧ https://www.youtube.com/c/DigitalAcademyOnline
♡ SUPPORT US ♡
✧ http://digital.academy.free.fr/join
✧ http://digital.academy.free.fr/donate
✧ http://digital.academy.free.fr/subscribe
✧ https://www.patreon.com/digital_academy
✧ https://www.buymeacoffee.com/digital_academy
***