Else Clauses on Loops

Did you know that loop statements may have an else clause? Well, it turns out that they can be used!

  • else clause will be executed when the loop completes through all of the iterations with for loop and when the condition becomes false with while loop.

Example: Alt Text

Output:

Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Treasure not found :(
  • But else clause will not be executed when the loop is terminated by a break statement.

Example: Alt Text

Output:

Searching...
Searching...
Searching...
Searching...
Found the treasure

Code along and have fun.

Aswin Barath

Aswin Barath

My name is Aswin Barath. I’m a technical blogger and budding software engineer