Python for Data Analytics • Lesson 13
for Loops
Learn how to repeat code efficiently using Python for loops. Work with sequences, range(), lists, strings, and real data analysis examples.
0 of 8 concepts completed
Complete the activity and related MCQ to unlock the next concept.
Why Do We Need Loops?
A loop lets Python repeat a block of code without you writing it out again and again. Without loops, printing 1 to 5 means five separate print() lines.
Learn by Seeing
Repeat automatically
# Without a loop
print(1)
print(2)
print(3)
# With a loop
for number in range(1, 4):
print(number)One loop replaces a long list of repeated instructions.
Compare manually written lines vs one loop:
Without a loop
print(1) print(2) print(3) print(4) print(5)
With a loop
for i in range(1, 6):
print(i)Interactive Activity
How many print() lines are needed to print 1 to 5 WITHOUT a loop?
Hint: One line per number.
Python Analyst Mindset
Loops are how you touch every row
Whether you are filtering a DataFrame, processing a file line by line, or applying a business rule to every transaction, you are looping. for is the analyst's way of saying "do this to each of these".
Repeat
One loop replaces many lines.
Sequence
Visit each item in a list or string.
Count
Use an accumulator with a loop.
Filter
Combine with if for conditional logic.
Frequently Asked Questions
for Loops — FAQs
range() is designed to exclude the stop value, so the number of items matches the argument. range(5) gives exactly 5 numbers, 0 through 4.
No. Every for (and if, while, def) statement must end with a colon and an indented body.
Use a negative step: range(10, 0, -2) gives 10, 8, 6, 4, 2.
Not safely. Build a new list, or loop over a copy. Modifying during iteration gives unpredictable results.
Lesson Summary
What you learned
Repeats code once per item.
0 up to (but not including) n.
Starts at start, excludes stop.
Advance by step each iteration.
Walk either as a sequence.
Count or filter high-value records.