A loop repeats a block of code. Python has two loops: for, which goes through the items of a sequence, and while, which repeats as long as a condition is True.
What You Will Learn
- for loops with range(), lists and strings
- while loops
- break, continue and pass
- enumerate(), zip() and nested loops
Prerequisites
for Loop
fruits = ['apple', 'banana', 'mango']
for fruit in fruits:
print(fruit)
apple banana mango
range()
for i in range(5):
print(i, end=' ')
print()
for i in range(2, 11, 2):
print(i, end=' ')
Explanation: The stop value is never included.
| Call | Produces |
|---|---|
| range(5) | 0 to 4 |
| range(2, 6) | 2 to 5 |
| range(2, 11, 2) | 2, 4, 6, 8, 10 |
| range(5, 0, -1) | 5 down to 1 |
0 1 2 3 4 2 4 6 8 10
while Loop
count = 1
while count <= 5:
print(count)
count += 1
1 2 3 4 5
break and continue
for n in range(1, 10):
if n == 3:
continue # skip 3
if n == 6:
break # stop at 6
print(n)
1 2 4 5
else with Loops
for n in [3, 5, 7]:
if n % 2 == 0:
print('Found even')
break
else:
print('No even number')
Explanation: The else block runs only if the loop finished without break.
No even number
pass
for i in range(3):
pass # placeholder, does nothing
enumerate() and zip()
names = ['Asha', 'Ravi']
marks = [88, 92]
for i, name in enumerate(names, start=1):
print(i, name)
for name, m in zip(names, marks):
print(name, m)
1 Asha 2 Ravi Asha 88 Ravi 92
Nested Loops
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end='\t')
print()
1 2 3 2 4 6 3 6 9
Looping Over a Dictionary
student = {'name': 'Asha', 'age': 21}
for key, value in student.items():
print(key, '->', value)
name -> Asha age -> 21
Common Errors
| Problem | Cause and fix |
|---|---|
| Infinite while loop | Make sure the loop variable changes so the condition becomes False. |
RuntimeError: dictionary changed size during iteration |
Loop over a copy: for k in list(d): |
Practice Exercises
- Print the multiplication table of any number.
- Sum the numbers 1 to 100 with a while loop.
- Print all prime numbers below 50.
- Count the vowels in a string.
Interview Questions
Q: When does a loop else run?
When the loop ends without break.
Q: for vs while?
for iterates over a known sequence; while repeats until a condition is False.
Summary
Use for with range(), lists and dicts, while for condition-based repetition, and break/continue to control the flow.
Next: Python Numbers · Python Lists
Machine Learning Tutorials, Courses and Certifications