Python for Beginners 14: For

To understand this lesson, I highly recommend you go back to the previous one on while loops if you don’t remember it well. The reason for this is that the for loop that we are learning now is quite similar to the second way of implementing while, i.e. the case in which you know how many times you want to repeat a process. In this case, you can replace a while loop by a for loop. Actually, a for loop might be better in this case, whereas while is mainly for scenarios in which you don’t know the number of repetitions or if you want to check a condition before each iteration.

There are only two differences:

  • the counter: You don’t need to initialize the counter or define it as adding one for every repetition. The for loop does all that automatically. You just use a random name for the counter, which is part of the for syntax. Basically, you have no explicit counter, just an implicit one.
  • the syntax: for + counter + in + range(number1,number2,step):
    indention in the next line

The overall syntax (colon, indention) should look quite familiar, as it is basically the same as for while or if. What is new is having two words (for … in) as part of the syntax in one single line. The range is not officially part of the syntax, but it is used in almost all cases when you use a for loop in combination with numbers.

The function range() has some particularities:

  • The first number is inclusive, the second one exclusive. This means that the first number is part of the range, but the second is not so the range ends one step before reaching the second number.
  • You can also write range(number2), in which case Python is going to set number 1 as 0.

Both of these aspects are important to know, but since Python starts at 0, but ends one number early, in sum, it does not have any implications for our pizza example. If you don’t indicate the step, Python is just going to assume that the step is equal to 1.

Based on this short introduction, you can simply convert the while loop from our pizza example (important: the second one, where we know the number of repetitions) into a for loop.

Your solution might look like this:

The only thing you have to do is delete the lines 2 and 5 (I put them inside of ‘’’ to comment them out) and to change line 4 from while syntax to for, setting a random variable (here: num_pizzas) as the counter and using the amount of pizzas ordered (here: variable order_pizzas) as the range.

If you feel like you need some more time to familiarize yourself with for loops – like I did in the beginning, I recommend this great tutorial by Digital Ocean. Other helpful resourcs are the wiki for Python and/or Tutorials Point. Of course, you can also ask questions in the comments below. #mastery14

Leave a comment