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
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to