Python While Loop

Discover the essentials of Python's while loop, a powerful tool for repeating tasks until a specific condition is met, enabling efficient and concise coding.

Python while loop is a control flow statement that repeatedly executes a code block if a given condition is true. Its syntax is while condition:, where condition is a boolean expression. Ideal for situations where the number of iterations is not predetermined, it facilitates repeated execution until the condition becomes false.

Flowchart Of Python While Loop

Consider the following steps to create a flowchart for a while loop in Python.

  1. Start with the entry point where the loop begins.
  2. Move to the loop condition. Here, the condition of the while loop is evaluated.
  3. If the condition is true, the flow proceeds to a block where the loop's code is executed.
  4. After executing the code within the loop, the flow returns to the loop condition.
  5. This process repeats as long as the loop condition remains true.
  6. Once the condition evaluates to false, the loop ends, and the flow moves out of the while loop to the next section of the code.

Examples Of Python While Loop

Infinite While Loop In Python

An infinite while loop in Python continuously executes a block of code as long as a specified condition remains true. Such loops are defined with a condition that never becomes false, often using True as the condition. They are useful in scenarios where a program needs to run continuously until an external event occurs.

Example.

while True:
    print("This loop will run forever.")

Output.

This loop will run forever.
This loop will run forever.
This loop will run forever.
...

To safely use infinite loops, ensure there is a way to break out of the loop, typically using a break statement. For example.

count = 0
while True:
    print("Loop iteration:", count)
    count += 1
    if count == 5:
        break

Output.

Loop iteration: 0
Loop iteration: 1
Loop iteration: 2
Loop iteration: 3
Loop iteration: 4

In this example, the loop terminates when the count reaches 5, demonstrating controlled execution within an infinite loop.

Control Statements In Python

Python While Loop With Continue Statement

A Python while loop with a continue statement facilitates skipping the rest of the loop's code block for the current iteration and immediately proceeds to the next iteration. In Python, while loops repeatedly execute a block of code as long as a given condition is true. The continue statement is used within this loop to bypass certain iterations without breaking out of the loop entirely.

Example.

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

In this example, the while loop iterates as long as i is less than 5. The continue statement is activated when i equals 3. As a result, the print statement is skipped for i = 3. The output of this code will be.

1
2
4
5

Notice that the number 3 is missing from the output, demonstrating the effect of the continue statement in a while loop.

Python While Loop With A Break Statement

Python while loop with a break statement allows for immediate loop termination upon a specified condition. The while loop iterates as long as its condition remains true. Integrating a break statement allows exit of the loop before the condition turns false. This mechanism is useful for ending loops based on external or internal factors.

For example.

count = 0
while count < 10:
    print(count)
    count += 1
    if count == 5:
        break

Output.

0
1
2
3
4

In this code, the loop begins with count set to 0 and continues until count is less than 10. The break statement is executed when count reaches 5, terminating the loop prematurely. Consequently, the numbers 0 through 4 are printed, demonstrating the effective use of break in a Python while loop.

Python While Loop With A Pass Statement

In Python, a while loop with a pass statement is used when you need a loop that does nothing in its body. The pass statement acts as a placeholder, ensuring the loop's structure is syntactically correct while intentionally not performing any action during its execution. This is particularly useful in scenarios where you need to set up a loop's structure before implementing its logic, or when creating minimal loops for timing or waiting purposes.

Example.

counter = 0
while counter < 5:
    pass  # Loop does nothing and moves to the next iteration
    counter += 1

print("Loop completed")
# Output: Loop completed

In this code, the while loop runs 5 times, but does nothing in each iteration due to the pass statement. The counter is incremented each time until it reaches 5, at which point the loop exits.

While Loop With Else

A while loop with else in Python is a control flow structure that allows for additional code to be executed when the loop condition becomes false. The else block is unique in Python loops, as it runs only if the loop terminates naturally, without being interrupted by a break statement. This makes it ideal for situations where you need to check whether a loop was completed successfully or was exited early.

Example.

count = 1
while count <= 3:
    print(count)
    count += 1
else:
    print("Loop completed")

# Output:
# 1
# 2
# 3
# Loop completed

In this code, the while loop executes as long as count is less than or equal to 3. Once count exceeds 3, the loop ends and the else block is executed, printing "Loop completed". If the loop had been broken prematurely with a break statement, the else block would not have executed.

Sentinel Controlled Statement

A Sentinel Controlled Statement in Python uses a while loop where the termination depends on a specific sentinel value. This approach is commonly used for loops where the number of iterations is not known in advance. The sentinel value acts as a signal to end the loop, typically when processing data until a certain condition is met.

For example, consider a program that reads numbers from the user until a sentinel value of -1 is entered.

sentinel = -1
number = 0

while number != sentinel:
    number = int(input("Enter a number (or -1 to stop): "))

print("Sentinel value encountered. Loop terminated.")

In this code, the loop continues to prompt the user for input until the sentinel value (-1) is entered, which terminates the loop. This technique is particularly useful for user input or reading data streams where the end of the data is marked with a specific value.

While Loop With Boolean Values

In Python, a while loop with Boolean values is used to execute a block of code repeatedly as long as a specified Boolean condition remains true. This structure is essential for tasks that need to continue until a certain condition is met.

Consider the example of a counter-controlled loop. Here, a Boolean variable is initialized with True and the loop continues to execute until the condition becomes False. Inside the loop, logic can be implemented to eventually change the Boolean variable to False, breaking the loop.

Example.

continue_loop = True
counter = 0

while continue_loop:
    print("Counter is:", counter)
    counter += 1
    if counter >= 5:
        continue_loop = False

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

In this example, while continue_loop: initiates a loop that continues until continue_loop becomes False. The loop increments counter and prints its value each time. When counter reaches 5, continue_loop is set to False, terminating the loop.

Python While Loop With Python List

In Python, a while loop with a list allows iteration as long as a certain condition is true. This is useful for processing elements of a list until a specific condition is met.

A common use case is iterating through a list and performing operations on each element. The while loop continues until it reaches the end of the list or a break condition is triggered.

Example.

my_list = [1, 2, 3, 4, 5]
index = 0

while index < len(my_list):
    print(my_list[index])
    index += 1

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

In this code, the while loop iterates over each element in my_list and prints it. The loop terminates when index is no longer less than the length of my_list.

Single Statement While Block

A single statement while block in Python allows for the execution of a single statement or a group of statements in a loop as long as a specified condition is true. This form of the while loop is useful for simple operations that require a short loop body.

Here's an example of a single statement while loop.

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

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

In this example, print(count) and count += 1 are executed in a loop until count is no longer less than 5. The semicolon ; is used to separate the two statements. This kind of loop makes the code compact and concise, particularly for simple iterations.

You can also check these blogs:

  1. Python Break Statement