Given positive integer num_insects, write a while loop that prints that number doubled up to, but without exceeding 100. Follow each number with a space.
Sample output with input: 8
8 16 32 64
Here's what I havenum_insects = 8 # Must be >= 1print(num_insects, '', end='')while num_insects <= 100 : num_insects = num_insects * 2 print(num_insects,'', end="")This code prints the number 128 even thought the loop is set to end after 100? Why is that?

Respuesta :

tonb

Answer:

The while loop is executed one more time when num_insects is 64. It gets doubled and 128 gets printed. Then the while loop is not executed anymore since 128 exceeds 100.

So the reason you see 128 is because the multiplication by 2 happens inside the loop before you print. You enter it with 64, but by the time you get to the print statement, it was already multiplied.

The solution is to switch the print and the multiply:

num_insects = 8 # Must be >= 1

while num_insects <= 100 :

   print(num_insects,'', end="")

   num_insects = num_insects * 2

This has one added advantage that the very first print statement outside the loop can be removed.