Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

python - While loop gives values equal to, even though it explicitly states 'less than' not 'less than or equal to'

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)
question from:https://stackoverflow.com/questions/65940647/while-loop-gives-values-equal-to-even-though-it-explicitly-states-less-than-n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...