Python While loop


WHILE LOOP

The while loop is used in the case where we need to execute some part of the code until the chosen condition is satisfied. It is easier to use the while loop if the number of iteration is before known in advance.

Syntax:

while < test_expression>:
< statement>

The while loop in python is used to check test expression first. Then, the body of the while loop is accessed only if the test_expression goes right and evaluates to True. After doing the first iteration, the test expression is verified again. And the process extends until the test_expression goes wrong and evaluates to False.

The while loop in python is practised to repeat over a piece of code as long as the test expression (condition) goes true.

While loop is used when a programmer doesn't know how many times to iterate beforehand.

Python represents any non-zero value as True. Whereas None and 0 are represented as False

. Note: The key point of the while loop is that the loop may not ever run. After testing the given condition, if the conclusion is false, the loop body will be skipped, and the first statement after the while loop will be executed.

. The body of the while loop in python is defined through indentation.

. The body begins with indentation, and the very first unindented line signifies the end. The exact number of character spaces indents all the statements in python after a programming construct is supposed to be part of a particular piece of code.

Example No.1:

i = 1 x='knowledge2life' while i < 6: print(x) i += 1

OUTPUT:

knowledge2life
knowledge2life
knowledge2life
knowledge2life
knowledge2life

Example No.2:

i = 1 x='Knowledge2life' while i < 6: print(x) if (i == 3): break i += 1

OUTPUT:

knowledge2life
knowledge2life
knowledge2life