While Loops

Basic While Loop

  1. # while condition is True
  2. count = 0
  3. while count < 5:
  4. print(count)
  5. count += 1
  6. #ans: 0, 1, 2, 3, 4

While with Countdown

  1. # countdown
  2. x = 3
  3. while x > 0:
  4. print(x)
  5. x -= 1
  6. #ans: 3, 2, 1

While with Break

  1. # infinite loop with break
  2. x = 0
  3. while True:
  4. x += 1
  5. if x > 5:
  6. break
  7. #ans: x is 6

While with Increment

  1. # increment by different values
  2. x = 0
  3. while x < 10:
  4. x += 2
  5. #ans: x is 10 (after last iteration)

Exercises - Part 1

  1. # what is count after?
  2. count = 0
  3. while count < 5:
  4. count += 1
  5. #ans: count is 5

Exercises - Part 2

  1. # how many prints?
  2. x = 3
  3. while x > 0:
  4. print(x)
  5. x -= 1
  6. #ans: 3 prints (3, 2, 1)

Exercises - Part 3

  1. # what happens?
  2. x = 0
  3. while x < 5:
  4. x += 2
  5. #ans: x is 6 (after last iteration)

Exercises - Part 4

  1. # infinite loop?
  2. x = 0
  3. while x >= 0:
  4. x += 1
  5. if x > 5:
  6. break
  7. #ans: x is 6 (breaks when x becomes 6)

Exercises - Part 5

  1. # what is x?
  2. x = 10
  3. while x > 0:
  4. x -= 3
  5. #ans: x is -2 (10, 7, 4, 1, -2)

Exercises - Part 6

  1. # condition never true?
  2. x = 0
  3. while x > 0:
  4. x += 1
  5. #ans: loop never runs, x is 0

Exercises - Part 7

  1. # what prints?
  2. x = 1
  3. while x <= 4:
  4. print(x)
  5. x *= 2
  6. #ans: 1, 2, 4

Exercises - Part 8

  1. # tricky: what is x?
  2. x = 0
  3. while x < 3:
  4. x += 1
  5. else:
  6. x += 10
  7. #ans: x is 13 (3 + 10)

Exercises - Part 9

  1. # what is final value?
  2. x = 100
  3. while x > 1:
  4. x = x // 2
  5. #ans: x is 0 (100, 50, 25, 12, 6, 3, 1, 0)

Exercises - Part 10

  1. # condition check?
  2. x = 5
  3. while x:
  4. x -= 1
  5. #ans: x is 0 (5, 4, 3, 2, 1, 0)

Google tag (gtag.js)