Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • explain why loops are needed
  • distinguish repetition from selection (if)
  • trace iterative logic using state tables
  • recognize loop-control variables

Why this week matters

In Week 2, you learned conditions and expressions.
In Week 3, you use them repeatedly with loops.
Without loops:
  • same statement must be written many times
  • code becomes long and error-prone
With loops:
  • concise code
  • easier updates
  • cleaner logic for counting and processing lists/strings

Repetition in daily coding

Common tasks requiring loops:
  • print 1 to 100
  • sum first n numbers
  • generate multiplication table
  • scan each character in a string
  • run input validation until correct input is entered

Iteration mindset

Every loop has 4 parts:
  1. initialization
  2. condition check
  3. body execution
  4. update (move toward stop condition)

Manual dry-run framework

For each iteration, track:
  • current values (i, sum, etc.)
  • condition result (True/False)
  • action taken in body
  • updated values

Example without loop (problem)

print(1)
print(2)
print(3)
print(4)
print(5)
If you need up to 100, this becomes unmanageable.

Example with loop (idea preview)

i = 1
while i <= 5:
    print(i)
    i += 1

Exam hints and traps

  • Loop question may hide a missing update line.
  • If condition never becomes False, loop is infinite.
  • if decides once; loop decides repeatedly.

Quick practice

  1. Write two tasks where loops are necessary.
  2. Identify loop-control variable in:
count = 10
while count > 0:
    print(count)
    count -= 2
  1. What happens if update line is removed?

Quick answers

  1. Sample: print first 100 numbers, compute factorial.
  2. count.
  3. Can become infinite loop (depends on condition).