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


#1



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:
        break

than this?:
while count < 10: 
    print count
    count+=1


#2

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.


#3

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:
      break

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


#4

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.


#5

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

Otherwise it'll go straight to none.

Thanks!


#6