PythonConditional Statements and LoopsPython loops
What is a loop in Python?
Question 51 of 88 · Updated
On this page
- 1. The parts of a loop
- 2. The for loop
- 3. The while loop
- 4. Repetition as a way to calculate a result
- 5. Repeating a task a fixed number of times
- 6. Loops can execute zero times
- 7. Iterables and iterators
- 8. Combining loops and conditional statements
- 9. Loop-control statements
- 10. Practical example: process remaining items
- 11. Scope and loop targets
- 12. Choosing an appropriate loop
- 13. Common mistakes and failure cases
- 14. Best practices
- Frequently asked questions
- What is an iteration?
- What are the types of loops in Python?
- Does a for loop always use a counter?
- Can a loop run forever?
- Do loops create a separate variable scope?
- Interview-ready answer
- Official references
A loop in Python is a control-flow construct that repeatedly executes a block of code. Instead of writing the same instructions several times, a program can repeat them for each item in an iterable or for as long as a condition remains truthy.
Python provides two main synchronous loop statements: for and while. An iteration is one execution of the loop body. A loop can perform zero, one, many or potentially infinitely many iterations, depending on its input and termination behavior.
Loops are used to process records, calculate totals, validate batches of data, search collections and repeat tasks until a goal is reached.
1. The parts of a loop#
A loop generally involves a rule for entering or repeating its body, an indented suite of statements and a way to finish.
| Term | Meaning |
|---|---|
| Loop header | The statement introducing the repetition rule |
| Loop body (suite) | The statements repeated during each iteration |
| Iteration | One execution of the loop body |
| Loop target | A name or other assignment target receiving an item in a for loop |
| Loop state | Values used or updated across iterations |
| Termination | The point at which repetition ends |
Both for and while headers end with a colon. In the usual multiline form, indentation identifies the statements belonging to the body. Four spaces per indentation level are recommended by PEP 8.
2. The for loop#
Use for to process the items supplied by an iterable, such as a list, string, range, dictionary or iterator.
PYTHONfor name in ['pen','book','bag']: print(name) print('done')
Output:
pen
book
bag
donePython evaluates the iterable expression once, obtains an iterator and repeatedly obtains items from it. Each item is assigned to the loop target name before the body executes. When the iterator is exhausted normally, the loop finishes.
This diagram shows normal iteration, without early termination, exceptions or an optional else suite.
The keyword in here is part of the for statement's grammar. It identifies the iterable to traverse; it is not a membership comparison.
A for loop does not need an integer counter. It processes items directly. For a collection of values, direct iteration is often clearer than creating numeric indexes solely to retrieve those values.
3. The while loop#
Use while when repetition depends on a condition rather than directly on the items of an iterable.
PYTHONremaining=3 while remaining>0: print(remaining) remaining-=1 print('ready')
Output:
3
2
1
readyThe condition remaining > 0 is tested before each iteration. On each successful test, the body prints the current value and subtracts one. When remaining reaches zero, the condition becomes false and the body is no longer executed.
A while condition uses ordinary truth-value testing. It does not need to be an expression whose type is bool. The state may change inside the loop, through a called function or for other reasons depending on the program.
When a finite repetition is intended, identify how the condition can become false or how another valid exit path will be reached. An unchanged truthy condition can lead to nontermination.
4. Repetition as a way to calculate a result#
An accumulator stores a result that is updated as a loop progresses.
PYTHONtotal=0 for price in [120,80,100]: total+=price print(total)
Output:
300| Iteration | Current price | Total after addition |
|---|---|---|
| Before loop | — | 0 |
| 1 | 120 | 120 |
| 2 | 80 | 200 |
| 3 | 100 | 300 |
The initialization total = 0 happens once, before the loop. Placing it inside the loop would reset the accumulated result on every iteration.
For the intended integer prices, the final result equals the sum of all three values. In ordinary code, sum(prices) is a simpler way to perform an uncomplicated summation. The explicit loop is useful when learning state updates or when additional processing is needed for each item.
If the input contains n prices, the loop performs n additions. Under a fixed-size arithmetic model, it takes O(n) time and O(1) auxiliary space, excluding input storage. Python's arbitrary-precision integers can have additional costs that depend on their sizes.
5. Repeating a task a fixed number of times#
PYTHONfor i in range(3): print(i)
Output:
0
1
2The range(3) object represents the integers from zero up to, but not including, three. The loop has three iterations. Python's range represents a progression compactly rather than constructing a list of every integer.
Use a for loop with range for a known number of repetitions. If the task does not need an index, a conventional target name such as underscore can communicate that the supplied value is intentionally unused.
The upcoming range lesson will explain start, stop, step, negative steps, indexing and other behavior in detail.
6. Loops can execute zero times#
PYTHONfor item in []: print(item) print('empty handled') while False: print('unreachable')
Output:
empty handledThe for body does not execute because the list is empty. The while body does not execute because its first condition test is false.
Do not assume the loop body will initialize a variable, perform validation or produce an output at least once. Establish any required initial values before the loop, and explicitly decide how empty inputs should be handled.
Python does not provide a separate built-in do-while statement that automatically executes the body once before testing its condition. When such behavior is required, use an appropriate explicit control-flow structure.
7. Iterables and iterators#
A for loop obtains items from an iterable through Python's iteration protocol. An iterable can usually provide an iterator, and an iterator supplies successive values until exhaustion.
PYTHONit=iter(['a','b']) for item in it: print(item) print(list(it))
Output:
a
b
[]The iterator is exhausted by the for loop. Calling list on that same iterator afterward returns an empty list.
A reusable list normally provides a fresh iterator for each traversal. An iterator itself maintains traversal state, so another loop over an exhausted ordinary iterator will not restart it.
The normal exhaustion signal in the synchronous iterator protocol is StopIteration. Python's for statement handles this signal when obtaining the next item. An unrelated exception raised by iterator code or the loop body can instead propagate.
The earlier membership lesson discussed iterator consumption. Iterators, generators and asynchronous iteration will be examined separately later in the curriculum.
8. Combining loops and conditional statements#
A loop can contain an if statement to process only items meeting a predicate.
PYTHONdef count_valid(values): count=0 for value in values: if value>=0: count+=1 return count print(count_valid([3,-1,0,8]),count_valid([]))
Output:
3 0The loop examines all four values in the first input. The if suite increments the counter only for nonnegative values. The empty input returns zero because count was initialized before the loop.
The function assumes comparable numeric values. A real validation boundary may need stricter type checks and a defined policy for non-finite values.
For n items, the algorithm performs n condition evaluations and at most n increments. It uses O(n) time and O(1) auxiliary storage under bounded-cost comparison and arithmetic assumptions.
9. Loop-control statements#
Python provides additional statements that change the normal progression through a loop body.
| Statement | Purpose |
|---|---|
| break | Exit the innermost enclosing loop |
| continue | Skip the remaining body of the current iteration and proceed to the next iteration |
| pass | Do nothing; execution continues normally |
PYTHONfor n in range(5): if n==1: continue if n==4: break print(n)
Output:
0
2
3The loop skips printing 1 and stops when n reaches 4. The break and continue statements affect control flow; pass does not.
Both for and while can also have an optional else suite. On normal exhaustion of a for loop or a false condition ending a while loop, the else suite can execute. A break from that loop skips its else suite. A return or an exception leaving the loop can also prevent normal completion.
These constructs have dedicated lessons later in this module. For now, distinguish normal completion from an early exit.
10. Practical example: process remaining items#
PYTHONdef drain(queue): while queue: print(queue.pop()) items=['a','b','c'] drain(items) print(items)
Output:
c
b
a
[]The condition tests the list's truth value. Each iteration removes the last item. When the list becomes empty, the condition becomes false.
This intentionally mutates the caller's list and processes items in reverse insertion order. Although the parameter is named queue, this example behaves like a stack because pop removes the last item. For first-in-first-out processing, collections.deque with popleft is usually a more appropriate data structure.
The loop completes after n successful removals for an ordinary finite list with n initial items and no other changes. End-of-list pop is normally amortized O(1) in CPython, so the removal work is amortized O(n), excluding printing and any other processing.
This local example is not a concurrent task queue. A production worker requires appropriate synchronization, error handling and termination policies.
11. Scope and loop targets#
Ordinary for and while statements do not introduce a new lexical scope. A for loop target is assigned in the surrounding scope.
PYTHONfor n in [1,2,3]: pass print(n) for n in []: pass print(n)
Output:
3
3After the first loop, n retains the last assigned value. The second loop has no iterations, so it does not assign a new value to n.
This is not a reliable method for retrieving the final element of a potentially empty input. If the target had never been bound and the loop were empty, reading it afterward could raise NameError or UnboundLocalError, depending on scope.
The earlier variable-scope lesson explains why an assignment inside a function influences local name classification. Comprehensions have their own scope rules and should not be assumed to behave identically to ordinary for statements.
12. Choosing an appropriate loop#
| Situation | Typical choice |
|---|---|
| Process each record in a collection | for |
| Repeat a fixed number of times | for with range |
| Repeat until a changing state reaches a threshold | while |
| Consume an iterator or a stream of items | for, if its iteration protocol fits |
| Wait or retry under a bounded condition | while with a deliberate exit policy |
This is a guide rather than a rigid rule. A while loop can reproduce many for-loop tasks, but manually tracking positions often introduces unnecessary state and off-by-one risks. A for loop can also terminate early using break.
Python additionally supports asynchronous for statements for asynchronous iterables in appropriate async contexts. That protocol is beyond this introductory synchronous-loop lesson.
13. Common mistakes and failure cases#
Four independent tests confirmed these errors:
| Incorrect operation | Exception |
|---|---|
| for over an ordinary integer | TypeError |
| while header without a colon | SyntaxError |
| Missing indented suite after a multiline for header | IndentationError |
| Reading a function-local loop target after an empty traversal with no previous binding | UnboundLocalError |
Other common problems include resetting an accumulator inside the body, forgetting to update a while-loop condition, assuming every loop runs at least once, mutating a collection in a way that invalidates traversal assumptions and consuming an iterator that is needed later.
Do not assume that a for loop necessarily finishes. Its iterable can be unbounded, or its body can itself fail to terminate. Similarly, a deliberately long-running while loop may be appropriate for a service with a well-defined cancellation or shutdown mechanism.
14. Best practices#
- Prefer direct iteration over items when indexes are unnecessary.
- Initialize accumulators and other required state before the loop.
- Define the intended completion behavior, especially for while loops and unbounded sources.
- Test empty inputs, a single item, ordinary inputs and relevant boundaries.
- Keep loop bodies focused on one clear task; extract helpers when processing becomes complex.
- Choose built-in functions such as sum when they express the complete operation more directly.
- Consider both the number of iterations and the cost of the work performed in each iteration.
Frequently asked questions#
What is an iteration?#
An iteration is one execution of the loop body. An item can be fetched or a condition tested without necessarily producing a completed iteration if execution is interrupted.
What are the types of loops in Python?#
The main synchronous loop statements are for and while. Python also provides async for for asynchronous iteration.
Does a for loop always use a counter?#
No. It can directly iterate over strings, records, iterator values and other supported iterables.
Can a loop run forever?#
Yes. A while condition can remain truthy indefinitely, and a for loop can consume an infinite iterable. A program should use a termination or cancellation policy appropriate to the task.
Do loops create a separate variable scope?#
Ordinary for and while statements do not. Their assignments follow the surrounding scope rules.
Interview-ready answer#
A loop is a control-flow statement used to repeat a block of code. Python's for loop obtains successive items from an iterable and executes its body for each item, while a while loop repeats as long as its condition is truthy. Both can execute zero or many times. Indentation defines the body, and break and continue can alter the normal iteration flow. Loops are useful for traversal, aggregation, searching and state-based repetition. Correct loop design accounts for termination, empty inputs, state updates and the cost of each iteration.
Official references#
- Python Language Reference — The for statement
- Python Language Reference — The while statement
- Python Tutorial — for Statements
- Python Standard Library — Iterator Types
- Python Standard Library — Ranges
- Python Language Reference — Execution model
- PEP 8 — Indentation
Verification note: All ten runnable Python example groups were executed independently on CPython 3.13.5 and matched their documented outputs. Four independent expected-exception tests passed. The two fenced Mermaid flowcharts were manually reviewed for normal loop control flow. The local Mermaid package and CLI were unavailable, so parser-level validation and public-site rendering were not performed. Official links are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.
References
- 1.Python Language Reference — The for statementdocs.python.org
- 2.Python Tutorial — for Statementsdocs.python.org
- 3.Python Standard Library — Iterator Typesdocs.python.org
- 4.Python Language Reference — Execution modeldocs.python.org
- 5.PEP 8 — Indentationpeps.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design