for vs while, and how to control loop flow.
In this lesson you will learn to:
- Use
forloops to repeat an action a fixed number of times or iterate over collections. - Use
whileloops to repeat until a condition changes. - Track and update variables inside loops and use
breakto exit early. - Decide when to use
forversuswhileloops in automation tasks.
- Reduce repetition and human error.
- Make code scalable and easier to maintain.
- Combine with data structures (lists, dicts, files) to process many items automatically.
loops.py.
For loops — repeat a fixed number of times
Without loops you would have to repeat statements manually. For example, printing numbers 0–10 with no loop would be tedious. A for loop does it succinctly:
forandindefine the loop header.iis the loop variable (conventionallyi, but any name works).range(11)produces numbers from 0 up to, but not including, 11.print(i)runs each iteration.
In many programming languages, counting often starts at zero.
range(n) produces 0 through n-1 — this zero-based indexing aligns with arrays, lists, and memory layouts. Use range(start, stop, step) when you need custom start, end, or step values.
Example: simple ranges
time module and use time.sleep():
5):
for loops work with many iterable types: lists, tuples, strings, dictionaries, file objects, and generator expressions. A couple of quick examples:
while loop when you don’t know how many iterations are required in advance — for example, waiting for valid user input or monitoring an external condition.
Basic structure:
while True:creates a loop that repeats untilbreakis executed.- Each iteration asks the user for input. When the guess matches
password,breakexits the loop; otherwise it repeats.
Be careful with
while loops — if the condition never becomes false (or you never break), the program runs forever. Ensure the loop updates state or receives input that can end the loop to avoid infinite loops.while pattern that accepts only “happy” or “sad”:
breakexits the nearest loop immediately.continueskips the rest of the current iteration and proceeds to the next one.
Recap
- Use
forloops when you know the number of iterations or are iterating over a collection. - Use
whileloops when the repetition depends on external state or user input. - Loops can update variables, perform calculations, and use
break/continuefor finer control. - Combine loops with data structures (lists, dictionaries, files) to build powerful automation patterns.