Introduction

Loops are an important concept in programming as they allow us to repeat a set of instructions multiple times. The while loop is a conditional loop in Python that repeats a set of instructions as long as a certain condition is met. The else clause in a while loop adds an additional block of code that executes once the loop completes, but only if the loop is not terminated by a break statement. In this tutorial, we will discuss the syntax and usage of the while...else loop, and provide examples to illustrate how it can be applied in practical scenarios. Let's get started!

Table of Contents :

  • Python while...else loop
  • Control flow of while..else statement 

Python while...else loop

  • We have already read about the while loop in Python.
  • There is an optional else clause of the while loop statement.
  • The basic syntax of while...else is as follows :

while logical_condition:
   # code to process Logic 
else:
   # else code statements
   
   
  • The code in the else block is executed only when these three conditions are met - 
    • the loop condition of while loop becomes false.
    • the execution of the while loop finishes normally.
    • no break statement was executed within the while loop.
  • The while..else statement helps in making the code shorter and cleaner.
  • The while..else statement can replace many if statements and flags, hence shortening the code.

Control flow of while..else statement :

  •  The logical condition is evaluated before each iteration.
  • If the condition is true - the code in the while loop is executed.
  • If a break statement is executed in an iteration, the while loop ends  - the else block is not executed.
  • If the while loop ends only when the loop condition becomes False i.e. the loop ends normally - the else block is executed.
  • Code Sample : 

index = 2
while index < 5:
	sqr = index ** 2
	print(f"Value of index = {index}")
	print(f"Square of index = {sqr}")
	print()
	index += 1
else:
	print("This is the Else block")
	print("For loop completed normally")
	print(f"Value of index = {index}")
	
# Output
# Value of index = 2
# Square of index = 4

# Value of index = 3
# Square of index = 9

# Value of index = 4
# Square of index = 16

# This is the Else block
# For loop completed normally
# Value of index = 5


	

 

  • Code Sample : When execution of while loop does not complete normally or a break statement is executed in between, the else block is not executed.

index = 2
while index < 5:
	sqr = index ** 2
	print(f"Value of index = {index}")
	print(f"Square of index = {sqr}")
	print()
	index += 1
	print("Executing break statement")
	break
else:
	print("This is the Else block")
	print("For loop completed normally")
	print(f"Value of index = {index}")
	
# Output
# Value of index = 2
# Square of index = 4

# Executing break statement

Prev. Tutorial : For...else loop

Next Tutorial : Do...while imitation