Published on

Else Clauses on Loops

Authors

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.