Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • write correct while loop syntax
  • explain execution flow line by line
  • avoid infinite-loop mistakes
  • solve simple counting tasks with while

Syntax

while condition:
    # loop body
Rule:
  • loop runs while condition is True
  • stops when condition becomes False

Execution flow

  1. evaluate condition
  2. if True, run body
  3. update loop variable
  4. return to step 1
  5. if False, exit loop

Counting example

i = 1
while i <= 5:
    print(i)
    i += 1
Output:
1
2
3
4
5

Dry-run table

Iterationi beforecondition i <= 5printedi after
11True12
22True23
33True34
44True45
55True56
stop6False--

Reverse counting example

i = 5
while i >= 1:
    print(i)
    i -= 1

Infinite loop trap

i = 1
while i <= 5:
    print(i)
Issue:
  • i never changes, condition always True

while with boolean input loop

ans = "yes"
while ans == "yes":
    print("Running task...")
    ans = input("Continue? yes/no: ").strip().lower()

Exam hints and traps

  • update must move variable toward stop condition
  • indentation errors can move update outside loop
  • while True needs explicit break inside

Practice

  1. Print even numbers from 2 to 20.
  2. Print numbers from 10 to 1.
  3. Find error:
i = 1
while i < 5:
print(i)
    i += 1

Answer key

i = 2
while i <= 20:
    print(i)
    i += 2
i = 10
while i >= 1:
    print(i)
    i -= 1
  1. Indentation error (print(i) must be indented in loop block).