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.
- Uses of Loops
- Advantages of using Loops in Python
- Types of Loops in Python
- While Loop
- Infinite Loop
- Nested Loops
- Control Statements
- The Pass Statement
- For Loop with Examples
- Nested Loops as Control Statement
- Control Statements
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:
- Loops play a vital role in the simplification of complex problems.
- Loops save developers from manually writing and executing even the most straightforward and shortest instructions repeatedly.
- Loops help increase the reusability of code.
- 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.
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!")
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")
Looping 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.
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.
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
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.
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")
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
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")
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)
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])
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")
Reached The Else Clause
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)
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.
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)
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)
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)
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.