Issue
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?
Solution
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:
count = 0
,count <= 5
->True
,count += 1
makescount = 1
, print1
.count = 1
,count <= 5
->True
,count += 1
makescount = 2
, print2
.count = 2
,count <= 5
->True
,count += 1
makescount = 3
, print3
.count = 3
,count <= 5
->True
,count += 1
makescount = 4
, print4
.count = 4
,count <= 5
->True
,count += 1
makescount = 5
, print5
.count = 5
,count <= 5
->True
,count += 1
makescount = 6
, print6
.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)
Answered By - Martijn Pieters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.