androidengineers.Book a session

Python 04 · Iteration and transformations

For loops, while loops, and termination

articleSelf-paced

Learn the concept

A for loop consumes an iterable; a while loop repeats while a condition remains true. Use for when iterating over known items and while when progress depends on changing state. Every retry loop needs a termination condition independent of success.

break exits the loop and continue skips to its next iteration. Be careful when a continue prevents a counter or cursor from advancing. Prefer bounded attempts when retrying a service. Infinite loops can exhaust resources even if the operations inside seem harmless.

enumerate pairs values with indexes, and zip pairs corresponding elements. By default, zip stops at the shorter iterable; validate lengths or use strict behavior when mismatched lengths are an error. Iteration should preserve the relationship between records and their labels.

Run and inspect

values = [2, 4, 6]
total = 0
for index, value in enumerate(values):
    total += value
assert total == 12
attempts = 0
while attempts < 3:
    attempts += 1
assert attempts == 3

Your exercise

Process a list of records while skipping invalid ones. Then create a retry loop with a maximum of three attempts and a recorded stop reason.

Check your understanding

An always-failing operation still terminates, and every valid record is processed exactly once.

YOUR LEARNING JOURNEY

0 of 119 available lessons completed

Progress saved in this browser. No account needed.
For loops, while loops, and termination | Forward Deployed Engineer | Android Engineers