For Loops
A for loop repeats a block of code once for each item in a sequence. It is how you process every item in a list, every character in a word, or every number in a range, without copying and pasting code.
What You'll Learn
- Looping over lists and strings
- Generating number sequences with
range() - The accumulator pattern for building totals
enumerate()for index-and-value
Looping Over a Sequence
Loading Python Playground...
The loop variable (fruit) takes each value in turn. Strings work the same way, one character at a time.
Loading Python Exercise...
range()
range() generates numbers for you. range(5) counts 0 to 4; range(start, stop, step) gives you more control:
Loading Python Playground...
Loading Python Exercise...
The Accumulator Pattern
Start a variable at zero, then add to it inside the loop. This is how you sum or count things:
Loading Python Playground...
Loading Python Exercise...
enumerate(): Index and Value
When you need the position as well as the value, enumerate() gives you both:
Loading Python Playground...
You will use this in the to-do list project to print a numbered list.
Key Takeaways
for item in sequence:repeats once per itemrange(n)counts 0 to n-1;range(start, stop, step)is flexible- The accumulator pattern builds totals: start at 0, then
+=inside the loop enumerate()gives you the index and the value together
Quiz
Question 1 of 425% Complete
0 of 4 questions answered

