How to use while loop in Python

About while loop in Python

In Python, the 'while' loop is used to repeatedly execute a block of code as long as a specified condition is true.

The condition is evaluated before each iteration. If it is True, the code block inside the loop is executed.

If the condition is False, the loop will stop to execute the block of code.

It's important to ensure that the condition in a while loop will eventually become False, otherwise, the loop will continue indefinitely.



Syntax of while loop

In the above syntax, the 'while' will be followed by a condition with colon (:).

The block of code must have proper indentation (at least one space at the beginning of the code for indentation).

Using while loop in Python

1. Create a variable 'counter' and initialize it with 1 (counter = 1).

2. Create a while loop with condition using 'counter' variable (while counter < 6:) where counter is less than 6 is the condition. The condition (counter < 6) is followed by a colon (:) which is part of the syntax.
The while loop will continue to execute as long as the counter value is less than 6.

3. Now create a block of code that will be executed if the condition is true. The print message print("While loop executed:", counter) is the block of code to be executed.

4. Increase the counter value by 1 in each iteration (counter += 1).

Important! It is necessary to increase the counter value, otherwise, the loop will continue indefinitely.

Please take a closer look at the following example:

Example of while loop

Output of the above example
While loop executed: 1
While loop executed: 2
While loop executed: 3
While loop executed: 4
While loop executed: 5
Loop stopped.

Using else in while loop

You can add an 'else' block to a while loop.

The code inside the 'else' block runs once when the condition becomes false.

Please take a closer look at the following example:

Example of else in while loop

Output of the above example
While loop executed: 1
While loop executed: 2
While loop executed: 3
While loop executed: 4
Loop stopped & else block runs.

Live Code Playground

In the following Python code editor, you can practice the above code by creating while loop. Click on the 'Execute Code' button to execute the code; the executed output will be displayed in the following Python Code Output frame. Practice until you become comfortable and proficient with your code.

Python logo Python Online Editor
Python Code Output