Warmup

Write a while loop that counts up from 0 to 10 and then prints "done!"

Agenda / Looking ahead

Today:

  • Assignment 2.5
  • Module 2 Quiz due

Tomorrow:

  • Unit 2 Quiz ('if/elif/else' and 'while')
  • Lesson 2.6 ('for' loops)

Lesson 2.5

More with While Loops

Nesting if inside while

  • You can put any code inside a loop, even another if
x = 5
while x > 0:
    if x % 2 == 0:
        print(x, "is even")
    else:
        print(x, "is odd")
    x = x - 1

While–Else

  • else can follow a while
  • Runs if the loop finishes normally (not with break)
n = 3
while n > 0:
    print(n)
    n = n - 1
else:
    print("Loop finished!")

Break statement

  • Ends the loop immediately
while True:
    word = input("Type 'exit' to quit: ")
    if word == "exit":
        break

Continue statement

  • Skips the rest of this iteration, goes to next cycle
x = 0
while x < 5:
    x = x + 1
    if x == 3:
        continue
    print(x)

Classroom Question

What will this print?

x = 0
while x < 4:
    x = x + 1
    if x == 2:
        continue
    if x == 3:
        break
    print(x)

Practice Challenge

Write a program that:

  • Keeps asking for numbers
  • Skips negative numbers (use continue)
  • Stops completely if the user types 0 (use break)
  • Otherwise prints the number