Python While Loop

  • Post category:python
  • Reading time:6 mins read

Introduction

Loops are essential constructs in Python (and many other programming languages) for iterating over collections of data or executing a block of code repeatedly. There are mainly two types of loops in Python: for loops and while loops. In this post, we will understand the concept of python While loop.

Python While Loops

A while loop is used to execute a block of code repeatedly as long as a condition is true. The basic syntax is:

while condition:
    # code block to be executed

Here, condition is any expression that evaluates to True or False. The code block underneath the while statement is executed repeatedly as long as the condition remains True. Let us see an example below:

The condition is an expression that is evaluated before each iteration. If the condition evaluates to True, the code block inside the while loop is executed. This process continues until the condition becomes False, at which point the loop terminates.

counter = 0
while counter <= 5:
    print("Counter: ", counter)
    counter += 1

# Output
Counter:  0
Counter:  1
Counter:  2
Counter:  3
Counter:  4
Counter:  5

Loop Control Statements

Python also provides loop control statements like break, continue, and else.

  • break statement: Terminates the loop prematurely.
  • continue statement: Skips the rest of the code block and continues with the next iteration of the loop.
  • else statement: Executed when the loop is exhausted (i.e., the condition in a while loop becomes False or when all items in an iterable are exhausted in a for loop).

Here is an example.

While Loop – break Statement

The break statement is used to exit a loop prematurely, regardless of the loop’s condition. When the break statement is encountered within a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop.

counter = 0
while counter <= 5:
    if counter == 4:
        break
    print("Counter: ", counter)
    counter += 1

# Output
Counter:  0
Counter:  1
Counter:  2
Counter:  3

While Loop – continue Statement

The continue statement is used to skip the rest of the code block within a loop for the current iteration, and the loop continues with the next iteration.

counter = 0
print("Continue Statement.")
while counter <= 5:
    if counter == 4:
        counter += 1
        continue
    print("Counter: ", counter)
    counter += 1

# Output
Continue Statement.
Counter:  0
Counter:  1
Counter:  2
Counter:  3
Counter:  5

While Loop – pass Statement

The pass statement is a null operation; nothing happens when it executes. It is often used as a placeholder when a statement is syntactically required but you don’t want any action to occur.

counter = 0
print("Continue Statement.")
while counter <= 5:
    if counter == 4:
        # Do nothing when counter equals 4
        pass
    else:
        print("Counter: ", counter)
    counter += 1

# Output
Continue Statement.
Counter:  0
Counter:  1
Counter:  2
Counter:  3
Counter:  5

The else Statement

In Python, the else statement can also be used with while loops. The else block associated with a while loop is executed when the loop’s condition becomes False. This is useful when you want to execute some code after the loop has finished its iterations normally, without encountering a break statement.

while condition:
    # code block to be executed inside the loop
else:
    # code block to be executed after the loop (when the condition becomes False)

Here is an example

count = 1
while count <= 5:
    print("Count: ", count)
    count += 1
else:
    print("Loop completed without interruption.")

# Output
Count:  1
Count:  2
Count:  3
Count:  4
Count:  5
Loop completed without interruption.

In this example:

  • The while loop iterates while count is less than or equal to 5. Inside the loop, it prints the current value of count and increments it by 1.
  • After the loop finishes iterating (i.e., when count becomes 6 ), the else block is executed, printing “Loop completed without interruption”.

NOTE: The else block associated with a while loop won’t be executed if the loop is terminated prematurely using a break statement. It only executes when the loop condition becomes False and the loop exits naturally.