Loops in every language usually fall under the same umbrella. There are three types and each one is used to accomplish the same goal, with some nuances. Let’s break this down by talking about each loop type based on the two categories: while and for. All of these are a form of iteration. Iteration is when you go over an element or repeat an operation multiple times. Now, let’s start about the first time of iteration with while loops.

The While Loop

The while loop is the most basic loop in any language. This loop has one important key feature. That key feature is the “conditional”; while loops have a condition that is evaluated at the beginning of each iteration of the loop. This condition decides whether the loop will continue or not. Here’s an example of a loop in Python.

As you can see this is a basic while loop. First, we initialize the variable i. Once the initialization is over, we then use it as the condition of the loop. In our case the condition is: “i < 6”; as long as i is less than 6, keep on repeating this section of code. You can see the effects of this because i gets higher with each iteration.

For Loop

Python has a for loop; this for loop is slightly different than others. It makes good use of iterators, allowing you to iterate over multiple objects. This means that you can iterate over the lines in a file, elements in an array, keys in an object, and more. In our case, we’ll keep it simple. Here’s an example:

Notice the difference between while and for. In this case, we’re initializing our variable and condition within the for loop structure. This is the key difference between the two. After that, it goes through the range of 0 – 6; this means that the condition is to keep iterating until x gets to 5. The other important thing to mention is that for loops in Python have iterators. Iterators allow you to iterate over objects as mentioned above.

With that in mind, that sums up loops. I hope this post helps you with understanding the underlying structure of the loop. I hope this information helps you make a better decision when writing Python code. Loops are one of the most important concepts to learn in Programming.

%d bloggers like this: