#separator:tab #html:true #tags:python-loops-quiz #columns:Front Back

What does this program print?

for number in range(2, 10, 3):
print(number)
  1. 2, 5 and 8, each number on a line of its own
  2. 2, 5, 8 and 11
  3. 3, 6 and 9
  4. 2, 3, 4, 5, 6, 7, 8 and 9

range(start, end, step) begins at start, counts in steps of step and stops before end: 2, 5, 8.

"

How often does for i in range(5): print(""Hello"") print the greeting?

  1. Four times
  2. Five times
  3. Six times
"

With one argument, range() starts at 0 and ends before the number, and so range(5) gives exactly five numbers and the loop five rounds.

What does this program print?

total = 0
for number in [4, 7, 1, 8]:
if number > 3:
total += number
print(total)
  1. 20
  2. 19
  3. 3
  4. 8

The accumulator starts at 0, and in every round in which the number is greater than 3 it is added: 4, then 11, then 19.

Someone wants to add up the prices and gets 3.5. Why?

for price in [2.5, 1.0, 3.5]:
total = 0
total += price
print(total)
  1. print() is in the wrong place and should be indented.
  2. total = 0 is in the body and resets the sum in every round.
  3. += does not calculate reliably with decimal numbers.

An accumulator gets its starting value before the loop. In the body it is set back to 0 in every round, and at the end it holds only the last price.

What does this program print?

number = 100
rounds = 0
while number > 10:
number = number // 2
rounds += 1
print(rounds, number)
  1. 4 6
  2. 3 12
  3. 4 6.25
  4. 5 3

The condition is checked before every round: 100, 50, 25 and 12 are greater than 10, 6 no longer is. That gives four rounds and the final value 6.

Which of these loops never stop if count is 0 beforehand? (several are right)

  1. while count < 3: print(count)
  2. while count < 3: count += 1
  3. while count < 3: count -= 1
  4. while count > 3: count += 1

A while loop ends only if its body eventually makes the condition false. If a program in the browser does not stop, the Stop button ends it.

For which tasks is while the right loop? (several are right)

  1. Writing every item of a shopping list on a line of its own
  2. Asking for the age until a number above 0 is entered
  3. Printing the numbers from 1 to 10
  4. Working out after how many years savings have doubled

for fits when a list, a text or a fixed number of rounds sets the course, while when the end only shows up in the loop.

"

What does this program print?

for number, item in enumerate([""milk"", ""bread""], start=1):
print(number, item)
  1. 0 milk and 1 bread
  2. 1 milk and 2 bread
  3. milk 1 and bread 2
"

enumerate() gives the number and the element in every round, the loop shares them out to number and item, and start=1 makes counting begin at 1.