One of the main components of the control flow in any language is loops. Like any other language, Python provides two main looping techniques which are (while loop, for loop), they will be discussed within the tutorial. But what makes loops in Python different is the way of iteration and choosing a range of loops and that will be clear in the examples.

  1. While loop with examples
  2. Infinite loop
  3. Nested loops
  4. Control statements
  5. For loop with examples
  6. Nested loops
  7. Control statements

Python Loops Explained

While loop with examples

While loops work in the following manner, the control goes to the condition of the while loop then it checks whether the condition is true or not, if it is true it executes the block of code and then goes check the next iteration. Any statement with the same indentation spaces under the while is considered to be of the same block of code.

Syntax of the while loop is as follows:

while expression:
    execute block of code

A simple example for the while loop:

i = 0
while (i < 3):
    i = i+1
    print("Hello World!")

Output:

Hello World!
Hello World!
Hello World!

Explanation

This example meant to increment the value of “i” and print “Hello World!” as long as the value of i is less than 3.

We can also use the else statement with loops. In our case here the else statement will be executed when the expression of the while loop is no longer true. Let’s see an example:

i = 0
while (i < 3):
    i = i+1
    print("Hello World!")
else:
    print("Looping has finished")

Output:

Hello World!
Hello World!
Hello World!
Looping has finished

Explanation:

As we can see we have the same output as the past example. In addition to the past output, we have the output of the else statement which indicates that the while loop has finished.

Infinite loop

What if you want to keep a block of code running in a specific manner. You will need to have an infinite loop following the simplest syntax.

while True:
	print("Hello World!")
   #time.sleep(10) ~ this line of code to add delay.

Explanation: the while loop keeps printing the statement “Hello World!” until an interrupt is presented in the code otherwise it will keep running until it has an error that no more available memory.

Nested loops

The nested loops are when one or more loops are found in the body of a single loop. How does it perform? The control flows through the first one till it finds the next and keeps executing it till it’s condition is not True. Then control goes to check whether the condition of the first loop is True or not, if it’s still true it will go make a new iteration like the past one otherwise it will exit the loop. This can be applied to an n-number of loops following the same manner. Let’s see an example:

i = 1
j = 5
while i < 4:
	while j < 8:
    	print(i, j)
    	j = j + 1
    	i = i + 1

Output:
1 5
2 6
3 7

Explanation:

Since the first condition is true and also the second condition is true the block of code will execute and loop till the value of j is no longer suitable for the second loop to execute therefore the control will exit and go check the condition of the first loop it will find it is no longer true and then it will exit the loop.

Control statements

What if you want to make changes to the execution order upon certain conditions? Python offers the following control statements for control flow.

The break statement: The loop keeps executing until a certain condition is satisfied and the break statement is inserted then the loop is terminated and control flows to the next block of code, let’s see an example:

i = 1
while i > 0:

	if i == 3:

    	break
	print(i)
	i = i +1
print("break")

Output:
1
2
break

Explanation:

The loop keeps running until the desired condition is satisfied therefore the loops is terminated and jumps to the next print statement.

The continue statement: the loop keeps running until the desired condition is satisfied therefore the loop skip the current iteration and then continue the loop, let’s see an example:

i = 5
while i > 0:

	i = i - 1
	if i == 2:
         continue
	print(i)

print("continue")

4
3
1
0
continue 

Explanation:

The loop keeps running and printing the values of “i” until the condition is satisfied and the continue statement is inserted, the loop will skip this iteration and continue with the next when until the loop statement is no longer true.

The pass statement:

In case you are implementing a code that might need a control statement later on and you want to set up the condition to use them later, they pass statement is presented as a null operation where it will have no effect on the loop sequence, it acts in an opposite manner to the continue statement. Let’s see an example:

i = 5
while i > 0:

	i = i - 1
	if i == 2:
               pass
	print(i)

print("pass")

Output:
4
3
2
1
0
Pass

Explanation:

The loop will act normally as we inserted the pass statement after the condition. It’s counted here as a placeholder for further changes in the code.

For loop with examples

For loops are mainly used to iterate over sequential input (list, array, string). As long as the iterator is in the range of the sequence, the for loop will keep executing the statements within it. The for loop in Python follows this syntax:

for iterator in data:
    Executes block of code

Simple example on for loop:

x = ["Germany", "USA", "France"]

for i in x:
    
    print(i)

Output:

Germany
USA
France

Explanation:

As we define a list of strings we need to print each string. So we provided the iterator which will iterate through the size of the list and print each value of it.

What if you want to print a part of the list only?. Let’s say you want to print from the third index to the end. Python offers an In range function to state which index you want to start with and which one to end with. let’s see an example:

x = ["Germany", "USA", "France", "China", "Poland"]
length = len(x)

for i in range(1 , length-1):
    
    print(x[i])

Output:

USA
France
China

Explanation:

As we can see we have a list of strings and you want to print out the whole strings starting from index = 1 till index = length of list -1. Therefore in range function will be used by passing to it the starting & ending index and printing the value of this index.

We can also use else statements along for loops. Where after the iterator finishes iterating on the sequence range, the loop then exits and jumps to the else statement. Let’s see an example:

for i in range(5):
  print(i)
else:
  print("Reached The Else Clause")

Output:
0
1
2
3
4
Reached The Else Clause

Explanation:

As we can see the iterator keeps iterating in the range of 5 till it’s no longer within the range therefore the control jumps to the else statement and print out the indication that the control is within it.

Nested loops

The nested for loops act in the following manner, the inner loop makes its full iteration for each iteration of the outer problem. And that can be applied for n-numbers of nested loops. Let’s see an example:

colors  = ["Green", "Blue", "Red"]
objects = ["Mint ", "Water", "Rose"]
for x in colors:
  for y in objects:
	print(x, y)

Output:

Green Mint
Green Water
Green Rose
Blue Mint
Blue Water
Blue Rose
Red Mint
Red Water
Red Rose

Explanation:

As we can see per each iteration in the colors list the three components of the objects are printed along with this color. As all iterations finish in the inner loop the control flows to the outer loop again.

Control statements

Again if you want to make changes to your control flow you will need to use control statements.

The break statement:

While the iterators are iterating within the sequence range, what if a certain value is an indication to terminate this loop now. We will need a condition followed by a break statement to do so. Let’s see an example:

Colors = ["Red","Yellow", "Blue", "Green"]
for x in Colors:
  if x == "Blue":
	break
  print(x)

Output:

Red
Yellow

Explanation:

As we can see our iterator x is iterating in range of Colors list and keep printing the strings till the if the condition is satisfied therefore the break statement executes and the loop is terminated.

The continue statement:

It works in the same manner of the break statement as it doesn’t execute until the condition is satisfied. The difference between the break statement and the continue statement is that the continue statement doesn’t terminate the loop. It only skips the iteration where the condition is true. Let’s see an example:

Colors = ["Red","Yellow", "Blue", "Green"]
for x in Colors:
  if x == "Blue":
	continue
  print(x)

Output:

Red
Yellow
Green

Explanation:

As we can see our iterator is iterating in a range of Colors list and keep printing the strings till the if the condition is satisfied therefore it skips the current iteration which is supposed to print out “Blue” and continue printing following strings.

The pass statement:

It’s a dummy operation that can be used as a placeholder for further control statements but the pass statement itself doesn’t affect the control flow. Let’s see an example:

Colors = ["Red","Yellow", "Blue", "Green"]
for x in Colors:
  if x == "Blue":
	pass
  print(x)

Output:

Red
Yellow
Blue
Gree

Explanation:

As we can see the whole list is presented in the output as the condition inserted within the loop is followed by a pass statement.