A quick overview of how to write better Python loops
Loops in Python
forloopwhileloop
Let’s learn how to use control statements like break, continue, and else clauses in the for loop and the while loop.
‘for’ Statement
The for statement is used to iterate over the elements of a sequence (such as a string, tuple, or list) or any other iterable object.
for item in iterable:
suite
- The iterable is evaluated only once. An iterator is created for the result of that iterable.
- The suite is then executed once for each item provided by the iterator, in the order returned by the iterator.
- When the items are exhausted, the loop terminates.
Example 1. ‘for’ loop
for i in range(1,6):
print (i)
'''
Output:
1
2
3
4
5
'''
The for loop may have control statements like break andcontinue, or the else clause.
There may be a situation in which you may need to exit a loop completely for a particular condition or you want to skip a part of the loop and start the next execution. The for loop and while loop have control statements break and continue to handle these situations.
‘break’ Statement
The break statement breaks out of the innermost enclosing for loop.
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
The break statement is used to terminate the execution of the for loop or while loop, and the control goes to the statement after the body of the for loop.
Example 2. Using the ‘break’ statement in a ‘for’ loop
- The
forloop will iterate through the iterable. - If the item in the iterable is
3, it will break the loop and the control will go to the statement after theforloop, i.e.,print (“Outside the loop”). - If the item is not equal to
3, it will print the value, and theforloop will continue until all the items are exhausted.
for i in [1,2,3,4,5]:
if i==3:
break
print (i)
print ("Outside the loop")
'''
Output:
1
2
Outside the loop
'''
Example 3. Using the ‘break’ statement in a ‘for’ loop having an ‘else’ clause
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
Example:
In the for loop, when the condition i==3 is satisfied, it will break the for loop, and the control will go to the statement after the body of the for loop, i.e., print (“Outside the for loop”).
The else clause is also skipped.
for i in [1,2,3,4,5]:
if i==3:
break
print (i)
else:
print ("for loop is done")
print ("Outside the for loop")
'''
Output:
1
2
Outside the for loop
'''
‘continue’ Statement
The continue statement continues with the next iteration of the loop.
A continue statement executed in the first suite skips the rest of the suite and continues with the next item or with the else clause, if there is no next item.
Example 4. Using the ‘continue’ statement in a ‘for’ loop
- The
forloop will iterate through the iterable. - If the item in the iterable is
3, it will continue theforloop and won’t execute the rest of the suite, i.e.,print (i). - So element
3will be skipped. - The
forloop will continue execution from the next element. - The
elseclause is also executed.
for i in [1,2,3,4,5]:
if i==3:
continue
print (i)
else:
print ("for loop is done")
print ("Outside the for loop")
'''
1
2
4
5
for loop is done
Outside the for loop
'''
‘else’ Clause in ‘for’ Loop
Loop statements may have an else clause. It is executed when the for loop terminates through exhaustion of the iterable — but not when the loop is terminated by a break statement.
Example 5. Using the ‘else’ clause in a ‘for’ loop
The else clause is executed when the for loop terminates after the exhaustion of the iterable.
for i in [1,2,3,4,5]:
print (i)
else:
print ("for loop is done")
print ("Outside the for loop")
'''
1
2
3
4
5
for loop is done
Outside the for loop
'''
Example 6. Using the ‘else’ clause in a ‘for’ loop with the ‘break’ statement
The else clause is not executed when the for loop is terminated by a break statement.
for i in [1,2,3,4,5]:
if i==3:
break
print (i)
else:
print ("for loop is done")
print ("Outside the for loop")
'''
1
2
Outside the for loop
'''
Example 7. Using the ‘else’ clause in a ‘for’ loop with the ‘continue’ statement
The else clause is also executed.
for i in [1,2,3,4,5]:
if i==3:
continue
print (i)
else:
print ("for loop is done")
print ("Outside the for loop")
'''
1
2
4
5
for loop is done
Outside the for loop
'''
Example 8. Using the ‘break’ statement and ‘else’ clause in a ‘for’ loop
Search the particular element in the list. If it exists, break the loop and return the index of the element; else return “Not found.”
l1=[1,3,5,7,9]
def findindex(x,l1):
for index,item in enumerate(l1):
if item==x:
return index
break
else:
return "Not found"
print (findindex(5,l1))
#Output:2
print (findindex(10,l1))
#Output:Not found
‘while’ Loop
The while statement is used for repeated execution as long as an expression is true.
while expression:
suite
else:
suite
This repeatedly tests the expression and, if it is true, executes the first suite. If the expression is false (which it may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.
Example 9. Using the ‘else’ clause in a ‘while’ loop
The while loop is executed until the condition i<5 is False.
The else clause is executed after the condition is False.
i=0
while i<5:
print (i)
i+=1
else:
print ("Element is not less than 5")
'''
Output:
0
1
2
3
4
Element is not less than 5
'''
‘break’ Statement
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
Example 10. Using the ‘break’ statement and ‘else’ clause in a ‘while’ loop
The break statement terminates the loop and the else clause is not executed.
i=0
while i<5:
print (i)
i+=1
if i==3:
break
else:
print ("Element is not less than 5")
'''
Output:
0
1
2
'''
‘continue’ Statement
A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
Example 11. Using the ‘continue’ statement and ‘else’ clause in a ‘while’ loop
The continue statement skips the part of the suite when the condition i==3 is True. The control goes back to the while loop again.
The else clause is also executed.
i=0
while i<5:
print (i)
i+=1
if i==3:
continue
else:
print ("Element is not less than 5")
'''
Output:
0
1
2
3
4
Element is not less than 5
'''
Conclusion
- Python version used is 3.8.1.
- The
breakstatement will terminate the loop (bothforandwhile). Theelseclause is not executed. - The
continuestatement will skip the rest of the suite and continue with the next item or with theelseclause, if there is no next item. - The
elseclause is executed when theforloop terminates after the exhaustion of the iterable.
Resources (Python Documentation)
break and continue Statements, and else Clauses on Loops
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee