1 of 6
A loop repeats a block of code multiple times. Python has two main types: for loops and while loops.
for LoopUse for when you know how many times to repeat.
for i in range(5): print(i)
Output:
0
1
2
3
4
range(5) gives you the numbers 0, 1, 2, 3, 4. The variable i takes each value, one at a time.
range() Explained| Code | Numbers produced |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
Two forms:
range(stop) β starts at 0, goes up to (but not including) stoprange(start, stop) β starts at start, goes up to stopfruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}")
Output:
I like apple
I like banana
I like cherry
The variable fruit takes each item in the list, one at a time.
while LoopUse while when you want to repeat until a condition becomes False.
count = 0 while count < 5: print(count) count += 1
Output:
0
1
2
3
4
Be careful: if the condition never becomes False, you get an infinite loop!
A very common pattern β start with a variable and build it up inside a loop:
total = 0 for i in range(1, 11): total += i print(total) # 55
This adds 1 + 2 + 3 + ... + 10 = 55.
break and continuebreak β exits the loop immediatelycontinue β skips to the next iterationfor i in range(10): if i == 5: break print(i) # Prints: 0 1 2 3 4
for i in range(5): if i == 2: continue print(i) # Prints: 0 1 3 4
for vs while β When to Use Which?Use for when... | Use while when... |
|---|---|
| You know the number of iterations | You don't know when to stop |
| Looping over a list or range | Waiting for user input |
| Counting from A to B | Running until a condition is met |
for loops repeat a known number of timeswhile loops repeat until a condition is Falserange(n) gives you numbers 0 to n-1for item in list:break exits, continue skipsβ Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit