Change language

Using else conditional statement with for loop in python

| | |

In most programming languages ​​(C / C++, Java, etc.), the use of the else statement has been limited to conditional if statements. But Python also allows us to use the else clause with for loops.

The else block just after for / while is executed only when the loop is NOT terminated by a break statement.

The rest of the block is executed in the following Python 3.x program:

for i in range ( 1 , 4 ):

print (i)

else # Done because there is no break for

pri nt ( "No Break" )

Exit:

 1 2 3 No Break 

In other Python 3.x programs, the block is NOT executed:

for i in range ( 1 , 4 ):

print (i)

break

else : # Not executed because there is a break

  print ( " No Break " )

Output:

 1 

This else type is useful only if the loop contains an if condition that somehow depends on the loop variable.

In the following example, the else statement will be executed only if none of the array elements are even, i.e. if the statement has not been executed for any iteration. Therefore, for the array [1, 9, 8], the if is executed in the third iteration of the loop and, therefore, the rest after the for loop is ignored. In the case of the array [1, 3, 5] if is not executed for any iteration and therefore the else after the loop.

# Python 3.x program for checking if the array consists of
even number

def contains_even_number (l):

for ele in l:

  if ele % 2 = = 0 :

print "list contains an even number" )

break

  

# This is still only done if break NEVER

Achieved # and the loop ends after all iterations.

else

print ( "list does not contain an even number" )

 
# Driver code

print ( "For List 1:" )

contains_even_number ([ 1 , 9 , 8 ])

print ( " For List 2: " )

contains_even_number ([ 1 , 3 , 5 ])

Output:

 For List 1: list contains an even number For List 2: list does not contain an even number 

As exercise predict the result of the next program.

count  = 0

while (count & lt;  1 ): 

  count = count + 1

print (count)

break

else :

print ( "No Break" )

This article is courtesy of Harshit Agrawal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically