Python while Loop Complete Tutorial

In this section, we will learn what the while loop is and how to use it in Python.

while Loop in Python

The while loop in python allows us to loop through a block of code (meaning execute that block of instructions repetitively) until a certain condition is met.

At its code, a while loop is nothing but a block with a condition statement on top of it.

The block is the place where we define the necessary instructions to be executed and the condition statement is the part that will be checked per each iteration (per each execution of the block).

As long as the condition of the while loop results True, the body of the loop gets executed over and over again.

But the moment the result of the while loop condition was False, the execution engine will terminate the work of the loop and continue to execute the instructions after the loop (if any).

Python while loop syntax

while condition: 
    #body… 

`while`: to create a while loop, we first start with the keyword `while`.

`condition`: this is the conditional expression of the loop where we define an expression that will be evaluated first and if the result was True, then the body of the loop executes. Note that the condition is evaluated per each body’s execution.

Now the moment the condition resulted False, the work of the loop is done and the execution engine will move on to the next instructions after the loop.

`:`: the body of the while loop starts after the colon `:` and it includes the indented lines below it.

Example: creating a while loop in Python

val = 0 
print("Before the while loop")
while val <3:
    print(val)
    val +=1

print("After the while loop")

Output:

Before the while loop

0

1

2

After the while loop

How does `while` loop work?

In the last example, when the execution engine reached the while loop, it first checked the condition of the loop to see if it results True! Here because the value of the `val` variable is less than 3, then the condition is True and so the engine is allowed to run the instructions within the body of the while loop.

After the body got executed, the Python execution engine returns to the condition of the loop to see if now the condition of the loop is still True or not. On the second evaluation of the condition, the value of the `val` variable is 1, and it is still less than the value 3. So the condition is True and the body of the loop will run again.

After another iteration through the body of the loop, the engine once again returns to the condition to see if the condition is still holding True. So here the value of the `val` variable reached to 2 and so the condition is still True and once again the body of the loop gets executed.

Now, for the fourth time, the execution engine returns to the condition of the loop to see if it holds True or not. This time, however, the value of the `val` variable is equal to `3` and so it is no longer less than the value 3 itself! And for this reason, the condition of the loop is no-longer True! So, the execution engine terminates the while loop and will move to the instructions after the loop, which for this example is just one simple call to the print() function in order to send a message to the output stream.

That’s how a while loop work in Python.

How to exit while loop in Python?

In a normal scenario, the job of a while loop is to run as long as its condition is met (True).

But sometimes we want to terminate a loop early and before its condition results False!

There are two ways by which we can terminate a loop early:

Python while loop and return statement:

We know that a return statement is used to return from a function call with a value! We can use the return statement within the body of a while loop as well! This way, when the execution engine reached to the `return` statement, it will terminate the work of the loop as well as the enclosing function.

Note: the return statement terminates not just the loop but also the function that the loop is called in.

Example: using return statement in the while loop

def func():
    val = 0
    while val <100:
        val +=1
        if val ==50:
            return val

res = func()
print(res)

Output:

50

Note that the condition of the `while` loop in the example above is to let the loop execute for as long as the value of the `val` variable is less than 100. This means in an ideal condition, the loop will run at least 100 times (because of the current value of the val variable is set to 0).

But after just 50 times of iteration, we can see that the loop breaks and returned the value 50 as a result!

This is because of the `if` statement and the `return` within its body that will trigger when the value of the `val` variable reached to 50.

Note: again, remember that the `return` statement will break not just the loop but also the enclosing function.

Python while Loop and else Statement

The `while` loop statement also has an optional `else` statement as well.

We can set an `else` statement for a `while` statement and it will get executed when the condition of the `while` loop becomes False.

So the moment the condition of the `while` loop is False, the Python execution engine will move on to the body of the `else` statement and run any instructions there.

Python else Statement Syntax:

while condition: 
    #body… 
else:
    #body…

`else`: in order to create an `else` statement, we first start with the keyword `else`. Note that the else statement comes after the body of the `while` statement.

`:`: we use the colon to set the beginning of the body of the `else` statement. After that, any indented line below the `else` statement becomes part of the `else` body.

Example: using while loop with else statement in Python

def func():
    val = 0
    while val <100:
        val +=1
    else:
        print("This message is coming from the else statement of the while loop")

    print(val)

func()

Output:

This message is coming from the else statement of the while loop

100

In this example, after the execution of the while loop for 100 times (because of the condition of the loop requires it to run for a 100 until the condition becomes False) after that, the body of the `else` statement ran.

Python Infinite while loop

An infinite while loop is a loop that runs forever! Or it runs as long as the operating system does not shut it down.

In order to create an infinite loop in Python, we need to set the condition of a while loop in a way that never result False! For example, we can simply put the value True as the condition, and that way it will never return False!

Note: even though we can create an infinite loop in Python, we seldom need such type of loop.

Example: creating Infinite while loop in Python

while True:
    print("infinite loop")
print(“This message will never print”)

Output:

infinite loop

If you run this simple program, you’ll get a constant message of “infinite loop”. This is because the condition of the loop is always True and so the execution engine gets stuck in the body of this loop forever.

Nested while loops in Python

The body of a while loop is the place where we can put any sort of instructions! This includes adding another while loop!

Basically, a while loop that is set inside another while loop is called nested while loop.

Example: creating nested while loop in Python

val1 = 0
val2 = 0

while val1<5:
    val1 +=1
    print(f"val1: {val1}")
    while val2<5:
        val2+=1
        print(f"The value of the val2 is: {val2}")
    val2 =0

Output:

val1: 1

The value of the val2 is: 1

The value of the val2 is: 2

The value of the val2 is: 3

The value of the val2 is: 4

The value of the val2 is: 5

val1: 2

The value of the val2 is: 1

The value of the val2 is: 2

The value of the val2 is: 3

The value of the val2 is: 4

The value of the val2 is: 5

val1: 3

The value of the val2 is: 1

The value of the val2 is: 2

The value of the val2 is: 3

The value of the val2 is: 4

The value of the val2 is: 5

val1: 4

The value of the val2 is: 1

The value of the val2 is: 2

The value of the val2 is: 3

The value of the val2 is: 4

The value of the val2 is: 5

val1: 5

The value of the val2 is: 1

The value of the val2 is: 2

The value of the val2 is: 3

The value of the val2 is: 4

The value of the val2 is: 5

More to Read:

Python break statement

Python continue statement

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies