Python

Python Loops

A function’s first statement is executed first, followed by its second, and so on. In general, statements are executed in order. You might need to run a block of code numerous times at some point. Different control structures of different programming languages provide more intricate execution routes. This tutorial will teach you how to iterate over a list of elements using various loop versions.

What Is for loop?

In the Python language, for loops are also referred to as “definite loops” since they repeat the instruction a predetermined number of times. When you want to run the same code for each item in a specific sequence, for loops come in handy. Any iterable data, including ranges, sets, tuples, lists, dictionaries, and even strings, can be traversed by a for loop.

The for loop performs exceptionally well with iterable objects, such as lists, tuples, and strings. In this manner, we can step through the components of these objects and change their values following our connection. The following syntax describes the zero-indexed for loop:

When it hasn’t iterated through every item in the iterable object does the condition in the for loop remain TRUE (n). In order to better understand the for loop, we will go through a few examples in the next section.

What Is a while loop?

While the condition is TRUE, a block of statements is continuously executed in a while loop in Python. We see that it resembles the if statement somewhat. The syntax is as follows:

The while loop does not cycle through a sequence like the for loop. For its condition, it makes use of the Booleans and comparison operators.

What Is a nested loop?

Python loops have the remarkable feature of being nested, meaning we can employ one or more loops inside another loop.

The number of iterations in the nested loop is determined by multiplying the number of iterations in the outer loop by the number of iterations in the inner loop.

We’ll now demonstrate some programming examples using these loops.

Example 1

The for loop will be used in this code to display a list of things. Look at the code. The value of the variable “i” will be “Red shirt” for the first iteration; for the second iteration, the value will change to “Blue socks,” then to “Rings”, and so on.

The for loop executes an operation while iterating through each item in a list, such as iterating the list (usually for every item in that list). Simply said, the iterator is the “i.” By convention, iterator names like i, k, and n are common, but you can call them whatever you like.

my_list = ['Red shirt', 'Blue socks', 'rings', 'shoes', 'lipstick']

for i in my_list:

 print(i)

Here, you can see the listing of all values:

Example 2

This program prints one-to-five-digit numbers. We first declare a variable (counter_num), and its value is set to “0”. Then, we employ a while loop with the constraint “do the following while the counter is less than five”. Every time the while loop iterates, we add one to the counter and print the new value. Our loop ends when the counter reaches five, which yields False because the value won’t be less than five any longer.

In order to use the while loop, you just need to give it a condition and insert statements inside of it that will keep repeating as long as the condition is True.

counter_num = 0

while counter_num < 5:

 counter_num+=1
 print(counter_num)

The output shows the numbers from 1 to 5, as you can see.

Example 3

An example of a nested loop is discussed here. In Python, it is normal to signify a matrix as a list of lists. In other words, every list corresponds to a matrix row. If you are unfamiliar with the term “matrix,” don’t panic. It is merely a list of lists in this case.

You must set up a nested loop in order to access each integer in the matrix. Here, we select a list from the matrix one by one and choose a number from the list one by one.

As you can see, the inner list is assigned to a row variable in the code. After that, a number variable is assigned to each value in the row.

mtx = [2, 4, 6], [1, 3, 5], [2, 8, 2]

for row in mtx:

    for num in row:
        print(num)

Here is the following output:

Example 4

We’ll demonstrate how to make an empty for loop in this section. You may have observed that a for loop cannot be left empty. You must always insert some code into the loop’s body. Otherwise, there will be an error.

However, there are situations when you might want to have a placeholder for a loop or leave the implementation of a loop “blank”. In this situation, skipping the implementation of it is possible by using a special pass statement in the body of the loop. The pass statement can also be employed in other types of code, such as functions.

Put the pass keyword inside the body of the loop to use the pass statement. Let’s construct a for loop that, for instance, loops through a list of numbers without doing anything:

for abc in [0, 2, 4]:

  pass

This piece of code can now be executed without issues.

If the pass statement is removed, the code will raise an error, and you will need to add some code.

Conclusion

Programs produced in any programming language have a sequential flow by design. The direction of the program may need to be changed occasionally. It could be necessary to execute a particular code multiple times. Programming languages offer a variety of loop types that can repeat a given piece of code numerous times for this purpose. The definition of loops, the various Python loop types, the application of the for loop, and the while loop with several examples was covered in this article.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content