Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 6 of 10

A while loop repeats until a condition changes. A for loop repeats once for each item in a sequence. When you know how many times you want to loop, for is almost always the better choice — there is no counter to forget to update, so no accidental infinite loops.

range()

range(n) produces the numbers from 0 up to but not including n.

for i in range(5):
    print(i)

That prints 0 1 2 3 4 — five numbers, starting at zero. Starting at 0 feels odd at first, but it lines up with how Python numbers everything else, as you'll see with lists in Module 3.

Choosing the start and step

range() takes up to three arguments:

for i in range(1, 6):
    print(i)

range(start, stop) counts from start up to but not including stop — so this prints 1 to 5.

for i in range(0, 10, 2):
    print(i)

range(start, stop, step) jumps by step — this prints 0, 2, 4, 6, 8. A negative step counts down:

for i in range(3, 0, -1):
    print(i)

Looping over a string

A for loop works on anything Python can step through, including strings — you get one character at a time.

for letter in "cat":
    print(letter)

The loop variable (letter, i, whatever you name it) is just a normal variable that gets reassigned each time around.

for versus while

  • Use for when you know the number of repetitions up front, or you are walking through a sequence.
  • Use while when you are waiting for a condition to change and don't know how long it takes.

Try it yourself

Use a for loop with range() to print the numbers 1 through 5.

Checkpoint

  • for repeats once per item in a sequence.
  • range(n) gives 0 to n - 1; range(a, b) gives a to b - 1; a third argument sets the step.
  • for loops also walk through strings, one character at a time.

Questions about this lesson

Log in to ask a question.