0

I have a while loop question that is stumping me. Below is a simple illustration of what is happening in my code - I ask the while loop to stop when the condition is less than, but it gives the values as if it stated less than or equal to. Does anyone know what i have done wrong?

A = 10.0
B = 20.0
x = 1.0

while ((A < 13.0) and (B < 23.0)):
    A += x
    B += x
    print(A, B)

    if x > 100.0:
       break
    
   x += 1.0

print(x)
jeans11
  • 3
  • 2
  • After it was "less than", there is something added, so it might not be "less than" anymore. – mkrieger1 Jan 28 '21 at 15:57
  • Keep in mind that comparing floating-point numbers for equality causes special problems: see [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – Karl Knechtel Aug 11 '22 at 06:04

4 Answers4

1

A and B equal 13 and 23 after the second loop iteration, which returns a FALSE in your while condition, thus the loop stops.

SuperTully
  • 319
  • 1
  • 6
0

You add 1 to A and B after it checks the condition. The loop isn’t some eternal contract within itself; it just checks at the top whether to execute all the instructions inside it, then go to the top and check again.

You could move those instructions after the printing, but then you’d be printing 10 and 20, which you aren’t so far. Otherwise, put another check inside the loop before printing.

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
  • 1
    Thank you all!! This has been very helpful, I added an extra check in the loop itself and fixed my problem. Thanks all for pointing out something I missed – jeans11 Jan 28 '21 at 16:27
0

The while is correct, but notice that you will sum the "x" value after the last loop.

A = 10.0
B = 20.0
x = 1.0

while ((A < 13.0) and (B < 23.0)):
    print('Here they are less then',A,B)
    A += x
    B += x
    print(A, B,x)

    if x > 100.0:
       break
    
    x += 1.0
Filipe
  • 169
  • 5
0

To explain that, we have to break down the code:

First, It initializes A, B and x. then it goes into the loop. since both the conditions are correct, it passes through.

Now notice you have added 1.0 to x. That makes x = 2.0.

Now we go back to the loop and it checks the conditions. 11.0 and 21.0 pass.

However, x is now 2.0. So we add 2.0 to A and B. Thus making them 13.0 and 23.0. It then prints it.

So the loop is working perfectly, its the way you have positioned the code that messes it up.

Ismail Hafeez
  • 730
  • 3
  • 10