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:
Iterating with range()
If you need to loop a specific number of times (rather than over a collection), use the range() function.
Iterating over Dictionaries
Dictionaries require a bit more specific handling since they have keys and values.
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:
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:
Lesson Review Test
- Which loop is best used when you know the exact collection of items you want to process?
- A)
whileloop - B)
forloop
- A)
- What happens if the condition in a
whileloop never becomesFalse?- 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.
- Which method do you use to get both keys and values simultaneously in a dictionary loop?
- A)
.keys() - B)
.values() - C)
.items()
- A)
- True or False: The
breakstatement 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:
- Python Docs: More Control Flow Tools
- Real Python: Python "while" Loops (Indefinite Iteration)
- W3Schools: Python For Loops Reference
- Programiz: Python break and continue