while loop in python


  • A Python ‘while loop’ repeatedly carries out a target statement while the condition is true.
  • The loop iterates as long as the defined condition is true. When it ceases to be true and becomes false, control passes to the first line after the loop.
  • A loop very similar to for since it also executes a code portion in a repeated way.
  • In this case there is no iteration over an object, so this loop doesn’t end when the iteration object is traversed, but when a given condition is not true.

Syntax

    while EXPRESSION:
      Statement

Flow Diagram

    while-loop in python language

Example

It is very important to take into account that there should be an instruction inside the block to make the while condition false. Otherwise, we could enter into an infinite loop.

    >>> a=10
    >>> while a<40:
          print(a)
          a = a+10
    

Output

    10
    20
    30