Table of Contents



The while Loop

The while loop in Python is used to iterate over a block of code as long as the test expression is True. We typically use the while loop when we don’t know the number of times to iterate beforehand. The syntax of a while loop is:

SYNTAX The while loop.

1while test_expression:
2    statement(s)

When the test expression evaluates to False in the process of looping, the program passes control to the line immediately following the loop. For example, to print the squares of the numbers from 1 to 10:

EXAMPLE Using the while loop.

1i=1
2while i <= 10:
3    print(i**2)
4    i += 1
5print('All numbers printed')
1
4
9
16
25
36
49
64
81
100
All numbers printed

As a more involved example, let’s compute the sum of the even numbers from 2 to 100, i.e. $2+4+6+…+98+100$. Recall that this task was solved using a for loop in a previous section .

EXAMPLE The while loop to compute sum of even numbers from 2 to 100.

1total = 0
2i = 1
3while i <= 100:
4    if i % 2 ==0:
5        total += i
6    i += 1
7print(f'Sum of all even numbers from 1 to 100 is {total}')
Sum of all even numbers from 1 to 100 is 2550
Tip: The while loop is often used in conjunction with a counter variable to keep track of the iteration number.

EXAMPLE Consider the arithmetic series $1+2+3+4+ \ldots$ How many numbers are needed to sum up to $300$?

1total = 0
2i = 1
3while total < 300:
4    total = total + i
5    print(f'+{i} : Sum = {total}')
6    i += 1
+1 : Sum = 1
+2 : Sum = 3
+3 : Sum = 6
+4 : Sum = 10
+5 : Sum = 15
+6 : Sum = 21
+7 : Sum = 28
+8 : Sum = 36
+9 : Sum = 45
+10 : Sum = 55
+11 : Sum = 66
+12 : Sum = 78
+13 : Sum = 91
+14 : Sum = 105
+15 : Sum = 120
+16 : Sum = 136
+17 : Sum = 153
+18 : Sum = 171
+19 : Sum = 190
+20 : Sum = 210
+21 : Sum = 231
+22 : Sum = 253
+23 : Sum = 276
+24 : Sum = 300

The break Statement

Recall that a while loop specifies a test condition and a block of code that is to be executed until the condition evaluates to False. Alternatively, we can end the loop explicitly with the break statement. The break statement terminates the loop containing it. Control of the program then flows to the statement immediately after the body of the loop.

Here is an example where we are trying to determine the first occurrence of the letter “i” in a word and print our its corresponding index.

EXAMPLE Determine the first occurrence of a letter in a word.

1ind = 0
2word = "terrible"
3target = "i"
4
5for letter in word:
6    if letter == target:
7        print(f'The letter {target} is found at index {ind}')
8        break
9    ind+= 1
The letter i is found at index 4

The problem with the above code is that if the given word does not contain the target letter, the index returned will always be the last index + 1 since the loop will continue all the way to the last letter of the word and the break statement is never executed.

In other words, if the specified letter isn’t contained in the word, the value of ind will become the length of the word. In this case, we can use this fact to write an if statement to indicate that the letter is not found.

EXAMPLE Determine if a letter is found in a word.

 1ind = 0
 2word = "terrible"
 3target = "f"
 4
 5for letter in word:
 6    if letter == target:
 7        print(f'The letter {target} is found at index {ind}')
 8        break
 9    ind+= 1
10
11if ind == len(word):
12    print(f'Letter {target} not found.')
Letter f not found.

for Loop with else

A for loop can have an optional else block as well. The else block is executed if the loop iterates until the end of the sequence. Since the break statement can be used to terminate a for loop, the else part is ignored. Hence, the else block of a for loop is executed if no break occurs. The syntax is:

SYNTAX The for... else loop.

1for item in sequence:
2    statement(s)
3else:
4    statement(s)

Here is the same example discussed previously but solved using a for loop with else and the break statement.

EXAMPLE Determine if a letter is found in a word using for... else loop with break.

 1ind = 0
 2word = "terrible"
 3target = "r"
 4
 5for letter in word:
 6    if letter == target:
 7        print(f'The letter {target} is found at index {ind}')
 8        break
 9    ind+= 1
10else:
11    print(f'Letter {target} not found.')
The letter r is found at index 2
Note: The `else` block of a `for` loop is executed if no `break` occurs.

while Loop with else

We note that while loops can also have an optional else block. The else code block is executed if the test expression of the while loop evaluates to False (i.e. end of the loop).

SYNTAX The while... else loop.

1while test_expression:
2    statement(s)
3else:
4    statement(s)

Here is one example. The code prints each letter of a word and its corresponding index. The loop ends with a statement that gives the total number of letters in the word.

EXAMPLE Using the while... else loop.

1ind = 0
2word = "excellent"
3
4while ind < len(word):
5    print(f'Letter "{word[ind]}" is found at index {ind}')
6    ind+= 1
7else:
8    print(f'End of Loop with a total of {ind} letters')
Letter "e" is found at index 0
Letter "x" is found at index 1
Letter "c" is found at index 2
Letter "e" is found at index 3
Letter "l" is found at index 4
Letter "l" is found at index 5
Letter "e" is found at index 6
Letter "n" is found at index 7
Letter "t" is found at index 8
End of Loop with a total of 9 letters

Here is an example using a while loop with an else block and a break statement. Recall that the while loop can be terminated with a break statement, in which case the else block is ignored. Hence, the else block of a while loop will only be executed if no break occurs and the test condition turns False.

The following determines the first occurrence of a certain letter in a word and prints our its corresponding index. This example also takes into account the possibility that the letter may not be found in the word.

EXAMPLE Determine if a letter is found in a word using the while... else loop with break.

 1ind = 0
 2word = "excellent"
 3target = "n"
 4
 5while ind < len(word):
 6    if word[ind] == target:
 7        print(f'The letter {target} is found at index {ind}')
 8        break
 9    ind+= 1
10else:
11    print(f'Letter {target} not found.')
The letter n is found at index 7

In the above example, if the specified letter is found within the word, the index will be printed, break statement executed and the loop terminated. Otherwise, if the letter is not found, the test expression turns False and the else block is executed.

Note: The `else block of a `while` loop will only be executed if no break occurs and the test condition turns False

ADVERTISEMENT

The continue Statement

The continue statement is used to skip the rest of the code within a loop for the current iteration only. The loop does not terminate but continues with the next iteration. It is typically used in conjunction with an if statement.

In the following example, we seek to find all the occurrences of a certain letter in a given word and print out the corresponding index. If the letter does not appear in the word, nothing is printed.

EXAMPLE Using for loop with if...else and continue.

1ind = 0
2word = "extraterrestrial"
3target = "t"
4
5for (ind, letter) in enumerate(word):
6    if letter != target:
7        continue
8    else:
9        print(f'Letter "{target}" is found at index {ind}')
Letter "t" is found at index 2
Letter "t" is found at index 5
Letter "t" is found at index 11

We could also have done the following. Note that we have changed the if test expression and include the continue statement in the else block.

EXAMPLE Using for loop with if...else and continue (variation).

1ind = 0
2word = "extraterrestrial"
3target = "t"
4
5for (ind, letter) in enumerate(word):
6    if letter == target:
7        print(f'Letter "{target}" is found at index {ind}')
8    else:
9        continue
Letter "t" is found at index 2
Letter "t" is found at index 5
Letter "t" is found at index 11

EXAMPLE Find all occurrences of a given letter in a certain word. Print their corresponding indices and total number of occurrences. If the letter is not found, print a statement to indicate so.

 1i = 0
 2word = "extraterrestrial"
 3target = "r"
 4
 5for (ind, letter) in enumerate(word):
 6    if letter == target:
 7        print(f'Letter "{target}" is found at index {ind}')
 8        i += 1
 9
10if i == 0:
11    print(f'Letter "{target}"" not found.')
12else:
13    print(f'The letter "{target}" appears {i} times.')
Letter "r" is found at index 3
Letter "r" is found at index 7
Letter "r" is found at index 8
Letter "r" is found at index 12
The letter "r" appears 4 times.

EXAMPLE Find and print all prime numbers (and their indices) between 2 and 50. Recall that a prime number is one which is only divisible by 1 and itself.

1lower = 2
2upper = 50
3
4for num in range(lower, upper):
5    for i in range(2, num):
6        if (num % i) == 0: # test if num if divisible by numbers other than itself
7            break          # if so, it is not prime, break the inner loop and move on to next num in the outer loop
8    else:
9        print(num)
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47