Zion Zion - 2 months ago 8
Python Question

while loop and less than or equal to sign (Python)

So I was doing while loops and I noticed something strange.

count = 0

while count <= 5:
count += 1
print(count)


output:

1
2
3
4
5
6


it's not that I don't understand while loops. It's that how come the count is printed up to six? when it's supposed to print
count
only if
count
is less than or equal to 5?

and well 6 is beyond 5. why is this?

I know I could do

count = 0

while count != 5:
count += 1
print(count)


but I just want to understand why does putting
<=
behave in an odd way?

Answer

There is nothing odd about <=; your loop condition allows for numbers up to and including 5. But you increment count and then print it, so you will print 6 last.

That's because count = 5 satisfies your loop condition, then you add one to make it 6 and print. The next time through the loop count <= 5 is no longer true and only then loop ends.

So your code does this:

  1. count = 0, count <= 5 -> True, count += 1 makes count = 1, print 1.
  2. count = 1, count <= 5 -> True, count += 1 makes count = 2, print 2.
  3. count = 2, count <= 5 -> True, count += 1 makes count = 3, print 3.
  4. count = 3, count <= 5 -> True, count += 1 makes count = 4, print 4.
  5. count = 4, count <= 5 -> True, count += 1 makes count = 5, print 5.
  6. count = 5, count <= 5 -> True, count += 1 makes count = 6, print 6.
  7. count = 6, count <= 5 -> False, end the loop.

You could increment the counter after printing:

while count <= 5:
    print(count)
    count += 1

or you could use < to only allow numbers smaller than 5:

while count < 5:
    count += 1
    print(count)
Comments