18. While loops
18.1. Events as conditions
x = 10
while x > 0 :
print(x)
x = x - 1
x = 10
18.2. Counters
18.3. Counting up
i is the counter.i starts off at 0 and is increased by 1 in the while loop line: i += 1.i += 1 is the same as i = i + 1i < 10, is True the while loop runs.i += 1 causes i to increase from 0 to 9.i is 10 since i < 10 will be False when i = 10.i = 0
while i < 10:
print(i)
i += 1
18.4. Counting down
i starts off at 5 and is decreased by 1 in the while loop line: i -= 1.i -+= 1 is the same as i = i - 1> sign when counting down.i is no longer greater than 1, i.e. when it is 1.i = 5
while i > 1:
print(i)
i -= 1
18.5. Step size
i += 2 sets a step size of 2.i = 0
while i < 11:
print(i)
i += 2
Tasks
Write a while loop that counts up from 1 to 5, printing the numbers 1, 2, 3, 4, 5.
Write a while loop that counts up from 3 to 12 in steps of 3, printing the numbers 3, 6, 9, 12.
Write a while loop that counts down from 9 to 1, printing the numbers 9, 8, 7, 6, 5, 4, 3, 2, 1.
Write a while loop that counts down from 24 to 18 in steps of 2, printing the numbers 24, 22, 20, 18.
Write 2 while loops to print 0 to 8 going up in 2s then 9 down to 1 going down in 2s.
Write a while loop that counts up from 1 to 5, printing the numbers 1, 2, 3, 4, 5.
i = 1
while i < 6:
print(i)
i += 1
Write a while loop that counts up from 3 to 12 in steps of 3, printing the numbers 3, 6, 9, 12.
i = 3
while i < 13:
print(i)
i += 3
Write a while loop that counts down from 9 to 1, printing the numbers 9, 8, 7, 6, 5, 4, 3, 2, 1.
i = 9
while i > 0:
print(i)
i -= 1
Write a while loop that counts down from 24 to 18 in steps of 2, printing the numbers 24, 22, 20, 18.
i = 24
while i > 17:
print(i)
i -= 2
Write 2 while loops to print 0 to 8 going up in 2s then 9 down to 1 going down in 2s.
i = 0
while i < 9:
print(i)
i += 2
i = 9
while i > 0:
print(i)
i -= 2