While Loop

In Python, a while loop is used to repeatedly execute a block of code as long as a certain condition remains true. The loop continues iterating until the condition evaluates to False. We use a counter variable which changes in every iteration and the condition is checked on the base of this variable.

In this example;

  • In the first line, we have assigned 0 to count variable.
  • Then in the second line, we check if count is less than 5 (which is true).
  • If true, we enter the block of while loop. Inside while loop, we print using print command.
  • In the fourth line, we increment count variable. It becomes 1. Again the process occurs, it becomes 2 and then 3, 4, and 5.
  • When it is 5, count is not less than 5. The condition on line 2 becomes false and it moves out of the while loop and the program terminates.

Note: If the condition is true and it is not becoming false, the loop will iterate again and again and never stops. The loop will stop when the condition becomes false. When infinite loop starts, you can use ctrl + c to terminate the loop.

Else Statement with while loop

We can also use else while loop. The while statement will not be executed until the condition in while loop is true. When the condition is false, the else statement is executed.

Note: The code in the else block is not executed if the loop is stopped by a break statement.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

What will be the output?

15 XP~4 min
for(i = 0 i < 3 i++) :
    print(i)
Exercise 2 of 2Easy

To exit a loop immediately, we use the ___ statement.

10 XP~2 min