Python: lesson 5 of 7

Python

PATH 01MODULE 02LESSON 05 OF 07Next: Functions in Python

Loops in Python

Repeat work over records and features while understanding when vectorized tools are better.

Beginner14 min readpythonloopsiterationdata-processing

Concept

A loop repeats code for a sequence of values. A for loop is the normal choice when you have a known collection; a while loop repeats while a condition remains true. Loops are essential for understanding how programs process records, even though later Data Science tools often offer faster vectorized alternatives.

Why It Matters

You may need to inspect feature names, validate a small batch of records, build a summary, or process a stream one record at a time. Loops make the repeated action explicit and give you control over each step.

Intuition

A loop is a careful checklist. Python takes one item, runs the indented block, then moves to the next item until there are no items left or you tell it to stop.

for Loops and enumerate

feature_names = ["age", "tenure_months", "monthly_charge"]

for feature in feature_names:
    print(f"Checking feature: {feature}")

Expected output:

Checking feature: age
Checking feature: tenure_months
Checking feature: monthly_charge

Use enumerate() when both the position and value are useful.

for index, feature in enumerate(feature_names, start=1):
    print(index, feature)

Real-World / Data Science Example

This small loop calculates a simple count of valid scores while skipping missing values.

scores = [0.91, None, 0.84, 0.88]
valid_score_count = 0

for score in scores:
    if score is None:
        continue
    valid_score_count += 1

print(valid_score_count)

Expected output: 3. continue skips the rest of the current iteration and moves to the next score.

while, range, break, and continue

range() creates a sequence of integers, which is useful for controlled repetition. A while loop is useful when the number of repetitions depends on a condition.

attempt = 1
while attempt <= 3:
    print(f"Validation attempt {attempt}")
    attempt += 1

Use break to exit a loop early when further work is unnecessary.

values = [12, 18, -1, 25]
for value in values:
    if value < 0:
        print("Invalid value found")
        break

Explanation of the Code

The for loop assigns each value to score in turn. The variable valid_score_count starts at zero and increases only for usable values. In the while example, updating attempt is essential; without it, the condition would remain true forever.

When to Use It

Use loops for small collections, custom record-by-record logic, API pagination, file processing, and streams where values arrive one at a time. Prefer for over while when you are iterating over an existing collection.

Failure Signals

Common Mistakes

  1. Forgetting to update a while loop variable.
  2. Modifying a list while iterating over it.
  3. Using an index when the item itself is clearer.
  4. Writing a Python loop over a very large table when a vectorized operation exists.

Best Practices

Keep loop bodies short, name the current item clearly, and use enumerate() instead of managing a counter yourself. Test edge cases such as an empty list and missing values. Use break and continue sparingly so the flow remains readable.

Data Science Perspective

Understanding loops is important, but vectorized NumPy and Pandas operations are usually faster and clearer for large arrays and tables. For example, later you would often calculate a whole column's missingness with Pandas rather than writing one Python loop per row. Use loops when the work is genuinely sequential or custom.

Interview Perspective

Question: When would you avoid a Python loop in data analysis? A strong answer: when a vectorized NumPy or Pandas operation can express the same calculation over a large dataset, because it is usually faster and often more concise.

Worked Example: Build a Small Summary

Loops are still valuable when the logic is custom and the collection is small.

order_amounts = [120, 340, 75, 610]
large_order_count = 0

for amount in order_amounts:
    if amount >= 500:
        large_order_count += 1

print(large_order_count)

Expected output: 1. The loop makes the definition of a large order visible. In a DataFrame later, the same rule would usually be applied to an entire column with a vectorized comparison.

Practice Questions

  1. Print every feature name in a list with its position.
  2. Count how many values in [3, None, 8, None] are not missing.
  3. Explain why a row-by-row loop may be a poor choice for a million-row DataFrame.

Quick Quiz

  1. Which loop is best for a list of feature names? Answer: for.
  2. What does continue do? Answer: skips to the next iteration.
  3. What risk comes from a while loop whose condition never changes? Answer: an infinite loop.

Key Takeaway

Key Takeaways

Loops express repeated work clearly. Learn them well, then choose vectorized Data Science tools when they fit the problem and scale better.

Next Lesson

Next, package repeated logic into reusable functions.

Finish this lesson on your terms

Mark it complete when you have worked through the material and are ready to move on.