3 examples to learn Python While loop

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 loop in Python with single and multiple statements execution.

A While loop example

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

See this example online


Output will be:

1

2

3

4

5

Example of while loop Python 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 well. As such, the while block is based at indentation, the last print statement at the root or zero space will be executed after the condition in the while loop is false.

See this example online


Output will be:

1

2

This is multi-statement while example

3

4

5

Execution is out of while now!

Using else with While loop

Python allows to use 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 be executed once and the execution will be moved outside of the Python while loop.

See the example below:

See this example online


Output will be:

1

2

3

4

5

While condition is evaluated FALSE

 

Also see – Python for loop | Python break statement

Was this article helpful?

Related Articles

Leave A Comment?