Break - Why bother setting While True, when you can set While count>10 straightaway?


In Break, I'm looking at the code but i don't see the practical use of setting While True then breaking afterwards. Why not set While [condition] straight away?

Also the description adds a strange comment :"The difference here is that this loop is guaranteed to run at least once." What does this mean?

Replace this line with your code. 
Why do this:
while True:
    print count
    count += 1
    if count >= 10:

than this?:
while count < 10: 
    print count


Specifically, how would you do this? You can post some code to demonstrate that.

The first loop will run until the break is executed, so it runs at least once, regardless of how count was initiated, as long as it is an int. When the if condition becomes True, the break will be executed, and for that if condition to become True, the loop, as given, must execute.

EDIT (February 19, 2017): Concerning "... as long as it is an int ...", a float would also suffice, though an int is usually more appropriate for counting.


Thank you for your prompt reply.

I mean, for example,

While count>5:

this oneliner above settles it.

whereas setting it like below needs a break

While True:

I guess I'm just really asking if there's a practical difference. Silly question it might seem!


Let's consider what happens if, prior to each of the loops, we have this ...

count = 11

How would the execution differ for each of the loops?

You can try it out if you want, then observe the difference in output.


Ah I see, so that's what it means to be guaranteed to run at least once.

Otherwise it'll go straight to none.