A while loop repeats its body as long as a condition remains True. You control when it stops.
Infinite loop: If the condition never becomes False, the program hangs forever. Always make sure the loop body changes something that affects the condition.
Output: 5 4 3 2 1 Blast off!
n -= 1 decrements n each iteration until n reaches 0, making the condition False.
A for loop iterates over a sequence — a range of numbers, a list, a string, etc.
range() generates a sequence of integers:
| Call | Produces |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(2, 7) | 2, 3, 4, 5, 6 |
range(0, 10, 2) | 0, 2, 4, 6, 8 |
range(10, 0, -1) | 10, 9, 8, ..., 1 |
Prints the 7 times table from 7x1=7 to 7x10=70.
| Keyword | Effect |
|---|---|
break | Exit the loop immediately |
continue | Skip the rest of this iteration; go to next |
else on a loop | Runs after loop finishes normally (not via break) |
Output: Found even: 4
The inner loop runs fully for each iteration of the outer loop. end="" prevents print from adding a newline.
Use a for loop to compute and print the sum of all integers from 1 to N (inclusive).
range(1, n+1) goes from 1 to n inclusive. The formula shortcut is n*(n+1)//2.Pick a secret number (hard-code it). Use a while loop to keep asking the user to guess until they get it right.
Use nested loops and the modulo trick to print all prime numbers from 2 to N.
What does range(1, 6) produce?
range(start, stop) goes up to but does NOT include stop. range(1,6) = 1,2,3,4,5.
range(start, stop) uses start as the first value. range(1,6) starts at 1.
range(1,6): starts at 1 (not 0), ends before 6, so: 1,2,3,4,5.
What is the risk of a while loop?
while and for have similar performance. The danger of while is an infinite loop if the condition never becomes False.
break exits any loop - while or for. It's the same keyword for both.
while condition: - the condition can be anything. Counting direction depends on how you write the body.
What does continue do inside a loop?
break exits the entire loop. continue only skips the rest of the current iteration and moves to the next one.
continue is a flow control statement - it immediately jumps to the next iteration without any delay.
continue moves to the next iteration (incrementing the counter / moving to the next item). It does not restart from zero.
How many times does this print? for i in range(3): for j in range(2): print(i, j)
Nested loops multiply: outer 3 iterations * inner 2 iterations = 6 prints.
Nested loops: each of the 3 outer iterations runs the full inner loop of 2. Total = 3 x 2 = 6.
The inner loop runs 2 times, but it runs once for each of the 3 outer iterations: 3 x 2 = 6.
The else clause on a for loop runs when:
An unhandled exception inside a loop propagates outward - it does not trigger the else clause.
else also runs for an empty range - but the key purpose is to detect 'loop finished without break'.
else does not care how many iterations ran. It only cares whether break was used. No break = else runs.