Skip to main content

Python Iteration: Mastering the Loop

Data is only useful if you can do something with it. In this lesson, we cover iteration—the process of "looping" through a collection of data to perform an action on every item.


1. The for Loop (Definite Iteration)

In Python, the for loop is primarily used to iterate over a sequence (like a list, tuple, dictionary, set, or string). It’s called "definite" because we usually know how many times it will run based on the size of the collection.

Basic Syntax:

Python Sandbox

Iterating with range()

If you need to loop a specific number of times (rather than over a collection), use the range() function.

Python Sandbox

Iterating over Dictionaries

Dictionaries require a bit more specific handling since they have keys and values.

Python Sandbox

2. The while Loop (Indefinite Iteration)

A while loop repeats as long as a certain condition is True. It is used when you don't know exactly how many times you need to repeat the code beforehand.

Example:

Python Sandbox

3. Loop Control: break and continue

Sometimes you need to change the behavior of a loop while it’s running.

  • break: Exits the loop entirely immediately.
  • continue: Skips the rest of the current block and jumps to the next iteration.

Example:

Python Sandbox

Lesson Review Test

  1. Which loop is best used when you know the exact collection of items you want to process?
    • A) while loop
    • B) for loop
  2. What happens if the condition in a while loop never becomes False?
    • A) The program crashes immediately.
    • B) It creates an "infinite loop" that runs until the process is killed.
    • C) Python automatically stops it after 100 rounds.
  3. Which method do you use to get both keys and values simultaneously in a dictionary loop?
    • A) .keys()
    • B) .values()
    • C) .items()
  4. True or False: The break statement skips the current item and moves to the next one in the loop.

(Answers: 1. B, 2. B, 3. C, 4. False (That is what continue does; break exits the loop entirely))


Deep Dive: External Resources

📚 Deep Dive

Ready to learn more? Check out these excellent resources: