Lesson 2 of 5 · Control Flow · 2 min read · Updated

Loops: for and while

Repeat work without repeating yourself — and why a Python for loop is not a C one.

A Python for loop does not count. It walks through a collection, one item at a time. That difference catches people arriving from C.

python
for name in ["Priya", "Arun", "Meena"]:
    print("Hello,", name)

# To count, ask range() for the numbers:
for i in range(1, 6):
    print(i, end=" ")
Output
Hello, Priya
Hello, Arun
Hello, Meena
1 2 3 4 5

Note

range(1, 6) gives 1 to 5 — the end is not included. That is consistent everywhere in Python, and it is why range(5) gives exactly the five valid indexes of a five-item list.

while — when you do not know how many times

python
total = 0

while True:
    line = input("Number (blank to stop): ")

    if line == "":
        break

    total += int(line)

print("Total:", total)

Walking a list with its position

python
names = ["Priya", "Arun", "Meena"]

# Works, but clumsy:
for i in range(len(names)):
    print(i + 1, names[i])

# The Python way:
for i, name in enumerate(names, start=1):
    print(i, name)

Warning

Never change a list while looping over it — removing items shifts everything along and the loop silently skips entries. Build a new list instead.

What does range(1, 6) produce?

Try this now

  1. Print the multiplication table for a number the user chooses.
  2. Read numbers until the user enters a blank line, then print the largest.
  3. Count how many words in a sentence start with a vowel.

Create a free account to save your progress, or sign in.