The else Statement with while in Python

The else Statement with while

Overview

In Python, the else statement can be used with loops (for and while). When used with a while loop, the else block is executed after the loop terminates, but only if the loop terminates normally. If the loop is terminated by a break statement, the else block is skipped.

Syntax

Here is the basic syntax for using else with a while loop: 

while condition:
    # Loop body
    if break_condition:
        break
else:
    # Code to execute after the loop

 How It Works

  • Normal Termination: If the while loop terminates due to the condition becoming False (i.e., it finishes all iterations without hitting a break), the else block is executed.
  • Break Termination: If the while loop is terminated by a break statement, the else block is not executed.

Example 1: Normal Termination 

i = 0
while i < 3:
    print(f"i is {i}")
    i += 1
else:
    print("Loop terminated normally.")
# Output:
# i is 0
# i is 1
# i is 2
# Loop terminated normally.

 Explanation:

  • The while loop increments i and prints its value until i is no longer less than 3.
  • Once i reaches 3, the loop condition becomes False, and the else block is executed.

Example 2: Terminated by break 

i = 0
while i < 5:
    if i == 3:
        break
    print(f"i is {i}")
    i += 1
else:
    print("Loop terminated normally.")
# Output:
# i is 0
# i is 1
# i is 2

 Explanation:

  • The while loop continues as long as i is less than 5.
  • When i equals 3, the break statement is executed, which immediately exits the loop.
  • Since the loop was terminated by break, the else block is not executed.

Common Use Cases

  • Search or Validation Loops:
    • When searching for an item or validating a condition, you may use else to handle cases where the item or condition is not found.

Example: 

numbers = [1, 2, 4, 6, 8]
target = 3
i = 0
while i < len(numbers):
    if numbers[i] == target:
        print("Target found!")
        break
    i += 1
else:
    print("Target not found.")

Explanation:

    • The loop searches for the target in the numbers list.
    • If the loop completes without finding the target (i.e., without a break), the else block prints “Target not found.”
  • Processing Until Completion:
    • Use else to perform final actions after a loop completes successfully without interruption.

Example: 

count = 0
while count < 10:
    print(f"Count is {count}")
    count += 1
else:
    print("All numbers processed.")

Explanation:

    • The loop processes numbers from 0 to 9.
    • After completing all iterations, the else block is executed to indicate that all numbers have been processed.

Key Points

  • else and break:
    • The else block will not execute if the loop is terminated by a break statement.
  • Readability:
    • Using else with loops can make certain algorithms more readable by clearly separating the normal end of the loop from cases where the loop is interrupted.
  • Use Cases:
    • It is particularly useful when dealing with searches or validations where the loop may end either by completion or by an early exit due to a condition.

Summary

The else statement with a while loop in Python provides a way to execute a block of code when the loop terminates normally. It is not executed if the loop is exited via a break statement. This can be particularly useful for situations like searches, validations, or any case where you need to handle normal completion and early termination differently.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Facebook
Twitter
LinkedIn
WhatsApp
Email
Print