Python for loops

Jeremiah Taguta (BSc in Computer Science, Masters in Information Systems)
Published on 20-11-2023
Mastering the Art of For Loops in Python Programming: Structure, Range Function and its Start, Stop and Step Arguments, Break and Continue Statements with Detailed Examples


Introduction

There are situations where we have to repeat something several times, which can be accomplished by using a loop, for instance, a for loop. In this article, I explore the use of a for loop, its structure, in, iterator variable, continue, and break statements. I also explain the range function and its application in for-loops. Included are also examples of the use of for-loops.

The for loop is a count-controlled loop.

If we want to display "Hello, World" five times manually, we could do the following:

print("Hello, World")
print("Hello, World")
print("Hello, World")
print("Hello, World")
print("Hello, World")

Looking at the above example, imagine if we had to display "Hello, World" 100 times. It would take more sweat to implement that. To solve this challenge, we may use a for loop.

1. For loop structure

for iterator_variable in range( number of times to repeat):
    body (statements to be repeated)
more code

a. The range function

This is a built-in Python function. It is used to generate a sequence of numbers within a specified range. These numbers determine the number of times the body will be repeated. 

Its structure is as follows:

range(start, stop, step)

Therange() function generates a sequence of integer numbers based on the provided startstop, and step values. This sequence is generated once, not on every iteration of the loop. It generates the sequence of numbers from start to stop -1, incrementing or decrementing by the step value. In other words, when the range function is called, it has to be given arguments including a start value, if none is given, the default is 0; a stop value which is compulsory; and a step value; if none is given, the default is +1. 

As an emphasis, the start, stop and step arguments should be integers, that is, positive or negative whole numbers. If the start value is smaller than the stop value, the step value should be positive, thus incrementing, and the reverse is true.

Since therange() function returns an iterable object, if you need to use the generated sequence as a list or other data structure, you can convert it using list() or another appropriate constructor, respectively, as explained in my Python Type Casting article. See below example:

1 print("Range: ", range(10))
2 # convert the generated sequence to a list and display
3 print("List of 0-9: ", list(range(10)))  

The output of line 1 is a range, Range:  range(0, 10) and line 3 is a list with numbers,0-9:  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

b. How the For loop works 

As shown in the for-loop structure above, the for and in should be in lowercase. The iterator_variable is the one whose value is going to change for every iteration. The for statement header ends with a :. The range function has been discussed above. The body of the for loop should be indented. The body is what will be repeated a certain number of times as stipulated in the range function.

The in operator is not used for testing membership. Instead, it is used to iterate over the elements of an iterable data structure, such as a list, tuple, string, or other sequence. The in operator in a for loop sets up an iteration process, allowing you to loop through each element in the iterable.

The iterator_variable is initially assigned the first value in the generated sequence (the range function start argument).

On each iteration of the loop, the iterator variable value is updated to the next value in the sequence. It is not generated again, it takes the next value from the pre-generated sequence.

The loop continues until the loop variable reaches the last value in the pre-generated sequence, i.e. the range function stop argument value less 1, at which point the loop terminates.

Once the loop is finished iterating, the next code outside its body, represented by more code, is implemented

2. Program to print numbers between 0 and 9 inclusive one by one

In the below example, line 1 will be executed then the for loop will be run on line 2. This program uses the range(10) to generate a sequence of numbers 0 -9 as seen in section 1(b). The iterator_variable, i, in the below example, line 2, will be initialised to a start value as generated by the range function, in our case none is given, hence 0.  0 will thus be printed by line 3. For the next iteration, i will be 1 as our step is not given, hence default is 1, (0+1=1). 1 will be printed, and the next iteration takes place, with i being assigned a 2, thus 2 will be displayed. This goes on and on until i become a 9, which will be displayed. Since i  will be the last generated number of our sequence, this will mark the last iteration of our loop and any code after the loop's body will be executed.

i remains a 9 because, in Python and other programming languages, the loop variable retains its value after the loop has finished executing. In other words, i retains its value of 9 because it was the last value assigned to it within the loop. To make this clear, i is assigned from the first generated number, start,  up to the last generated number, stop - 1. i is not generated for every iteration, it is updated to take the next value in the already generated sequence as explained before.  See below example:

1 print("Before for loop")
2 for i in range (10):
3     print(i)
4 print("i value after loop = ", i )

The output for the above code will be Before for loop, 0,1, 2, 3, 4, 5, 6,7, 8, 9 and i value after loop =  9 with each of these on its line. Any code above the for loop is run before it and any code after the loop will run after it as seen by the output of lines 1 and 4 above.

To explain how i is assigned, the below code assigned a 5 to i but during iteration, i started from 0 and not 5. Thus, i is assigned a value only and only from the pre-generated sequence.

i = 5
for i in range(10):
    print(i)

The output will be 0,123456,789 with each of these on its line. One could argue that the in is a membership operator, if so, a 5 is supposed to be shown first as it is in the generated sequence, but alas, it doesn't work like a membership operator in this circumstance.

3. A program to display "Hello, World" five times

To display "Hello, World" five times using a for loop takes only two lines as shown below. Even a million printing of the same takes these two lines. All that has to be changed is the range. That's how powerful for-loops are. For every value of j from 0 to 4, "Hello, World" is printed.

for j in range (5):
   print("Hello, World")

4. A program to display 2 - 7 inclusive in one print line

Our start and stop values will be a 2 and 8 respectively as seen below:

1 print("Numbers (2-7):", end=" ")
2 for j in range (2,8):
3    print(j, end=" ")

The output will be "Numbers (2-7): 2 3 4 5 6 7 ". The outputs from line 1 and iterations of line 3 are on one line or row due to the end argument of our print statements. You may see my printing tutorial for more on this.

5. A program to display even numbers from 100 to 90 

a. Method 1

To display even numbers from 100 to 90, we need to use a start value of 100 and a negative step value of -2 as seen below. That way the range generates a sequence of even numbers. We have to use an 89 as our stop value as seen in line 2 below so the the last generated number of the sequence could be 89 +1 thus 90. Yes, the last value in the generated sequence is stop plus one become we are iterating from a bigger to a smaller number. See below example:

1 print("Even numbers from 100 to 90: ") 
2 for k in the range (100, 89, -2):
3    print(k)

The output for the above program will be Even numbers from 100 to 90 and 100, 98, 96, 94,92 and 90 with each of the numbers on its line.

b. Method 2

We can write a solution to this problem by generating numbers from 100 to 90 with a step of -1, line 2 below, but displaying only even numbers using decision-making, as in line 3 below. If you aren't conversant with decision making check my simple decision-making and complex decision-making tutorials. You may put if elif else statements in loops or in any code when necessary and vice-versa. Only a number divisible by 2, thus an even number, will be displayed as seen below.

1 print("(M2) Even numbers from 100 to 90: ")
2 for k in the range (100, 89, -1):
3    if k % 2 == 0:
4       print(k)

Our output will be Even numbers from 100 to 90:  100989694,92 and 90 with each of these on a new print line.

c. Method 1 vs Method 2

Which of these two methods is best? The first depends on the start and step values, if start and step values are even numbers, then even numbers will be displayed, if one of them is odd, then the generated sequence will be odd numbers, thus odd and not even numbers will be displayed. Try that and see. Yet the second method works with odd or even start and step values by checking if a number is even before displaying it hence it's the best of these 2.

6. A program to sum and average numbers, and count odd numbers between a user's start and end value

We have to get 2 integers from the user. Assign them to start and stop values, with smaller being start and bigger being stop. The step will be the default, 1. You may do the opposite but the step should be negative -1.  We also need to initialise our odd number and all numbers counter to 0. 

All numbers counter will be incremented for every iteration while the odd number counter is incremented only if a number is odd and, thus, has a remainder which is not a 0 if divided by 2.

The total variable is initialised to 0 and is overwritten for every iteration with the sum of the old total value and current iterator variable value stored in i. We will then calculate our average by dividing the total of our numbers stored in total the variable by the number of numbers between start and stop values. 

For our iterations, our stop value needs to be stop value + 1 so that the user stop value is included in the operation. See the code below and read the comments for explanations.

# fetch user numbers
num1 = int(input("Enter start value: "))
num2 = int(input("Enter stop value: "))
# assign the start and stop values 
if num1 > num2 : 
    start, stop = num2, num1
else:
    start, stop = num1, num2
# initialise variables
odd_count = 0
num_count = 0
total = 0

for i in range(start, stop +1):
    # increment all nums count
    num_count = num_count + 1
    # update total
    total = total + i
    # check if i is odd and increment odd count
    if i % 2 != 0:
        odd_count = odd_count + 1
# calculate average
average = total / num_count
# display results
print("For nums between", start, "and", stop)
print("Sum is =", total,"Avg", average)
print("Num of odd nums:", odd_count)

The output, for instance, if you put a 1 and 10 will be: For nums between 1 and 10, Sum is = 55 Avg = 5.5, and  Num of odd nums: 5 with each of these on a new line.

7. Using the break and continue statements

The continue statement is used to skip the execution of the instructions or code in a loop after it. Its placement position is therefore important.

The break statement is used to stop further iterations even if the loop isn't done iterating or the iterator variable hasn't reached the stop value -1.

The following 2 programs will not execute line 3 because it's after the continue or break statement thus for every iteration, it continues or breaks on line 2. Therefore, no output is shown.

1 for i in range (1,10):
2     continue
3     print(i)
1 for i in range (1,10):
2     break
3     print(i)

In the code below, line 3, a continue statement, serves no purpose as line 2 will be executed, while line 4 is ignored for every iteration. If one doesn't want line 4 to be executed, why include it? The output is 0,123456,789

1 for i in range (1,10):
2     print(i)
3     continue
4     print("Hello, World")

In the example below, after printing a 1, the loop stops iteration, and line 4 is never run. If we want the code to run once, why use a for loop?

1 for i in range (1,10):
2     print(i)
3     break
4     print("Hello, Wolrd")

The dilemmas explained above have to be avoided as the loops will not have any purpose. A break or continue should thus be implemented if a certain condition is met, hence the use of decision-making as seen below in lines 2 and 5.

1 for i in range (1,10):
2     if i==3:
3         continue
4     print(i)

5     if i == 7:
6         break  

The output for the above code will be 1 2 4 5 6 7 with each number on its line. As you can see, when i becomes a 3, line 4 wasn't executed due to the continue statement on line 3 hence a 3 isn't on the output. When i becomes a 7, the loop stops iterating because of the break statement on line 6. This means that break and continue statements need to be used when certain conditions are met.

Having discussed the for loop, range function and its start, stop and step values, and break and continue statements, this marks the end of this piece. I hope you have also written your copies of these programs to understand them better.

Thanks for reading. If you have any questions, feel free to ask in the comments section, I'll gladly help. Check out my programming tutorials on YouTube and don't forget to subscribe, comment, like, and share on both YouTube and on this Blog. Lets code together!!!

152 Like

Drop your comment

© Copyright 2023 Jeremiah Taguta. All Rights Reserved.

Product of ‌

Jeremiah Taguta T/A Charis Technologies