❮ Back

Introduction

What are loops? loops are essentially the repetition of a piece of code for a defined (or undefined) number of times. You have learnt about loops in our Pseudocode Tutorial and you must be familiar with the basic idea of its structure. If you haven't checked it out yet, please do.

Loops make it easy for programmers to write code without having to repeatedly type it out. Let's look at an example of how it can be painful to type out everything.

In [1]:
#Q: Print the first 5 natural numbers 
print(1)
print(2)
print(3)
print(4)
print(5)
1
2
3
4
5

This was only a small program. What if the task ws to print the first 100 natural numbers? You could copy-paste the print statements, but you would still have to change the numbers inside them. It's much simpler to use loops to complete tasks which require repetition. There are two loops which are used in Python: FOR and WHILE.

The For Loop

The first kind of loop we will look at is the FOR loop. It is used to iterate over a range of values or a sequence.

Let us start by looking at the syntax

In [ ]:
for '''Insert control variable''' in '''sequence/items in range''':
    '''statements inside the loop'''

The interesting thing is that we can iterate through a string. Let's suppose a string has n characters. We can use a control variable (a temporary variable whose value changes with each iteration of the loop), for example, ch, to iterate through each character in the string. For every 'x' iteration of the loop, the value of the control variable is the xth character of the string. Let me show you how.

In [2]:
##Q: Print each letter in the string "qprogrogramming" line by line
for ch in "qprogramming":
    print(ch)
    
q
p
r
o
g
r
a
m
m
i
n
g

As you can see, when we run the code, it prints each letter of the string, line by line.

We can also iterate through a sequence of numbers i.e. numbers in the form of a list

In [3]:
#Q: Print all the numbers in the sequence [3,5,6,7,8] line by line

for i in [3,5,6,7,8]: #here i is the control variable
    print(i)
3
5
6
7
8

The Range() Function

range() is a built-in function in python, i.e. it can be accessed without installing any external modules or libraries.

Let us start with its syntax

In [ ]:
range('''start value''', '''end value''', '''step value''')

Note that the value set as the end value is NOT included while using range()

Let's look at some other cool things that can be done with range()

In [4]:
#Q; Generate a list of numbers ranging from 2-6
rangelist = list(range(2,6)) #generates a list of values between 2 and 6
print(rangelist)
[2, 3, 4, 5]
In [5]:
#Generate a list of every third value between 0 and 20
rangelist2 = list(range(0,20,3)) #generates a list of every third value between 0 and 20
print(rangelist2)
[0, 3, 6, 9, 12, 15, 18]

Let us now incorporate range() with our for loop

In [6]:
#Q: Print all the natural numbers in the range 0-5
for i in range(0,5): #iterates through the values 0-5 and prints them
    print(i)
0
1
2
3
4
In [7]:
#Q: Print every second number in the range 0-6
for i in range(0,6,2): #iterates through every second value between 0 and 6 and prints them
    print(i)
0
2
4

Great! We're done with the for loop. Let's now move on to the while loop

The While Loop

The while loop is another kind of loop which is used to repeat code as long as a condition is satisfied. Let's start by looking at the syntax.

In [ ]:
while '''condition''':
    '''code to be repeated'''

As you must have seen in our Pseudocode Tutorial, we generally use a variable to control the number of iterations

In [8]:
#Q: Print the first 5 natural numbers using a while loop
number = 1 #declaring the variable 'number'
while number <= 5: #'adding a condition to define the number of iterations'
    print(number)
    number += 1 #increments 'number' by one in every iteration
1
2
3
4
5

Conditionals in Loops

We can incorporate conditionals in loops in order to use only certain values as our output

In [9]:
#Q: Print all the even numbers between 5 and 15
for i in range(5,15):
    if i%2 == 0: #checks whether i is even for each iteration. Since even numbers are multiples of 2, the remainder when divided by 2 is 0
        print(i)
6
8
10
12
14
In [10]:
#Q: Find the factors of a number inputted by a user
num = int(input("Enter the number to find its factors: "))
factor = 1
while factor <= num: #factors must be less than or equal to the number
    if num%factor == 0: #numbers divided by their factors leave 0 as the remainder
        print(factor)
    factor += 1 #incrementing the variable to check whether each whole number less than the number is a factor
Enter the number to find its factors: 28
1
2
4
7
14
28

Nested Loops

We can nest loops for certain purposes, such as repeating a loop for multiple items

In [13]:
#Q: Find the facotrs for 6,7,8
for i in [6,7,8]:
    print("The factors for " + str(i) + " are:")
    factor = 1
    while factor <= i:
        if i%factor == 0:
            print(factor)
        factor += 1 
The factors for 6 are:
1
2
3
6
The factors for 7 are:
1
7
The factors for 8 are:
1
2
4
8

Be careful to use correct indentation while nesting loops as it can result in an error, as discussed in the previous tutorial

Conclusion

That brings us to the end of this tutorial. Do check out the other tutorials on our website and let us know what you think!

Do check out our Instagram Page for more content and interesting material