while loop with else


while loop with else

While loops may also have an optional else block, the else part is considered if the condition in the while loop results in False. The while loop can also be terminated with a break statement.

    The else with other loops in Python is a unique thing. In Python, a while loop is written to iterate over a code block as long as the given test expression (condition) evaluates to true.

The while loop in Python is used to check test expressions first. The Python supports having an else statement connected with a loop statement. The body of the while loop in Python is defined with an indentation. If the given condition is false, the code moves to the else part. Using the else statement, we can operate a code block once the condition is no longer true.

Just like the for loops, while loops can also use an optional else block. The else code runs only when the given condition goes wrong and evaluates to false in the while loops. If we want to stop the code at the while loop only, we can stop the while loop using a break statement. And in such cases, the else part is skipped.

  • If the given condition goes right and evaluates to true, then the else part is eliminated.
  • So, the while loop's else part operates if no break occurs and the given condition goes wrong and evaluates to false.

The programming language python evaluates any non-zero value as True. And None and digit 0 are evaluated as False.

Example:

i = 1 while i < 6: print(i) i += 1 else: print("Knowledge2life webiste")

OUTPUT:

1
2
3
4
5
Knowledge2life webiste