Definition
📌 Loops
Python has two loop types: for (used to iterate over a sequence like a list, string, or range of numbers) and while (repeats while a condition is true).
Syntax
syntax
for item in iterable:
# code
while condition:
# codeExample
py
for i in range(1, 6):
print(i, end=" ")Output
output1 2 3 4 5
Important Points
range(start, stop)generates numbers fromstartup to, but excluding,stop.- Python's
forloop iterates directly over items — lists, strings, ranges — not a manual index counter. breakexits a loop early;continueskips to the next iteration.- There is no
do-whilein Python; simulate it withwhile True:plus abreak.
Common Mistakes
- Forgetting that
range(1, 6)stops before 6, not at 6. - Trying to use a C-style
for(int i=0;...)syntax — Python's for loop works differently. - Forgetting the colon
:after the loop header.
Interview Tip
🎯 Before your interview
Know that Python's for loop is really a "for-each" loop under the hood — it iterates over any iterable object, not just numeric ranges.
