On 12/10/2016 11:15, Peter Otten wrote:
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.
The idea is to detect whether the while loop has been entered.
With while-else-print, it will always execute the else (assuming no
break). With while then print, you can't tell if it has attempted to or
not. My example above has wrapped the if-cond around the whole of
while-else because it has to (that's the advantage).
With a separate print it need not do that:
if cond:
while n>=x:
n=n-1
print "*"* n
print ("2nd loop exit n=",n,"x=",x)
With real code it may not be as easy to see. 'else' adds structure.
--
bartc
--
https://mail.python.org/mailman/listinfo/python-list