For Loops and Ranges
Explore how to use for loops and the range() function in Python to iterate over sequences and control loop execution. Understand the difference from while loops and learn patterns for accumulating totals and repeating actions efficiently.
In the previous lesson, we used while loops to repeat code as long as a specific condition remained true. This approach is especially useful when the number of repetitions is unknown in advance, such as when waiting for a user to type "quit."
In many situations, however, we know exactly how many times an action should be repeated, or we want to process each element in a sequence, such as iterating over every character in a string. Using a while loop for these cases requires manually managing counters and update logic, which increases the likelihood of errors. To address these predictable repetition patterns, Python provides a more elegant solution: the for loop. A for loop automatically handles iteration and boundaries, resulting in code that is shorter, safer, and easier to read.
Iterating over sequences
In Python, the for loop is the primary tool for definite iteration. This means it runs a block of code once for each item in a set of data, stepping through them one by one. Since we have already worked with strings, which are collections of characters, we can use a for loop to inspect every letter in a word without needing manual index counters.
The syntax relies on the in keyword. We define a temporary variable (the loop variable) that Python automatically updates with the next item in the collection at the start of every ... ...