Interview Questions
Loops · Study material
Loops – Interview Questions
1. What loops does Python have?
for (over the items of an iterable) and while (while a condition is true). There is no do-while.
2. What does range(2, 10, 3) produce?
2, 5, 8 – stop is excluded.
3. When does the else block of a loop run?
When the loop finishes without break – the for iterable is exhausted or the while condition becomes false.
4. Difference between break, continue and pass?
break exits the loop, continue jumps to the next iteration, pass does nothing.
5. What is the value of the loop variable after the loop?
The last value it was bound to; it is not deleted. If the loop never ran, it is not defined.
6. Why should you not modify a list while iterating over it?
Removing or inserting items shifts positions, so items are skipped or repeated. For dicts and sets, changing the size raises RuntimeError.
7. What does enumerate() do?
Yields (index, item) pairs; start= sets the first index.
8. What does zip() do with lists of different lengths?
Stops at the shortest. itertools.zip_longest pads instead; zip(strict=True) raises an error (3.10+).
9. How do you emulate do-while?
while True: body; if not condition: break.
10. How do you exit nested loops?
Return from a function, use a flag, or raise and catch an exception.
11. Is range a list?
No, it is a lazy, immutable sequence object; list(range(…)) builds a list.
12. How do you loop over a dictionary's keys and values?
for key, value in d.items():.
13. Does changing the loop variable inside a for loop affect the iteration?
No. The next pass rebinds it to the next item from the iterator.
14. How do you iterate backwards?
reversed(seq), seq[::-1], or range(n - 1, -1, -1).
15. What is an infinite loop and how do you stop one?
A loop whose condition never becomes false; a break inside it (or Ctrl+C when running) ends it.