Python While Loop: Learn Basics with 3 examples

Python While Loop: Learn Basics with 3 examples

What is the While loop of Python?

A while loop in Python keeps on executing the block of the statement(s) as long as the given condition, a Boolean expression, is true.  As the condition becomes false the pointer/execution will move to the next statement, outside of the while loop.

Syntax of While loop

Following is the general structure of while loop:

while expression:

   statements(s) to be executed

Examples of using while loop

Following are a few examples of using the while Python loop with single and multiple statement execution.

A while loop example

The example below prints the numbers by using the Python while loop.

See this example online

The output will be:

1

2

3

4

5

Example of while loop with multiple statements

In the following example, an if statement is used for illustration purpose. As variable i will have the value = 3, it will print a statement.

As such, the while block is based on indentation, the last print statement at the root or zero space will be executed after the condition in the while loop is false.

Python while loop

See this example online

The output:

1

2

This is multi-statement while example

3

4

5

Execution is out of while now!

Using else with While loop

Python allows using the else statement (without the if statement) when a condition in the while loop becomes false.

As such, the block of the statement(s) inside the while loop will be executed as long as the condition is true. When it becomes false, the else block will execute once and the execution will be moved outside of the while loop.

See the example below:

Python while else

See this example online

The output:

1

2

3

4

5

While condition is evaluated FALSE

 

Further ReadingPython for loop