while loop (Reposting On Python-List Prohibited)
BartC
bc at freeuk.com
Wed Oct 12 05:53:28 EDT 2016
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)
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.
--
Bartc
More information about the Python-list
mailing list