user11761997
user11761997

Reputation:

why while loop get incorrect outcome

The question is: 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.

Input: 8 Expected output: 8 16 32 64

but actual output:

8
16
32
64
128

This is my code

num_insects = int(input("")) 

while num_insects <= 100:
   if num_insects > 0:
   num_insects *= 2
   print(num_insects)

Upvotes: 0

Views: 4000

Answers (4)

rmazur7831
rmazur7831

Reputation: 11

This was a good challenge activity. Here is the code after the input()

while (num_insects <=100):
    if num_insects >= 0:
      print(num_insects, end= ' ')
      num_insects = num_insects * 2

Another fun activity was the gambling challenge: all you need to do is write the while statement to include: while (keep_going != 'n'):

That was an easy one, figured I would include that just in case someone was pulling out their hair.

Upvotes: 0

Amanda Z Eckardt
Amanda Z Eckardt

Reputation: 1

Given positive integer num_insects, write a while loop that prints, then doubles, num_insects each iteration. Print values ≤ 100. Follow each number with a space.

Sample output with input: 8 8 16 32 64

num_insects = int(input()) # Must be >= 1

while num_insects <= 100:
  print(num_insects, end = ' ')
  num_insects = num_insects *2

Upvotes: 0

Adam_Karlstedt
Adam_Karlstedt

Reputation: 306

This is because when num_insects is 64, the conditional num_insects <= 100 is true. It then is multiplied by two, which is 128 and is then printed. To fix this, you'll want to check if num_insects * 2 is less than 100 like the following:

num_insects = int(input("")) 

while num_insects * 2 <= 100:
   if num_insects > 0:
      num_insects *= 2
      print(num_insects)

Upvotes: 1

That1Guy
That1Guy

Reputation: 7233

When the loop that prints 128 begins, the value of num_insects meets the while-loop criteria. After the loop begins, it is changed.

Does this make sense to you?

Let's look at the final iteration.

while num_insects <= 100: # Current value is 64
    if_num_insects >0:    # This is true. 64 is greater than 0
        num_insects *= 2  # Double 64. Now it is 128
    print(num_insects)    # Prints 128

At this point, num_insects <= 100 is no longer true and the loop exits.

Upvotes: 0

Related Questions