While Else

Introduction:

  • The While Else construct in Python allows you to execute an else block when the while condition becomes false. The syntax and working are similar to the while loop but include an additional else block that runs if the loop completes without encountering a break statement.

Syntax:

python
while condition:
    statement(s)
else:
    statement(s)

Examples:

  1. Simple Example of While Else:
    • This example demonstrates a while loop with an else block.

      python
      i = 0
      while i < 5:
          print(i)
          i += 1
      else:
          print('Printing task is done.')
      
    • Output:

      0
      1
      2
      3
      4
      Printing task is done.
      
  2. While Else with File Reading:
    • This example uses an else block to close a file after reading it line by line in the while block.

      python
      f = open("sample.txt", "r")
      while True:
          line = f.readline()
          if not line:
              break
          print(line.strip())
      else:
          f.close()
      
    • Output:

      Hi User!
      Welcome to Python Examples.
      Continue Exploring.
      

Exercises:

  1. Simple While Else Loop:
    • Write a program to print numbers from 1 to 5 using a while loop with an else block that prints a completion message.

      python
      i = 1
      while i <= 5:
          print(i)
          i += 1
      else:
          print('Loop has finished.')
      
  2. While Else with Condition:
    • Write a program to check for even numbers from 1 to 10 using a while else loop. If an even number is found, break the loop; otherwise, print a completion message.

      python
      i = 1
      while i <= 10:
          if i % 2 == 0:
              print(f'Found an even number: {i}')
              break
          i += 1
      else:
          print('No even number found.')
      

Summary:

  • In this tutorial, we learned about the While Else construct in Python, its syntax, and how to use it in programs. Practice using While Else to perform actions after a while loop completes without encountering a break statement!