Python Loops: for, while and Nested Loops
Learn Python for loops, while loops and nested loops with syntax, worked examples and placement test patterns. Covers break, continue and pass.
Python gives you two loop types, for and while, plus nested combinations of both. Placement coding rounds test all three. The for loop handles sequences where the count is known upfront; while handles anything condition-driven; nested loops power patterns and matrix operations.
The for Loop in Python
The Python language reference defines a for loop as iteration over any iterable object: a list, string, tuple, or range. The loop variable takes each value in the sequence in order, one per iteration.
Syntax
for variable in sequence:
statement(s)
For numerical iteration, the range() function is the standard tool. The range() documentation describes three call signatures:
range(stop)— integers from 0 up to (but not including) stop.range(start, stop)— integers from start up to (but not including) stop.range(start, stop, step)— integers from start, stepping by step, up to (but not including) stop.
for variable in range(start, stop, step):
statement(s)
Worked Example: Even Numbers from 2 to 10
for i in range(2, 12, 2):
print(i)
Output:
2
4
6
8
10
Verified from first principles:
range(2, 12, 2)starts at 2, steps by 2, and stops before 12.- Five iterations: i takes values 2, 4, 6, 8, 10.
- 12 is not printed because the stop value is exclusive.
When to Use a for Loop
Use for when you know the number of iterations before the loop starts, when you are traversing a list or string, or when the loop counter is a direct index into a sequence. Array traversal problems are a natural fit. The find smallest and largest element in an array article shows this pattern applied to a classic placement test problem.
The while Loop in Python
A while loop runs a block of code as long as its condition evaluates to True. Once the condition turns False, the loop exits.
while condition:
statement(s)
Worked Example: Sum of Integers from 0 to 6
n = 7
total = 0
i = 0
while i < n:
total += i
i += 1
print(total)
Output: 21
Verified from first principles:
- i=0: total = 0 + 0 = 0, i becomes 1
- i=1: total = 0 + 1 = 1, i becomes 2
- i=2: total = 1 + 2 = 3, i becomes 3
- i=3: total = 3 + 3 = 6, i becomes 4
- i=4: total = 6 + 4 = 10, i becomes 5
- i=5: total = 10 + 5 = 15, i becomes 6
- i=6: total = 15 + 6 = 21, i becomes 7
- Check:
7 < 7is False. Loop exits. - Final result: 21.
Convergence Requirement
Every while loop needs a statement that eventually makes its condition False. In the example, i += 1 is that statement. Remove it and the loop runs forever. In placement tests, spotting a missing increment inside a while loop is a standard “find the bug” question type.
When to Use a while Loop
Use while when the iteration count depends on runtime input, when you are searching for a value without knowing how far into the data it lives, or when a computation converges over an unknown number of steps.
Nested Loops in Python
A nested loop is a loop placed inside another loop. The inner loop runs to completion for every single iteration of the outer loop.
for outer_var in outer_sequence:
for inner_var in inner_sequence:
statement(s)
Worked Example: Number Triangle Pattern
for i in range(1, 5):
for j in range(i):
print(j + 1, end=' ')
print()
Output:
1
1 2
1 2 3
1 2 3 4
Trace:
- i=1: inner
range(1), j=0, prints1. Outerprint()adds newline. - i=2: inner
range(2), j=0 then j=1, prints1 2. Newline. - i=3: inner
range(3), j=0,1,2, prints1 2 3. Newline. - i=4: inner
range(4), j=0,1,2,3, prints1 2 3 4. Newline.
Time Complexity
When an outer loop runs m times and an inner loop runs n times per outer iteration, the total operation count is m × n. For problems that ask you to compare every pair in a dataset, a nested loop is the starting-point solution. The 20 most-asked data structures interview questions covers several such problems where a naive nested loop answer is step one and the interviewer then asks for an O(n) optimisation.
Loop Control: break, continue and pass
Three statements modify how a loop executes:
- break exits the loop immediately, regardless of the remaining condition.
- continue skips the rest of the current iteration and jumps to the next one.
- pass does nothing at runtime. It is a syntactic placeholder for an empty loop body.
Worked Example
for i in range(10):
if i == 5:
break # exit when i reaches 5
if i % 2 == 0:
continue # skip even numbers
print(i)
Output:
1
3
Trace:
- i=0:
0 % 2 == 0triggerscontinue. Skipsprint. - i=1: odd, prints 1.
- i=2: even,
continue. - i=3: odd, prints 3.
- i=4: even,
continue. - i=5:
breakfires before the parity check. Loop ends. - Printed values: 1 and 3.
The break in a nested loop exits only the innermost loop. To exit an outer loop from inside an inner loop, use a flag variable set inside the inner loop and checked in the outer condition.
for vs while: Choosing the Right Loop
| Criterion | for loop | while loop |
|---|---|---|
| Iteration count known before loop starts? | Yes | No |
| Iterating over a list, string, or range? | Natural fit | Needs manual indexing |
| Exit driven by a converging condition? | Needs an extra break | Natural fit |
| Risk of an infinite loop? | None with a finite sequence | Yes, if condition never turns False |
| Common placement test form? | Range iteration, list traversal | Convergence, search, input reading |
The two forms are interchangeable when you have a counter. for i in range(5): and the while equivalent with i = 0; while i < 5: produce identical output. The for version is preferred when the count is fixed because it is easier to read and impossible to accidentally omit the increment.
For string traversal problems, either loop works. The palindrome string check article uses the two-pointer approach, which maps to a while loop because the stop condition is pointer crossing rather than a fixed count.
Once you have loops in place, writing them against real data is where the skill becomes durable. The while loop pattern (run until a condition changes) shows up constantly in LLM API code: poll until a response arrives, retry on a rate-limit error, iterate until a generated output passes a validation check. The nested loop pattern surfaces in batch prompt evaluation across a grid of temperature and prompt variants. TinkerLLM gives you real LLM API endpoints and a Python notebook to practise those exact loop structures at ₹299, without setting up separate accounts elsewhere.
Primary sources
Frequently asked questions
What is the difference between a for loop and a while loop in Python?
A for loop iterates over a fixed sequence or range — the number of iterations is known before the loop starts. A while loop runs as long as a condition stays true — the number of iterations depends on runtime state. Use for when you can state the count upfront; use while for condition-driven logic.
Can break exit a nested loop in Python?
break exits only the innermost loop it is placed in. To exit an outer loop from inside an inner loop, use a flag variable set inside the inner loop and checked in the outer loop's condition, or restructure the logic into a function and use return.
What does pass do in a Python loop?
pass is a no-op statement — it does nothing at runtime. It is used when a loop body is syntactically required but no action is needed, for example as a placeholder while you build out a function incrementally.
How do you loop through a list with both index and value?
Use enumerate(): for i, val in enumerate(my_list) gives you index i and value val together, without manual index management or a separate counter variable.
What does range(0, 10, 2) produce?
range(0, 10, 2) produces 0, 2, 4, 6, 8 — five values. The stop value 10 is excluded. The step of 2 means every other integer starting from 0.
How do you avoid an infinite while loop?
Ensure the loop body contains a statement that eventually makes the condition False — usually an increment, decrement, or state change. Before writing a while loop, identify what changes per iteration and confirm it converges toward the exit condition.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)