#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)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?
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)20193819The 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)print() is in the wrong place and should be indented.total = 0 is in the body and resets the sum in every round.+= does not calculate reliably with decimal numbers.total = 0 is in the body and resets the sum in every round.7.0.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)4 63 124 6.255 34 6number > 10 no longer holds.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)
while count < 3: print(count)while count < 3: count += 1while count < 3: count -= 1while count > 3: count += 1while count < 3: print(count)count.while count < 3: count -= 1count keeps getting smaller and therefore stays below 3 for ever.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)
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)0 milk and 1 bread1 milk and 2 breadmilk 1 and bread 21 milk and 2 breadstart=1 the number begins at 1.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.