Python While Loop

Python while Loop: In the previous article, we have briefly discussed the for Loop in Python.

Now, it’s time to move to the next and last type of Loop statement which is while Loop.

If you already know the working of for Loop, then understanding the while Loop will be very easy for you.

The while Loop is much similar to the for Loop and in certain conditions can be used interchangeably as well.

However, the only difference between for Loop and while Loop is that for loop is a definite loop and while loop is an indefinite loop.

Now the question arises is that what is a definite and indefinite loop.

A definite Loop is a type of loop in which we exactly know the total number of iteration the loop will perform beforehand. Example – for Loop.

On the other hand, Indefinite Loop is a type of loop in which we don’t know the total number of iteration the loop will perform beforehand and the iteration will take place until the condition doesn’t gets False. Example – while Loop.

So, while Loop is a loop statement that performs the iteration till the test expression or condition is True.

Now that you have a basic understanding of while Loop, it’s time to take a look at the Syntax of while Loop in Python.

Syntax of Python while Loop

The syntax of while Loop in Python is very simple and is as follows:

while TEST_EXPRESSION:
    STATEMENTS #body of the while loop

Firstly the “while” keyword is used for defining the while Loop.

Then followed by the while keyword, the test expression or condition is used. This expression will get evaluated and return the Boolean value (True/False) as a result.

After defining the test expression, the : (colon) symbol has to be used.

In the next line, followed by indentation, the statement (body of while Loop) is defined. These are the set of statements that will get executed until the condition or expression doesn’t returns False.

So, the block of code inside the while Loop will get iterated, till the TEST_EXPRESSION returns True.

To understand the working of while Loop in more detail, you should take a look at the Python while Loop Flowchart.

Flowchart of while Loop

Below is the Flowchart of Python while Loop which will help you in better understanding it’s working.

Flowchart of Python While Loop

As you can see that after entering the while Loop the test expression gets evaluated.

If it returns True, then the Statements or the body of the while loop will get executed and if it returns False the Loop will get ended.

So, until the test expression doesn’t returns False, the body of the while loop will get executed.

Python while Loop Examples

Nothing is better than examples to understand any concept in Programming.

So, here are some of the common and simple examples in Python while Loop:

1. Python while Loop with number

num = 0

while num <= 5:
    print(num)
    num = num + 1

Output:
0
1
2
3
4
5

As you can see above, that you need to first initialize the variable before actually creating the while Loop.

So, we have initialized the num variable with 0.

In the next line, we created a while Loop with “num <= 5” as a test expression and followed by that we used the : (colon) symbol.

Now, this test expression (num <= 5) will check whether the value of num is smaller or equal to 5 and will return True or False accordingly.

Till the test expression returns True, the set of code inside the while Loop gets executed.

As you can see inside the body of while Loop, the print() function is used for printing the value of num, and the value of num is incremented with every iteration.

Now, incrementing the value of the “num” variable is very important because, without incrementing the value of num, our Loop will never end (test expression will never return False) and will continue to print the same value of the “num” variable for the infinite times.

2. Python while Loop with string

password = ''

while password != 'helloworld':
    password = input("Enter the correct password: ")

print("You are logged In")

Output:
Enter the correct password: hello
Enter the correct password: helloworld
You are logged In

Here is another good example of Python while loop, in which we have to compare one string with another.

So, firstly we declared an empty variable named “password”.

Inside the while Loop, we defined the test expression, which will check whether the value of the “password” variable is equal to ‘helloworld’ or not.

If the value of the “password” variable is not equal to ‘helloworld’, it will ask for the user to enter the correct password.

On the other hand, if the value of the password is equal to ‘helloworld’, the loop will end and you will see the message “You are logged In” on the screen.

3. Python while Loop with list

cars = ["Chevrolet", "BMW", "Ford", "Hyundai"]
while cars:
    print(cars.pop())

Output:
Hyundai
Ford
BMW
Chevrolet

Python while Loop is also used with list.

As you can see in the above code. We have created the list named “cars”, which consist of the names of the 4 car brands.

Inside the test expression, we have simply written the name of the list (which is cars).

Now, To print all the elements of the list with the help of while Loop, we have to make use of the pop() function.

The pop() function is used for returning the elements from the last index of the list.

4. Python while Loop with sequence

cars = ["Chevrolet", "BMW", "Ford", "Hyundai"]
x = 0

while x < len(cars):
    print(cars[x])
    x = x + 1

Output:
Chevrolet
BMW
Ford
Hyundai

Here is the second approach for printing the elements of the list with while Loop in Python.

In case, you want to print the elements from the first index of the list, you can use the above method.

As you can in the above program, we have initialized the list named “cars” and the ‘x’ variable with 0.

In the while loop, the test expression (x < len(cars)) is used, which will check whether the value of ‘x’ is smaller than the length of the ‘cars’ list or not.

So, until the test expression doesn’t returns False, the body of the while loop will get executed.

With the help of index operator, we will print the elements of the list.

At last, we have to increment the value of the ‘x’ variable as well.

Now, similar to the above example, here is the program for printing the elements of the tuples with the help of a while Loop.

city = ("Dubai", "Paris", "Tokyo", "London")
x = 0

while x < len(city):
    print(city[x])
    x = x + 1

Output:
Dubai
Paris
Tokyo
London

One-Line while Loop in Python

One-Line while Loop is also known as Single Statement while Block or One-Liner while Clause.

The working of the One-Line while Loop is similar to the normal while Loop. However, the difference is in the syntax only.

num = 0
while num < 5: num = num + 1; print(num)

Output:
1
2
3
4
5

In One-Liner while Clause, instead of writing the statements (body of the loop) in the next line after the test expression, we write it in the same line and separate the statements with the ; (semicolon) symbol.

Nested while Loop in Python

Nested while Loop is nothing but using one while Loop inside another while loop.

i = 1

while i <= 2:
    print(f"Outer Loop run {i} time")
    j = 1
    while j <= 3:
        print(f"Inner Loop run {j} time")
        j = j + 1
    i = i + 1

Output:
Outer Loop run 1 time
Inner Loop run 1 time
Inner Loop run 2 time
Inner Loop run 3 time
Outer Loop run 2 time
Inner Loop run 1 time
Inner Loop run 2 time
Inner Loop run 3 time

As you can see in the above program, the Outer loop runs 2 time and with each iteration of the Outer Loop, the Inner Loop runs 3 time.

Therefore, In the output, you can the single statement of Outer Loop followed by the 3 statements of Inner Loop and again the same loop continue.

Python Infinite Loop

Python Infinite loop is a state in which the test expression of the while loop will never return False. As a result, the loop runs for an infinite amount of times.

num = 2

while num == 2:
    print("This is Infinite Loop")

Output:
This is Infinite Loop
This is Infinite Loop
This is Infinite Loop
This is Infinite Loop
This is Infinite Loop
This is Infinite Loop
.
.
.
This is Infinite Loop
This is Infinite Loop

As you can see in the above program, the test expression consists of “num == 2”. Since, the value of num is 2, so it returns True.

Now, Inside the Loop body, num variable never gets incremented.

So, In the output section, we will get the message “This is Infinite Loop” for the infinite amount of times.

Below is another example of Infinite while Loop.

str_value = True

while (str_value):
    print("Infinite Loop")

Output:
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
.
.
.
Infinite Loop
Infinite Loop

In the above program, we have initialized the Boolean variable named “str_value” with True.

So, by using this Boolean variable in the test expression of the while Loop, we will get the Infinite amount of iteration.

Loop Control Statements in Python while Loop

In Python, there are 3 types of loop control statements.

First, let’s start with the break statement.

1. Python break statement

The Python break statement is used to exit the Loop.

num = 0

while num < 7:
    num = num + 1
    if num == 5:
        break

    print(num)

Output:
1
2
3
4

So, Inside the while loop, whenever the break statement gets executed, the loop gets ended and the flow of the program gets out of the scope of the while loop.

2. Python continue statement

The Python continue statement is used to skip the particular iteration and move the flow of the program to the next iteration.

num = 0

while num < 7:
    num = num + 1
    if num == 5:
        continue

    print(num)

Output:
1
2
3
4
6
7

As you can see in the above program when num gets equal to 5, the continue statement gets executed and as a result that iteration is skipped and we didn’t get 5 in the output as well.

3. Python pass Statement

Python pass statement is nothing but just a placeholder for the future code.

num = 0

while num < 7:
    num = num + 1
    if num == 5:
        pass
        print("This is a Pass Statement")

    print(num)

Output:
1
2
3
4
This is a Pass Statement
5
6
7

So, In case you don’t have a code for any particular section of your program, however, you want to add the code in that section in future, then you can make use of the pass statement.

Else Statement in Python while Loop

In Python, you can use else statement with a while Loop as well.

The block of code inside the else statement gets executed after the while Loop ends or test expression returns False.

num = 1

while num < 5:
    print(num)
    num = num + 1
else:
    print("Else Statement in While Loop")
print("Loop Ends")

Output:
1
2
3
4
Else Statement in While Loop
Loop Ends

As you can see in the above program, the value of num gets printed iteratively and when the value gets equal to 5, the condition gets False and else block gets executed.

Below is another example of else statement with while Loop. However, here we have also used the break statement inside the while loop.

If you are using else statement with while Loop and break statement gets executed inside the while block, then along with the while block, the else block also gets skipped or doesn’t executes.

num = 1

while num < 5:
    if num == 4:
        break
    print(num)
    num = num + 1
else:
    print("Else Statement in While Loop")
print("Loop Ends")

Output:
1
2
3
Loop Ends

As you can see in the above code that by using the break statement, the flow of the program gets shifted to the last line without the execution of the else block.

Python do-while Loop

Unlike C, C++, or Java Programming Language, Python doesn’t have support for do-while Loop.

So, we have to manually create a code which will work exactly like a do-while loop.

Before creating a code, let’s take a look at the basic syntax of do-while Loop.

do {
    STATEMENTS
} while (EXPRESSION / CONDITION)

In the do-while loop, the statement gets executed for at least one time. Doesn’t matter whether the condition or test expression is True or False.

So, here is the Python code which will work exactly as the do-while loop works and we have a break statement for doing so.

x = 0

while True:
    print(x)
    x = x + 1
    if(x > 4):
        break

Output:
0
1
2
3
4

As you can see that we have set the test expression to True and inside the while loop, we have used the break statement as well.

So, as the test expression is True, the value of ‘x’ gets printed and then the value of x gets incremented.

At last, the If statement is used for checking whether the value of x is greater than 4 and if it returns True, then the break statement gets executed and while Loop ends, otherwise the iteration continue.

Subscribe to our Newsletter

Get regular updates and tips related to Programming and Software Development, right in your Inbox.

* indicates required