What is a while loop in Python

What is while loop in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
We generally use this loop when we don't know beforehand, the number of times to iterate.

Syntax of while Loop in Python

while test_expression:
    Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as TrueNone and 0 are interpreted as False.

Flowchart of while Loop

while Loop in Python programming

while loop with else

Same as that of for loop. we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a  break statement. In such case, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.

Post a Comment

0 Comments