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), and 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. Uses of Loops
  2. Advantages of using Loops in Python
  3. Types of Loops in Python
  4. While Loop
  5. Infinite Loop
  6. Nested Loops
  7. Control Statements
  8. The Pass Statement
  9. For Loop with Examples
  10. Nested Loops as Control Statement
  11. Control Statements

Python Loops Explained

Uses of Loops

Instead of manually executing instructions till the accurate outcome, using loops provides a shortcut to minimize code, increase the readability of code, and reduce complexity. Loops and statements hold various uses in any programming language. Loops help alter the conventional flow of a program and execute a specific set of instructions with developer-specified conditions to produce optimal results. The working of the loops depends upon the particular requirements. In loops, a group of instructions tends to repeat itself till the termination condition. After that, the program revises the already devised relevant action. Therefore, the loops provide the opportunity of bringing similar executable instructions together. This technique makes the code reusable for similar tasks.

Advantages of using Loops in Python

Following are some of the advantages of using loops in Python:

  1. Loops play a vital role in the simplification of complex problems.
  2. Loops save developers from manually writing and executing even the most straightforward and shortest instructions repeatedly.
  3. Loops help increase the reusability of code.
  4. These provide easy traversal for the elements like arrays and linked lists.

Types of Loops in Python

Python is the most famous programming language for developing applications. Developers worldwide use Python for web development, Data Science, and Machine Learning. Being such a popular and helpful language, Python provides developers with a wide range of abilities to build clean and reusable code. Therefore, it offers various loops to simplify the coding process and create time and cost-efficient applications. The basic functionalities of all loops are similar; however, the syntax and the condition timings are varied. Following are some of the types of loops being used in Python programming:

  • For Loop
  • While Loop
  • Nested Loop

Following are the explanations regarding each type of loop and its usage.

While Loop

The utilization of the concept of “while loop” is the most helpful in cases with no clarity of the iteration numbers. Unlike for loops, the precise number of iterations is unknown until the program has executed the set of instructions. Therefore, the specified piece of code runs itself till the condition statement is satisfied. Hence, considering this property, the other name of the while loop is “pre-tested loop.” However, the do-while loops work till the termination condition is satisfied. Another word for such loops is “post-tested loops.” The loop executes at least once in this scenario.

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 to check the next iteration. Any statement with the same indentation spaces under the while is considered to be of the same block of code.

The syntax of the while loop is as follows:

while expression:
    execute block of code

A simple example of the while loop:

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

Output:

Hello World!
Hello World!
Hello World!

Explanation

This example is 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.

Importance of While Loop in Python

The while loop helps execute a specific code block considering the statement’s condition. The developers can set a particular requirement to be true, and the program will execute the code till that condition remains true. The while loop helps iterate a code block till the expression is true. While loop helps iterate over a condition where the developers need clarification on the exact number of times it needs to be executed.

Although the Do while loops are not as common in any program as the for and while loops, these loops help in writing readable code. The only thing to remember during the process of the while loop is to use the terminating condition. The program might get stuck in an infinite loop if the termination condition is not provided. On the other hand, using a do-while loop offers the advantage of executing the code block at least once during the process. After a complete analysis of the loops, the developers have confirmed that the do-while loop is faster than the while and for loops.

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 purpose of using control statements is to clarify the control flow of the program. These statements help determine the possible execution or non-execution of certain statements. These statements allow the program to perform an action, skip the code statements, or even jump from one code section to the other. It all depends on the satisfied conditions applied to them.

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 loop 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 skips the current iteration and then continues 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, the 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 scenario where there is a clarification regarding the number of iterations required in the loop, for loop proves helpful. It is beneficial to combine a set of instructions and execute them till all the conditions satisfy completely. This loop is also known as the pre-tested loop since it allows the test expression evaluation before the next iteration.

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.

Importance of For Loop in Python

The For loops provide an executable block of a specific code. The developers can execute the code multiple times by managing the loop variables efficiently. This code block can help in the iteration of a tuple, list, string, dictionary, or other iterable Python object. For loop is a  compelling concept to be used in any programming language. This loop is comprehensible and provides a single-line statement to implement all the conditions.

Moreover, the For loop provides a simple solution to complex problems. It allows the code to be reusable by introducing some simplified statements so that the users do not have to write the same code multiple times. The developers can traverse over the data structure elements using For loops and repeating the steps a few times.

Nested Loops as Control Statement

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 to 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 the range of the Colors list and keep printing the strings till if the condition is satisfied therefore the break statement executes and the loop is terminated.

The Continue Statement

It works in the same manner as 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 condition is satisfied therefore it skips the current iteration which is supposed to print out “Blue” and continue printing the 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.

Therefore, the examples mentioned earlier examples explain the working of various loop formats in python. In conclusion, loops are beneficial in repeating a specific set of instructions to get the desired outcome. The developers can easily use these loops for string, arrays, lists, tuples, and sets alike. Adding loops and conditional statements to the program ensures reusability and easy comprehension. Moreover, introducing control statements in the program provides the desired flow in case of their need. Combined with for, while, and nested loops, control statements like pass, break, and continue can determine any required program’s desired flow. The optimal execution of a program highly depends on both looping and conditional statements.

Learn about automation in Python using Selenium in this tutorial as well as web scraping tools in Python. Find more advanced Python tutorials here.