Skip to content

Loops

Dictionary

A loop is control structure that is used to perform same set of instructions for specific number of times.

One of the applications of loops is traverse or iterate over a sequence, e.g. lists, tuples, strings, dictionary, etc.

There are 2 types of loops that we can use,

  • the for loop
  • the while loop

The for Loop

The for loop iterator starts from the beginning of the sequence. In each iteration, set of instructions are performed and after completion the iterator updates to the next value in the sequence.

The iterator stops when a condition is met.

SYNTAX:

The in keyword specifies that the iterator will go through the values in the sequence.

Let go through an example to understand how it works,

Info

range() is an in-built function that can be used to create sequence of integers.

format:

1
range(start, end, step)

  • The end value is not included. Range of numbers will be in [start, end).
  • If start is not specified, default value will be 0
  • step is used to skip integers in the sequence.

Things to remember: - range() function only works with Integers. - the step value must not be zero.

1
2
3
4
5
for num in range(1, 10):    # sequence range [1,10)
    if(num%2):
        print(f"{num} is odd number.")
    else:
        print(f"{num} is even number.")
Result
1
2
3
4
5
6
7
8
9
1 is odd number.
2 is even number.
3 is odd number.
4 is even number.
5 is odd number.
6 is even number.
7 is odd number.
8 is even number.
9 is odd number.

By using loops we can apply set of same operation on each element in sequence in one go instead of checking it individually.

Let's use step,

1
2
for num in range(1, 11, 3): # step of 3, range : [1,11)
    print(f"Cube of {num} is {num**3}.")
Result
1
2
3
4
Cube of 1 is 1.
Cube of 4 is 64.
Cube of 7 is 343.
Cube of 10 is 1000.

Tip

range(1, 11, 3) outputs [1,4,7,10]

Traversing elements of list directly through the iterator,

1
2
3
4
data_types_list = [44, '55.1', 'Professor', 12.11, True]

for item in data_types_list:
    print(f"{item} data type is {type(item)}")
Result
1
2
3
4
5
44 data type is <class 'int'>
55.1 data type is <class 'str'>
Professor data type is <class 'str'>
12.11 data type is <class 'float'>
True data type is <class 'bool'>

Tip

In above code, item is an iterator and altering item variable will not affect the orignal value of list.

1
2
3
4
5
6
7
my_list = [1,2,3,4]

for item in my_list:
    item += 2
    print(item)

print(my_list)
Result
1
2
3
4
5
3
4
5
6
[1, 2, 3, 4]

As we know list are of mutable type, to alter value of the list we can use,

1
2
3
4
5
6
7
my_list = [1,2,3,4]

for idx in range(len(my_list)):
    if my_list[idx]%2:
        my_list[idx] = 'hash'

print(my_list)   
Result
1
['hash', 2, 'hash', 4]
How does it work?
  • len(my_list) = 4
  • range(len(my_list)) = range(4) = [0,1,2,3]
  • enter for loop:
    • idx = 0
      • my_list[0] = 1 (points to first index value of my_list)
      • my_list[0]%2 returns 1 which is equivalent to True
      • condition True
        • my_list[0] = 'hash'
      • my_list = ['hash', 2, 3, 4]
    • idx = 1
      • my_list[1] = 2 (points to second index value of my_list)
      • my_list[1]%2 returns 0 which is equivalent to False
      • condition False
      • my_list = ['hash', 2, 3, 4]
    • idx = 2
    • rest you can figure it out.

Nested for Loop

We can define a for loop inside of another for loop as well. We can also use conditional statements inside for loop. Let's see both in action using an example,

Problem we have in hand is to count number of integer types and floating point types in a given nested list.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
num_list = [[2, 2.2, 3],[1.1, 3, 33],[2, 1, 0]] # nested list

count_int = 0
count_float = 0

for l in num_list:
    for item in l:
        if isinstance(item, int):
            count_int += 1
        elif isinstance(item, float):
            count_float += 1

print(f"Count of integers : {count_int}")
print(f"Count of floating-points : {count_float}")   
Result
1
2
Count of integers : 7
Count of floating-points : 2
How does it work?
  • first iteration first loop
    • l = [2, 2.2, 3]
    • first iteration second loop
      • item = 2
      • checks isinstance(2, int) : condition holds True
        • count_int += 1
    • second iteration second loop
      • item = 2.2
      • checks isinstance(2, int) : condition holds False
      • checks isinstance(2, float) : condition holds True
        • count_float += 1 .... and so on.

Once the inner loop iteration completes, first loop's iterator will move one step ahead and then again inner loop will execute.
Operation will be completed until outer loop condition is met.

Info

In above example, we have used isinstance(), an in-built function.
The built-in isinstance() function returns True if the specified object is of the specified type, otherwise False.

The break Keyword

Sometimes we need to exit a loop in between, even before final condition is met. There are certain types of problems where you need to find something and when found you don't need other operations to be computed. We do this by using break keyword.

Let's understand it by an example.

Suppose the problem we have in hand is, print first 3 even numbers in order from a given list of itegers.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
my_list = [2, 3, 1, 5, 6, 23, 32, 211, 22, 99, 100]

count_even_no = 0

for num in my_list:
    if num%2==0:
        print(num)
        count_even_no += 1 # only when condition holds True we increment count of even no.

    if count_even_no==3:   # as this condition holds True we have print 3 even numbers.
        break              # keyword exists the loop when if condition holds True
Result
1
2
3
2
6
32

Using return as break

We have already studied about return statement. The return statement exits from a function scopt, without executing the remaining code in the block.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def get_first_even_num():
    for num in range(5, 20):    # range : [5,20)
        if num%2==0:            # checks for even number
            return(num)
        print(num)

    return -1                   # in-case no even number found

first_even_num = get_first_even_num()

if first_even_num==-1:
    print("No even number found.")
else:
    print(f"Even Number : {first_even_num}")
Result
1
2
5
Even Number : 6

Using return from inside above loop is equivalent to having a break, as the rest of the operation of the loop is not executed.

The continue Keyword

As the name suggests, a continue statement will skip the rest of the operations in the block and move to the next iteration of the loop.

It doesn't breaks the loop, it only skips the rest of the operations and continue the iteration process. Let's understand it using an example.

Suppose we to print all the numbers which are not mutiple of 2 and 3 from our given list.

1
2
3
4
5
6
my_list = [1, 2, 66, 23, 33, 22, 18]

for num in my_list:
    if num%2==0 and num%3==0:
        continue
    print(num)
Result
1
2
3
4
5
1
2
23
33
22

The pass Keyword

A pass is a null statement and does nothing to code execution. It can be used when no action is required or desired by the programmer. You want to execute a code but you haven't written down operations for certain block.

1
2
3
4
5
6
my_list = list(range(20))

for item in my_list:
    pass        # You can write code here later on

print(len(my_list)) 
Result
1
20

The while Loop

The while loop keeps iterating over a set of operations as long as a certain condition holds True.

The number of iterations in a for loop is fixed since we define the size of a sequence.

On the other hand, a while loop is not restricted to a fixed range. Its execution is based on the condition associated with it.

Let's see it in action.

Suppose the problem in our hand is to find the factorial of given number (give number is less than 10).

Tip

Factorial of 4 is 24, which is calculated as, 1*2*3*4 = 24.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
my_num = 8  # user defined number

def get_fact(num):
    result = 1  # intialize result as 1

    while num>1:
        result *= num
        num -= 1

    return result

print(f"Factorial of {my_num} is {fact(my_num)}")
Result
1
Factorial of 8 is 40320

Be careful when using while loop. If the condition is always true and there is no condition specified to terminate the loop by using a break or return statement or an exception, the while loop will run forever (infinite loop) which may lead to crash the program.

1
2
3
4
5
6
while(True):                # this condition always holds True
    print("Hello World")    # prints Hello World infinitely

x = 1
while(x > 0):               # this condition always holds True
    x += 5                  # value of x will be updated and eventually program will crash our the system will hang.

Like in for loop, we can use the break, continue, and pass keywords with while loops.

1
2
3
4
5
6
x = 1
while(x>0):
    if x>100:
        break
    x+=25
    print(f"Value of x changed to {x}")
Result
1
2
3
4
Value of x changed to 26
Value of x changed to 51
Value of x changed to 76
Value of x changed to 101

Congratulations 🎉🎉🎉🎉 We have completed Python Fundamentals Module.

I would now recommend you to go through exercise section of the module.

I will see you in next module, i.e. OOPs, Object Oriented Programming.

Back to top