Python For loops and While loops

PythonPython is an interpreted, high-level, cross-platform program... like all other major programming languages support both For and While loops for running the same block of code over and over again.

Generally the difference between the two kinds of loops is that you declare and initialize the loop and variables at the same time with a for loop. Whereas with a while loop, you declare the variables first, and then the wile loop separately.

The most simple while loop would be something like this:

The above loop will run infinitely unless you add a break statement.

Here is an example while loop which will loop 10 times:

 

The above loop will run 10 times, each time it will increment X and print out the current value.

Here is an example of the same operation, but written with a for loop:

Just like the while loop, the above for loop will iterate 10 times. You can see it is a little simpler as we were able to write it in two lines of code as opposed to 4.

In the next example of a for loop, we will pass a list to the loop and iterate on each element in the list.

 

In the above example, we created an array of pets and listed all of our pets. We then declared our for loop and created a vairable called pet and passed the list called pets. As we iterate through the array, the value of the variable pet is set to the current element in the array. We then print the value of the current pet in the array.