Python While Loop

While loop in Python iterates over the block of code as long as the test condition) is true. It executes the statements as long as the condition is true.

The while loop tells a computer to do something if the condition is met or held. Its construct consists of the block of code and the condition. The condition is evaluated, and if the condition is true, the code within the block is executed. It repeats until the condition becomes false.


while test_expression:
 { body of while }

In the while loop, the test expression is checked first. After that, the body of a loop is entered only if a test_expression evaluates to True.

After one iteration, the test expression is rechecked. This process continues until the text_expression evaluates to False. Remember, we need to change the value somehow. Otherwise, it will go into an infinite loop.

In Python, a body of a while loop is determined by indentation. The body starts with an indentation, and the first unindented line marks the end. Python interprets any non-zero value to TrueNone and 0 are interpreted as False.

Example 1

i = 21

while i < 29:
  i += 1


Python While Loop Example

In the above program, the test expression will hold as long as our variable i is less than or equal to 29 in our program, starting from 21.

We need to increase the value of i variable in the body of the loop. It is essential and mostly forgotten. If we fail to do so will result in an infinite loop or never-ending loop. Finally, the result is displayed.

Example 2

In Python, you can use an “else statement and a while loop”. The else block will be executed only when the loop has finished iterating (i.e. when the loop condition becomes False). If the loop is terminated by a break statement, the else block will not be executed.

counter = 0

while counter < 3:
  counter = counter + 1
  print('Executed Else Statement')

In the above code, the counter is printed unless the condition is false. After the condition is false, the else block is executed. 

while loop with else

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.