blue swirly wire or plastic

Python like all other major programming languages support both For and While loops for running the same block of code over and over again. In this article I will discuss the difference between a python for loop and a while loop.

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:

while True:
  print "Hello"

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

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

while x < 10:
  x =x +1
  print x


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:

for x in range(1,10):
  print x

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.

pets = ["dog", "cat", "pig"]
for pet in pets:
  print pet


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.