CS 111 › Lesson 4 of 12

Loops: while and for

Lesson 4 · CS 111: Programming I — Python · OKSTEM College

while Loops

A while loop repeats its body as long as a condition remains True. You control when it stops.

while condition: # body executes repeatedly # something must eventually make condition False!

Infinite loop: If the condition never becomes False, the program hangs forever. Always make sure the loop body changes something that affects the condition.

Example - Countdown

n = 5 while n > 0: print(n) n -= 1 # n = n - 1 print("Blast off!")

Output: 5 4 3 2 1 Blast off!

n -= 1 decrements n each iteration until n reaches 0, making the condition False.

for Loops & range()

A for loop iterates over a sequence — a range of numbers, a list, a string, etc.

for variable in sequence: # body runs once per item

range() generates a sequence of integers:

CallProduces
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

Example - Multiplication table

for i in range(1, 11): print(f"7 x {i} = {7 * i}")

Prints the 7 times table from 7x1=7 to 7x10=70.

break, continue, else

KeywordEffect
breakExit the loop immediately
continueSkip the rest of this iteration; go to next
else on a loopRuns after loop finishes normally (not via break)
# Find first even number in a list numbers = [1, 3, 7, 4, 9] for n in numbers: if n % 2 == 0: print(f"Found even: {n}") break else: print("No even numbers found")

Output: Found even: 4

Nested Loops

# Print a multiplication grid for row in range(1, 4): for col in range(1, 4): print(f"{row * col:3}", end="") print() # newline after each row

The inner loop runs fully for each iteration of the outer loop. end="" prevents print from adding a newline.

Practice Problems

Problem 1 - Sum of 1 to N

Use a for loop to compute and print the sum of all integers from 1 to N (inclusive).

n = int(input("N: ")) total = 0 for i in range(1, n + 1): total += i print(f"Sum: {total}")
Note: range(1, n+1) goes from 1 to n inclusive. The formula shortcut is n*(n+1)//2.

Problem 2 - Guess the number (while loop)

Pick a secret number (hard-code it). Use a while loop to keep asking the user to guess until they get it right.

secret = 42 guess = 0 while guess != secret: guess = int(input("Guess: ")) if guess < secret: print("Too low") elif guess > secret: print("Too high") print("Correct!")

Problem 3 - Print only primes up to N

Use nested loops and the modulo trick to print all prime numbers from 2 to N.

n = int(input("N: ")) for num in range(2, n + 1): is_prime = True for d in range(2, num): if num % d == 0: is_prime = False break if is_prime: print(num)
The break exits the inner loop early once we know it's not prime - no need to keep checking.

Knowledge Check

What does range(1, 6) produce?

range stop is exclusive - 6 is not included.
Correct - stop is exclusive.
range(1,6) starts at 1, not 0.
Both start and stop are off.
Quick Recap

range(start, stop) goes up to but does NOT include stop. range(1,6) = 1,2,3,4,5.

Quick Recap

range(start, stop) uses start as the first value. range(1,6) starts at 1.

Quick Recap

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?

Speed difference is negligible; the real risk is correctness.
Correct - always ensure the loop body modifies the condition.
break works in both while and for loops.
while loops can count up, down, or iterate based on any condition.
Quick Recap

while and for have similar performance. The danger of while is an infinite loop if the condition never becomes False.

Quick Recap

break exits any loop - while or for. It's the same keyword for both.

Quick Recap

while condition: - the condition can be anything. Counting direction depends on how you write the body.

What does continue do inside a loop?

That is break.
Correct.
continue has nothing to do with timing.
continue does not reset the loop variable.
Quick Recap

break exits the entire loop. continue only skips the rest of the current iteration and moves to the next one.

Quick Recap

continue is a flow control statement - it immediately jumps to the next iteration without any delay.

Quick Recap

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)

The outer loop runs 3 times but the inner runs 2 times per outer iteration.
5 = 3+2, but nested loops multiply, not add.
Correct - 3 outer x 2 inner = 6 total prints.
Only the inner loop count, missing the outer multiplier.
Quick Recap

Nested loops multiply: outer 3 iterations * inner 2 iterations = 6 prints.

Quick Recap

Nested loops: each of the 3 outer iterations runs the full inner loop of 2. Total = 3 x 2 = 6.

Quick Recap

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:

Exceptions propagate past else; they don't trigger it.
Interesting edge case - this also triggers else. But the main answer is the loop completed normally.
Correct - else signals the loop exhausted normally.
else does not count iterations.
Quick Recap

An unhandled exception inside a loop propagates outward - it does not trigger the else clause.

Quick Recap

else also runs for an empty range - but the key purpose is to detect 'loop finished without break'.

Quick Recap

else does not care how many iterations ran. It only cares whether break was used. No break = else runs.