Sometimes you want to repeat a certain bit of code a certain number of times, or until a certain thing happens. For this sort of programming, you’ll use a loop. There are two kinds of loops in Python, for loops and while loops.

A for loop repeats the same code for a certain number of items. We’ll look more closely at these later, but here’s the basic structure:

for number in range(10):
    print(number*2)

The range() function creates a list of numbers, starting at 0 and ending at the number before the number you give it. So in the example above, the numbers start at 0 and end at 9.

A while loop repeats as long as a certain condition is met—for example, as long as a certain value isn’t too big, or as long as a variable is equal to a certain thing. Check it out:

Some important things to pay attention to in this code:

  • x is what we call a sentinel variable: it’s the variable that controls whether the loop runs or not. We subtract 1 from x each time we run through the loop, and eventually its value reaches 0 and the loop ends.
  • Notice the indentation. There are two lines of code inside the loop, and then a print statement outside the loop. What happens if you indent the print statement on line 5?
  • As with conditionals, the colon : at the end of line 2 is an important part of the syntax of the loop.
  • It’s possible to (accidentally or on purpose) create an infinite while loop. It’s useful to know how to do this, mostly so you can avoid doing it and breaking your programs.

While loops can be used alongside other control structures to create fun little games: