Class 9 Computer Science — Repeating while something is true
Follow a loop that keeps going while a condition holds, working out what it leaves behind and how many times it went round.
Name: ________________________
1.Look at the condition before you follow anything. What does this program print?
n = 5 while n > 10: n = n + 1 print(n)- a) 5
- b) 11
- c) 10
- d) 6
2.Money is put by each week until there is enough. What does this program print?
money = 50 weeks = 0 while money < 200: money = money + 25 weeks = weeks + 1 print(weeks)3.A second variable here does nothing but count the trips. What does the program print?
count = 0 total = 0 while total < 30: total = total + 7 count = count + 1 print(count)4.In each of these a variable starts at 0 and the body adds 1 to it every time round. Sort each condition by how many times the body runs.
Groups: The body runs 4 times · The body runs 7 times
- while n < 3 + 4:
- while n < 7:
- while n <= 3:
- while n <= 6:
- while n < 4:
- while n < 2 + 2:
5.This loop doubles a number until the condition stops holding. What does the program print?
n = 1 while n < 20: n = n * 2 print(n)6.In each of these a variable is changed as described and the loop keeps going while the variable is below 40. Put them in order of the value the variable is left holding, smallest first.
- Starts at 1 and is doubled each time
- Starts at 2 and is multiplied by 3 each time
- Starts at 6 and has 15 added each time
- Starts at 10 and has 9 added each time
7.Both variables change every time round here, and only one of them is in the condition. What does the program print?
total = 0 n = 1 while total < 20: total = total + n n = n + 1 print(n)8.The subtraction here takes the variable past the condition and keeps going. What does the program print?
n = 27 while n > 0: n = n - 4 print(n)
Answer key — Class 9 Computer Science — Repeating while something is true
- 1. a) 5
- 2. 6
- 3. 5
- 4. while n < 4: → The body runs 4 times; while n < 7: → The body runs 7 times; while n <= 3: → The body runs 4 times; while n <= 6: → The body runs 7 times; while n < 2 + 2: → The body runs 4 times; while n < 3 + 4: → The body runs 7 times
- 5. 32
- 6. 1. Starts at 10 and has 9 added each time 2. Starts at 6 and has 15 added each time 3. Starts at 2 and is multiplied by 3 each time 4. Starts at 1 and is doubled each time
- 7. 7
- 8. -1