PYTHON - for-else Loops
Python for-else Loops
Python - For Else Loop
Python supports an optionalelse blockto be associated with afor loop. If aelse blockis used with afor loop, it is executed only when the for loop terminates normally.
The for loop terminates normally when it completes all its iterations without encountering abreak statement, which allows us to exit the loop when a certain condition is met.
Flowchart of For Else Loop
The following flowchart illustrates use offor-else loop−
Syntax of For Else Loop
Following is the syntax of for loop with optional else block −
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 inPython. 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 followingoutput−
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 loopFor-Else Construct without break statement
As mentioned earlier in this tutorial, the else block executes only when the loop terminates normally i.e. without using break statement.
Example
In the following program, we use the for-else loop without break statement.
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 executedFor-Else Construct with break statement
In case of forceful termination (by using break statement) of the loop, else statement is overlooked by the interpreter and hence its execution is skipped.
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
TFor-Else with break statement and if conditions
If we usefor-elseconstruct withbreak statementandif condition, thefor loopwill iterate over the iterators and within this loop, you can use anif blockto check for a specific condition. If the loop completes without encountering abreak statement, the code in the else block is executed.
Example
The following program shows how else conditions works in case of break statement andconditional 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 ExecutedUsing else statement with while loop in python
Else-While without break statement
pAlgorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task
<ul class="list">
<li>pInitialized k value with 0.</li>
<li>pUsing a while loop to traverse until the specified condition is true(until k<8).</li>
<li>pIncrementing the k value by 1, since we don’t want to execute the while loop infinite times. </li>
<li>pPrint k value.</li>
<li>pElse block gets executed when the condition fails/becomes false i.e when the k value becomes 8. </li>
</ul>
Example
The following program demonstrates the use of the else statement in the while loop
<pre class="demo-code notranslate language-python" data-lang="python3">
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”)
</pre>
On executing, the above program will generate the following output
<pre class="result notranslate">k = 1
k = 2
k = 3
k = 4
k = 5
k = 6
k = 7
k = 8
This is an else block
</pre>
Using Else statement in While loop with a break statement
Example
<pre class="demo-code notranslate language-python" data-lang="python3">
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])
</pre>
On executing, the above program will generate the following output
<pre class="result notranslate">For Input list 1:
The input list contains an even number
For Input list 2:
The input list doesn’t contain an even number
</pre>
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
<pre class="just-code notranslate language-python" data-lang="python">
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
</pre>
The syntax for a nested while loop statement in Python programming language is as follows −
<pre class="just-code notranslate language-python" data-lang="python">
while expression:
while expression:
statement(s)
statement(s)
</pre>
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.
<pre class="demo-code notranslate language-python" data-lang="python3">
for i in range(1,11):
for j in range(1,11):
k=i*j
print (”{:3d}“.format(k), end=’ ’)
print()
</pre>
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 −
<pre class="result notranslate">
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
</pre>