Python for-else Loops



Python - For Else Loop

Python supports having an "else" statement associated with a "for" loop statement. If the "else" statement is used with a "for" loop, the "else" statement is executed when the sequence is exhausted before the control shifts to the main line of execution.

Flowchart of For Else Loop

The following flow diagram illustrates how to use else statement with for loop −

for-else

Syntax of For Else Loop

The following is the syntax of for loop with optional else clause -

for variable_name in iterable:
 #stmts in the loop
 .
 .
 .
else:
 #stmts in else clause
 .
 .

Example of For Else Loop

The following example illustrates the combination of an else statement with a for statement in Python. Till the count is less than 5, the iteration count is printed. As it becomes 5, the print statement in else block is executed, before the control is passed to the next statement in the main program.

for count in range(6):
   print ("Iteration no. {}".format(count))
else:
   print ("for loop over. Now in else block")
print ("End of for loop")

On executing, this code will produce the following output

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
for loop over. Now in else block
End of for loop

Using else statement with for loop in python

In other languages, the else functionality is only provided in if-else pairs. But Python allows us to implement the else functionality with for loops as well.

The else functionality is available for use only when the loop terminates normally. In case of forceful termination of the loop else statement is overlooked by the interpreter and hence its execution is skipped.

.

NOTE: When the loop is not terminated by a break statement, the else block immediately after for/while is executed.

Method 1: For-Else Construct with normal termination (without break statement)

Example

The following program shows how to use the else statement with for loop −

for i in ['T','P']:
   print(i)
else:
   # Loop else statement
   # there is no break statement in for loop, hence else part gets executed directly
   print("ForLoop-else statement successfully executed")

On executing, the above program will generate the following output −

T
P
ForLoop-else statement successfully executed

Method 2: For-Else Construct with forceful termination (with break statement)

Example

The following program shows how else conditions work in case of a break statement −

for i in ['T','P']:
   print(i)
   break
else:
   # Loop else statement
   # terminated after 1st iteration due to break statement in for loop
   print("Loop-else statement successfully executed")

On executing, the above program will generate the following output −

T

Explanation

This type of else is only useful if there is an if condition inside the loop that is dependent on the loop variable in some way.

In Method 1, the loop else statement is executed since the for loop terminates normally after iterating over the list['T','P']. However, in Method 2, the loop-else statement is not executed since the loop is forcedly stopped using jump statements such as break.

These Methods clearly show that when the loop is forcedly terminated, the loop-else expression is not executed.

Now consider an example in which the loop-else statement is performed in some conditions but not in others.

Method 3: For-Else Construct with break statement and if conditions

Example

The following program shows how else conditions works in case of break statement and conditional statements

# creating a function to check whether the list item is a positive
# or a negative number
def positive_or_negative():
   # traversing in a list
   for i in [5,6,7]:
   # checking whether the list element is greater than 0
      if i>=0:
         # printing positive number if it is greater than or equal to 0
         print ("Positive number")
      else:
         # Else printing Negative number and breaking the loop
         print ("Negative number")
         break
   # Else statement of the for loop
   else:
      # Statement inside the else block
      print ("Loop-else Executed")
# Calling the above-created function
positive_or_negative()

On executing, the above program will generate the following output −

Positive number
Positive number
Positive number
Loop-else Executed

Using else statement with while loop in python

Else-While without break statement

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Initialized k value with 0.

  • Using a while loop to traverse until the specified condition is true(until k<8).

  • Incrementing the k value by 1, since we don't want to execute the while loop infinite times.

  • Print k value.

  • Else block gets executed when the condition fails/becomes false i.e when the k value becomes 8.

Example

The following program demonstrates the use of the else statement in the while loop

k=0
# traversing until the condition is true(k<8)
while k<8:
   # incrementing the k value by 1
   k+=1
   # printing k value
   print("k =",k)
else:
   # else block gets executed when the condition fails(becomes false)
   print("This is an else block")

On executing, the above program will generate the following output −

k = 1
k = 2
k = 3
k = 4
k = 5
k = 6
k = 7
k = 8
This is an else block

Using Else statement in While loop with a break statement

Example

# creating a function that checks if the
# list passed to it contains an even number
def hasEvenNumber(l):

   # getting the list length
   n = len(l)
   # intializing a variable with 0(index)
   i = 0
   # traversing the loop until the I value is less than the list length
   while i < n:
   # checking whether the corresponding index element of a list is even

      if l[i] % 2 == 0:

         # printing some text, if the condition is true
         print("The input list contains an even number")

         # giving a break statement/break the loop

         break

         # incrementing the I (index) value by 1

      i += 1

   else:
   # Else print "The input list doesn't contain an even number"
   # It executes Only if the break is NEVER met and the loop is terminated after all iterations

      print("The input list doesn't contain an even number")

# calling the hasEvenNumber() function by passing input list 1 as an argument
print("For Input list 1:")
hasEvenNumber([3, 9, 4, 5])
# calling the hasEvenNumber() function by passing input list 2 as an argument
print("For Input list 2:")
hasEvenNumber([7, 3, 5, 1])

On executing, the above program will generate the following output −

For Input list 1:
The input list contains an even number
For Input list 2:
The input list doesn't contain an even number

Nested Loops in Python

Python programming language allows the use of one loop inside another loop. The following section shows a few examples to illustrate the concept.

Syntax

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
      statements(s)

The syntax for a nested while loop statement in Python programming language is as follows −

while expression:
   while expression:
      statement(s)
   statement(s)

A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example a for loop can be inside a while loop or vice versa.

Example

The following program uses a nested-for loop to display multiplication tables from 1-10.

for i in range(1,11):
   for j in range(1,11):
      k=i*j
      print ("{:3d}".format(k), end=' ')
   print()

The print() function inner loop has end=' ' which appends a space instead of default newline. Hence, the numbers will appear in one row.

The last print() will be executed at the end of inner for loop.

When the above code is executed, it produces the following output

  1   2   3   4   5   6   7   8   9  10 
  2   4   6   8  10  12  14  16  18  20 
  3   6   9  12  15  18  21  24  27  30 
  4   8  12  16  20  24  28  32  36  40 
  5  10  15  20  25  30  35  40  45  50 
  6  12  18  24  30  36  42  48  54  60 
  7  14  21  28  35  42  49  56  63  70 
  8  16  24  32  40  48  56  64  72  80 
  9  18  27  36  45  54  63  72  81  90 
 10  20  30  40  50  60  70  80  90 100 
Advertisements