while loop (Reposting On Python-List Prohibited)
Peter Otten
__peter__ at web.de
Wed Oct 12 06:15:56 EDT 2016
BartC wrote:
> On 12/10/2016 05:30, Lawrence D’Oliveiro wrote:
>> On Wednesday, October 12, 2016 at 11:23:48 AM UTC+13, BartC wrote:
>>> while n>=x:
>>> n=n-1
>>> print "*"* n
>>> else:
>>> print ("2nd loop exit n=",n,"x=",x)
>>
>> What is the difference between that and
>>
>> while n>=x:
>> n=n-1
>> print "*"* n
>> print ("2nd loop exit n=",n,"x=",x)
>>
>> ?
>>
>> None at all.
>>
>
> Not so much in this specific example: that message will be shown whether
> there have been 0 or more iterations of the loop body.
>
> But with 'else', if you see the message it means the while statement has
> been entered. Here:
>
> if cond:
> while n>=x:
> n=n-1
> print "*"* n
> else:
> print ("2nd loop exit n=",n,"x=",x)
Lawrence is right. The enclosing if doesn't make a difference.
> when cond is false, nothing will be printed. You then know the while
> statement hasn't been entered, so it's not looping for some other reason
> than its loop condition being false from the start.
>
> Another situation is when the loop body contains 'break'; then it will
> bypass the 'else' part.
This is the only case where while...else makes sense: the code in the else
suite is executed if and only if the break was not reached.
More information about the Python-list
mailing list