The purpose of this blog is to happily share my learning and ideas to help people, who actively seek solutions for the day-to-day problems faced.

Recent Posts

for/else loop in python

Loops:
Loops are supported in many of the programming languages, Python provides support for while and for loop statements. When using loops based on the need we can make use of the conditional statements to control the program flow.

Apart from conditional statement the rarely used statement is 'else' block in for loop. Yes, python supports 'for/else' block similar to 'if/else'.

for/else loop

for/else:
for/else is a strange construct in python. Both the for and else statements behave normally when used independent of each other but when combined things are little unusual. 

for:
    <iterate through loop and perform action>
else:
    <if the loop ends normally without any intervention>

Use case 1:
for/else construct can be used for searching an item, when iterating the loop if the searched item found we can break the loop and perform the desired action but if the searched item is not available in the list then we can simply route the message to else block.

Example 1:
Please click on the below git hub link for example explained using python code,

Live Demo 1:
Just in case if you feel lazy to look for the code, you can make use of the below live demo code

Use case 2:
for/else statement can also used to find prime numbers when used wisely inside another for loop

Example 2:
Best example is searching. Yes when you are looking out for something say in a file for a particular keyword, you would be more happy when you get the first searched result instead of the search engine to go through the full file and return you the result. Sounds good right :)

Please click on the below git hub link for example explained using python code,

Live Demo 2:

References:

No comments