loops in python

Python Loops

Last Updated | Jan, 02, 2021 By Kingsley Ijomah
In this post, we are going to learn about the for in loop and the while loop used in Python programming, we will take a closer look at break statement and continue statements and how they affect nested loops ( loops within a loop ).

By the end of this post you will have a solid understanding of looping in Python and be able to write you own or understand it when you read it in someone else's code.

loops in python explained

What is for loop in Python

The for loop in Python is used to iterate over a sequence, think of this as the same as foreach function in other programming languages, for loop in Python executes a set of statements for each item in a sequence e.g list, tuple, dictionary, set, string, range.

code
'''
Output:
Hi Bob
Hi Jennifer
Hi David
'''
students = ["Bob", "Jennifer", "David"]
for stu in students:
    print("Hi", stu)

The Range Function

The range() function generates a sequence of numbers, for example, range(10) will generate numbers from 0 to 9.

We can be more specific and specify the start, stop and step size: range(start, stop, step) the step defaults to 1 if not given.

code
'''
calling range directly acts in a lazy fashion and
will only remember the start and stop numbers, you need
to cast to something like a list.
'''
range(10) # output: range(0, 10)

'''
calling list function on the range will print out the
desired result set.
'''
list(range(10)) # output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

'''
with the range function, you can change where the count
begins, in the example below, we are starting the count
from 3, the default is 0.
'''
list(range(3, 6))  # output: [3, 4, 5]

'''
we can also decide to step over the list of number by using
something other than 1, in the example below we use 2 as 
the step number.
'''
list(range(3, 12, 2)) # output: [3, 5, 7, 9, 11]

Just printing list of numbers as in the example above might be enough for what you want, but in most cases it will not be all you want to do, so for that reason you can also use for loop with the range function.

code
# Ouput: 0,2,4,6,8,10
for x in range(6):
    print(x*2)


# Output: 4,5,6
for x in range(3, 6):
    print(x+1)


# Output: 3,5,7,9,11
for x in range(3, 12, 2):
    print(x)

Nested For Loops

Nested looping is when you run a loop within a loop, this is useful for when you want to pass through a list and then for each item in list you want to perform additional action.

For example, you could read a file line by line and for each line you want to count how many times the word "and" was found. The outter loop will read the line and the inner loop will count the occurrences of the word "and".

In Python, nested loops are written as:

code
'''
output:
* 
* * 
* * * 
* * * * 
* * * * * 
'''

for i in range(1, 6):
    for j in range(i):
        print("*", end=' ')
    print()

The example above is a really good example of a nested loop in action, it actually has a lot packed into it, so be sure to spend sometime to understand and be able to follow the execution before you proceed.

First we have a range(1, 5) and then in the inner loop we create different ranges starting with range(1), range(2) up to range(5) and each time we print "*" with a blank space to the right of it hence end=' ' every time we finish a roll we call the print() to make sure we move down to the next line and start all over again.

Think of the outer loop as the rows and the inner loop and the columns.

While Loops

The while loop is used to repeat a section of code an unknown number of times until a specific condition is met.

As long as the condition is not met, while loop will carry on executing.

code
'''
This will print the numbers 1 through to 10
'''

i = 1
while i < 10:
  print(i)
  i += 1

The while loop above will continue until i < 10 is no longer true, while loop would require a way to exit otherwise it will run indefinitely, imagine running the code below, it will run forever because there is no way for i to increment and therefore i < 10 will will always be true.

code
# runs forever, use ctrl + c to terminate if you are using terminal
i = 1
while i < 10:
  print(i)

The Break Statement

Python's break statement will terminate the loop, in a while loop this will be terminated even if the condition is still True. If the break statement is inside a nested loop, the break statement will terminate the innermost loop.

Let's see some example of this.

code
'''
break statement in a while loop

This starts with 1 and checks each time
if the incrementing value is up to 3
then it terminates.

output: 1 2 3
'''

i = 1
while i < 10:
  print(i)
  if i == 3:
    break
  i += 1


'''
break statement in a for loop

This is similar to the one above except
that we are applying a break before
printing, so this will terminate earlier

output: 1 2
'''
for i in range(1, 10):
    if(i==3):
        break
    print(i)


'''
break statement in a nested loop

the inner loop is terminated but the
outer loop caries on.

output: 
* 
* 
* 
* 
* 
'''
for i in range(1, 6):
    for j in range(i):
        if(j==1):
            break
        print("*", end=' ')
    print()

The Continue Statement

The continue statement is used as a way to end the current iteration in a for loop or a while loop, and continues/skip to the next iteration.

Let's see an example of this:

code
'''
This will skip 3 and continue iterating

output: 1 2 4 5
'''
i = 0
while i < 5:
  i += 1
  if i == 3:
    continue
  print(i)

Final Thoughts

We have looked at the two types of loops in Python while loop and for in loop, spend as much time as needed to understand how they both work, when to use them and just play around with them until you feel comfortable with your loops.

Also revise on the range function, remember that range(10) would print(0 to 9) and you could manually change the start and step count etc

Hope learnt a lot from this post, please do share it so others can learn from it too.

Happy coding...

MY STORY

My name is Kingsley Ijomah, I am the founder of CODEHANCE, an online education platform built with you in mind, a place where I express my gratitude to a skill ( coding ) which has changed my life completely.

Learn To Code With Me.
FREE course included.

GET IN TOUCH

Enter your email address:

Delivered by FeedBurner