Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • solve pattern problems using while
  • use sentinel-controlled loops
  • apply break and continue correctly
  • trace digit-based loops

Pattern 1: sum of first n numbers

n = int(input())
i = 1
total = 0
while i <= n:
    total += i
    i += 1
print(total)

Pattern 2: sum of digits

n = int(input())
s = 0
while n > 0:
    s += n % 10
    n //= 10
print(s)

Pattern 3: reverse a number

n = int(input())
rev = 0
while n > 0:
    d = n % 10
    rev = rev * 10 + d
    n //= 10
print(rev)

Pattern 4: sentinel input loop

Read numbers until user enters -1.
total = 0
x = int(input("Enter number (-1 to stop): "))
while x != -1:
    total += x
    x = int(input("Enter number (-1 to stop): "))
print(total)

break and continue

i = 1
while i <= 10:
    if i == 6:
        break
    print(i)
    i += 1
i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

Trap: continue without update

i = 0
while i < 5:
    if i == 2:
        continue
    i += 1
Issue:
  • when i == 2, it keeps repeating (infinite loop)

Exam hints and traps

  • in digit loops, use n //= 10 to shrink number
  • place update before continue if needed
  • sentinel value should be excluded from computation

Practice

  1. Count digits of a number using while.
  2. Print odd numbers from 1 to 19.
  3. Write loop to find smallest positive n such that sum 1+...+n >= target.

Quick answers

count = 0
while n > 0:
    count += 1
    n //= 10
i = 1
while i <= 19:
    print(i)
    i += 2