This is the last day focusing on loop basics and we will learn about an interesting feature in Python that we haven’t seen in C++ loops!
‘Else’ in loops!
In Python, there can be an else clause in loops (just like in if-else conditions). The ‘else’ clause is executed if the loop condition fails.
If there is ‘break’ in the loop and the break condition is executed, then the ‘else’ clause is skipped totally.
However, if there is ‘continue’ in the loop, and the ‘continue’ condition is executed, the ‘else’ clause is still considered.
This may be a bit confusing but is usually helpful in ‘search’ loops. If we are searching for an item and we do not find it in the loop, the else clause can be executed.
According to the official Python docs:
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
- First let’s do some revision. Look at the following code, and predict what may be the output. Then type and run to check whether you got it correct or not
for i in range(4):
print(“Value of i is %d” %i)
else:
print(“Done with iteration”)
- That was a for loop revision. Now let’s refresh our while loop concept as well as the rand number generation skill . Type and run the following. (Try to predict beforehand how the output may look like – you can’t predict the exact output as there is a random number generator, but you can figure out what the general look would be)
from random import randint #we are importing a function ‘randint’
#from a special library ‘random’
#that will help us generate random numbers
x=0
while x<4:
age= randint(20,30) # generate a number between 20 to 30
print(“age is %d” %age)
x = x+1
- Now, we will put at ‘else’ clause at the end of the while loop. Look what happens when you type and run the following
from random import randint #we are importing a function ‘randint’
#from a special library ‘random’
#that will help us generate random numbers
x=0
while x<4:
age= randint(20,30) # generate a number between 20 to 30
print(“age is %d” %age)
x = x+1
else:
print(“We are done looking at the age of %d people” %x)
- Actually, in #3, you could have not written the ‘from random import randint..’ part as you have already imported the randint function for the current kernel in your code for #2 (hopefully your kernel is not ruined as you proceeded from #2 to #3).
Ok, now we will use another function from ‘sample’ from that library ( so we have to import it) and use it on a new example to see how to use ‘else’ with a for loop. Sampling also generates random numbers, but it generate a list according to the length you request and ensures all numbers in the list are unique.
Type and run the following. Well, run it several times and see the results each time.
from random import sample # We are importing a function ‘sample’
# from a special library ‘random’
# that will help us generate a LIST of random numbers with no repetition
aRandomList=sample(range(20,30), 5) # Make a list of 5 numbers, sampling from 20 to 30
print(aRandomList)
for x in aRandomList:
print(x)
if x==27:
break
else:
print(“Nobody in the 27 Club!”)
- Now get back to while loop. Check out the simple code below. Try to predict what will be the output. Then type and run.
n = 5
while n > 0:
n = n – 1
if n == 2:
break
print(n)
else:
print(“Loop has ended”)
- EXERCISE: Modify the code in #5 by changing ONLY ONE WORD (no number) , such that your output is as follows:
4
3
1
0
Loop has ended