Introduction

Python programming language provides a comprehensive range of control structures that programmers can use to manage the flow of their programs. One of the essential control structures in Python is the for...else loop. The for...else loop in Python is used to iterate over a sequence like lists, tuples, or strings. It allows the programmer to execute a block of code repeatedly for each item in the sequence. Additionally, the loop also enables the programmer to specify the code that should execute once the loop has iterated through the entire sequence. In this tutorial, we will introduce you to the for...else loop, how it works, and how you can use it in your Python programs.

Table of Contents :

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

Python for...else loop

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

for item in iterable_object:
   # code to process item 
else:
   # else code statements
   
   
  • The code in the else block is executed only when these three conditions are met :
    • no more items are left in the iterable object.
    • the execution of the for loop finishes normally.
    • no break statement was executed within the for loop.
  • The for..else statement helps in making the code shorter and cleaner.
  • The for..else statement can replace many if statements and flags, hence shortening the code.

Control flow of for..else statement :

  • The items of the iterable_object are executed one by one.
  • The code within the for loop is executed for each item.
  • If a break statement is executed for some item, the for loop ends - the else block is not executed.
  • If all the items are iterated and the for loop ends normally - the else block is executed.
  • Code Sample :

for index in range(2, 5):
	sqr = index ** 2
	print(f"Value of index = {index}")
	print(f"Square of index = {sqr}")
	print()
else:
	print("This is the Else block")
	print("For loop completed normally")
	
# 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


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

for index in range(2, 5):
	sqr = index ** 2
	print(f"Value of index = {index}")
	print(f"Square of index = {sqr}")
	print()
	print("Executing break statement")
	break
else:
	print("This is the Else block")
	print("For loop completed normally")
	

# Output 

# Value of index = 2
# Square of index = 4

# Executing break statement

Prev. Tutorial : While loops

Next Tutorial : While...else loop