473,769 Members | 5,836 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

for what are for/while else clauses

Hi,

today I rummaged through the language spec to see whats in the for ... else:
for me. I was sort of disappointed to learn that the else clauses simply
gets executed after the loop-body - regardless of the loop beeing entered
or not.

So where is an actual use case for that feature?

I imagined that the else-clause would only be executed if the loop body
wasn't entered, so I could write this

for r in result:
print r
else:
print "Nothing found, dude!"

instead of

if len(result):
for r in result
print r
else:
print "Nothing found, dude!"

waiting for enlightment,

Diez
Jul 18 '05
33 3861
Alex Martelli wrote:
in every single case, it means "run once, if and only if the
controlling condition is false".
I'm not sure what you mean by "the controlling condition" in this case.


the condition that controls if the conditional part of the statement
is executed. from what I can tell, that's the usual definition.
In a for/else or while/else construct, the only way to make your
assertion true is to define "the controlling condition" as "a break
[or return] interrupted the for or while loop [or an exception was
propagated]" -- basically (quibbles on returns and exceptions apart)
just what I said about "no break was executed".
for a while-statement, the controlling condition is the test at
the top.

for a for loop, the condition is "is there another item" (to quote the
language reference: "When the items are exhausted (which is imme-
diately when the sequence is empty) ... the loop terminates.".

for a try-except clause, the condition is "did the suite raise an
exception".
the fact that the 'controlling condition' is "a break statement
has executed"


that's not how it works.

</F>


Jul 18 '05 #21
Alex Martelli <al***@aleax.it > writes:
Python could presumably help a little by warning about an 'else' on
a for or while loop that contains no 'break' statements. But the
reason Python's for/else and while/else statements are not intuitive
to most people can be boiled down to identifying that "controllin g
condition" -- the fact that the 'controlling condition' is "a break
statement has executed" is """hardly obvious or most particularly "the
only obvious" interpretation" "", to repeat myself:-).


Hmm, I can't see the break here:
for x in []: print 'something'

.... else: print 'nothing'
....
nothing

(Not that I wouldn't argue that the semantics of else in loops are blindingly
obvious, but I can see the (albeit slightly strained) analogy with if/else).

'as
Jul 18 '05 #22
Fredrik Lundh wrote:
Alex Martelli wrote:
> in every single case, it means "run once, if and only if the
> controlling condition is false".


I'm not sure what you mean by "the controlling condition" in this case.


the condition that controls if the conditional part of the statement
is executed. from what I can tell, that's the usual definition.


We agree that it is the usual definition. We appear to disagree that
focusing on that condition is a sensible way to present (e.g.) the way
while/else works. E.g., consider:

while avalue < another: .... print avalue,
.... avalue += 1
.... else:
.... print 'else here'
....

versus
while avalue < another:
.... print avalue,
.... avalue += 1
.... if something(avalu e, another): break
.... else:
.... print 'else here'
....

When somebody else "will the else clause execute", I would answer
(for the first case) "yes [if the loop ever terminates]" -- and for
the second case, "if and only if the break does not execute [i.e.,
if the 'something' test is never satisfied while the controlling
condition holds]".

In the first case, it would make no difference whatsoever to
recode the loop as:

while avalue < another:
print avalue,
avalue += 1
print 'foo here'

Again, "foo here" gets printed (as long as the loop ever terminates).

But in the second case, where a guarded 'break' is involved, the
transliteration is not feasible (you'd have to add a 'flag' variable
in order to remove the 'else' and keep the same semantics).

It seems misleading to me to focus on the controlling condition, i.e.,
on whether "avalue < another" is still true, or not. In the second
version of the loop it may perfectly well be true that the controlling
condition is false when the predicate 'something' is satisfied --
nevertheless, if the predicate is satisfied and thus the break
executes, the "else" clause does not execute.

In a for/else or while/else construct, the only way to make your
assertion true is to define "the controlling condition" as "a break
[or return] interrupted the for or while loop [or an exception was
propagated]" -- basically (quibbles on returns and exceptions apart)
just what I said about "no break was executed".


for a while-statement, the controlling condition is the test at
the top.

for a for loop, the condition is "is there another item" (to quote the
language reference: "When the items are exhausted (which is imme-
diately when the sequence is empty) ... the loop terminates.".

for a try-except clause, the condition is "did the suite raise an
exception".
the fact that the 'controlling condition' is "a break statement
has executed"


that's not how it works.


In practice, it is (for both while and for, not for try; and net of
the already-interpolated distinguos about returns and exceptions).

When there is no 'break' in the loop's body, the 'else' clause is
useless: the body of the else clause would execute under exactly the
same conditions (i.e., if the loop ever terminates normally, w/o
return or exceptions) if the same statements were placed right after
the loop's end, rather than in an 'else' clause. The only practical
reason to ever have an 'else' clause on a for or while is to do
something different for a loop that terminates with a break, rather
than terminating "normally". Focusing on the 'break' being present
and executing therefore seems more practical to me, than focusing on
the "controllin g condition" (which may be false without this fact
causing the 'else' clause to execute -- if a break intervenes).
Alex

Jul 18 '05 #23
In article <ma************ *************** *********@pytho n.org>,
"Fredrik Lundh" <fr*****@python ware.com> wrote:
the fact that the 'controlling condition' is "a break statement
has executed"


that's not how it works.


But it is: the only time the else clause is _not_ executed is when the
loop was stopped due to a break statement:
for x in []: ... print x
... else:
... print "else"
...
else for x in [1]: ... print x
... else:
... print "else"
...
1
else for x in [1]: ... print x
... break
... else:
... print "else"
...
1


You're either speaking in tongues, or you're wrong. Am I missing
something?

Just
Jul 18 '05 #24
on confused.lang.p ython, Just wrote:
the fact that the 'controlling condition' is "a break statement
has executed"
that's not how it works.


But it is: the only time the else clause is _not_ executed is when the
loop was stopped due to a break statement:


the break statement has nothing to do with the else clause; the else
is executed when there's no more item in the sequence. if you break
or raise or return or yield-and-never-resume or call-and-never-return
your way out of the loop doesn't matter.

read the C code if you don't believe me.
You're either speaking in tongues, or you're wrong. Am I missing
something?


like Alex, you're confusing cause and effect. don't do that; things are
easier to understand if you explain how they actually work.

</F>


Jul 18 '05 #25
Alexander Schmolck wrote:
Alex Martelli <al***@aleax.it > writes:
Python could presumably help a little by warning about an 'else' on
a for or while loop that contains no 'break' statements. But the
reason Python's for/else and while/else statements are not intuitive
to most people can be boiled down to identifying that "controllin g
condition" -- the fact that the 'controlling condition' is "a break
statement has executed" is """hardly obvious or most particularly "the
only obvious" interpretation" "", to repeat myself:-).
Hmm, I can't see the break here:
for x in []: print 'something'

... else: print 'nothing'
...
nothing


Exactly because there is no 'break' in the loop's body, the 'else: '
clause-header is useless in this case; the code:

for x in []: print 'something'
print 'nothing'

(where the second print follows the whole loop rather than being
the body of its 'else' clause) would be quite equivalent.
(Not that I wouldn't argue that the semantics of else in loops are
blindingly obvious, but I can see the (albeit slightly strained) analogy
with if/else).


If I squint hard enough I can see the similarity, sure, but I keep
thinking that "how do I _USE_ this language feature" is a more generally
useful viewpoint than "how is this language feature implemented". And
the (modest) _usefulness_ of the else clause on for and while loops is
inevitably connected to the possibility that a 'break' in the loop's
body may execute. If there is no such possibility, you might as well
just code the statements right after the whole loop, rather than putting
them in an else clause.
Alex

Jul 18 '05 #26
On Fri, 14 Nov 2003 19:31:08 +0100, "Diez B. Roggisch" <de************ @web.de> wrote:
Hi,

today I rummaged through the language spec to see whats in the for ... else:
for me. I was sort of disappointed to learn that the else clauses simply
gets executed after the loop-body - regardless of the loop beeing entered
or not.

So where is an actual use case for that feature?

I imagined that the else-clause would only be executed if the loop body
wasn't entered, so I could write this

for r in result:
print r
else:
print "Nothing found, dude!"

instead of

if len(result):
for r in result
print r
else:
print "Nothing found, dude!"

waiting for enlightment,

My mnemonic is to think of the mysterious elses as coming after prefixed pseudo-code like:

if this_code_is_in terfered_with:
<loop code or try block>
else: # got to end of loop or end of try block without interference

hence
for x in []: pass ... else: print 'got to end of nothing without interference ;-)'
...
got to end of nothing without interference ;-)
try: pass ... except: pass
... else: print 'got to end of try: without interference.'
...
got to end of try: without interference.
while raw_input('whil e> '): ... if raw_input('brea k? ')=='y': break
... else: print 'got to end of while w/o interference'
...
while> asdad
break? asad
while> asdasd
break?
while>
got to end of while w/o interference
while raw_input('whil e> '):

... if raw_input('brea k? ')=='y': break
... else: print 'got to end of while w/o interference'
...
while> asd
break? y

Regards,
Bengt Richter
Jul 18 '05 #27
Fredrik Lundh wrote:
you mean you don't know how the for-loop checks if there's
another item in the sequence?

(hint: look for StopIteration in the docs)


This hardly seems like a very good mnemonic, since the for...else
construct predates iterators.

The whole point here is that the behavior of for...else isn't
intuitively obvious. Sure, you can rationalize it after the fact, but
you have to be familiar with that rationalization to claim it makes
intuitive sense.

In the face of language rejections like try...except... finally,
for...else does not at all seem like something that is intuitively
obvious. (There's no doubt it's useful, but it's hardly transparent.)

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \
\__/ It's only love that gets you through
-- Sade
Jul 18 '05 #28
In article <ma************ *************** *********@pytho n.org>,
"Fredrik Lundh" <fr*****@python ware.com> wrote:
for a while-statement, the controlling condition is the test at
the top.

for a for loop, the condition is "is there another item" (to quote the
language reference: "When the items are exhausted (which is imme-
diately when the sequence is empty) ... the loop terminates.".

for a try-except clause, the condition is "did the suite raise an
exception".


Interesting way to think about it. Thanks.

So in some sample code:

while some_condition:
some_action ()
else:
last_action ()
following_code ()

If the loop results in some_action being done, say, 17
times; then that means that some_condition was found true 17
times. The 18th time, some_condition is found to be false,
the else takes effect and last_action gets done one time.
The only wrinkle then is that the while loop construct
passes control to the following code after that one
last_action. But we expect that from a while loop.

The effect of a break in the suite controlled by the
while is to blow away execution of the whole while
construct, including the else.

As an explanation, I like it.

Regards. Mel.
Jul 18 '05 #29
Mel Wilson wrote:
for a while-statement, the controlling condition is the test at
the top.

for a for loop, the condition is "is there another item" (to quote the
language reference: "When the items are exhausted (which is imme-
diately when the sequence is empty) ... the loop terminates.".

for a try-except clause, the condition is "did the suite raise an
exception".
Interesting way to think about it. Thanks.

So in some sample code:

while some_condition:
some_action ()
else:
last_action ()
following_code ()

If the loop results in some_action being done, say, 17
times; then that means that some_condition was found true 17
times. The 18th time, some_condition is found to be false,
the else takes effect and last_action gets done one time.


imagine a dialect of Python that supports C-style goto's and labels.
in this dialect,

while some_condition:
some_action ()
else:
last_action ()

can be rewritten as

this_statement:
if some_condition:
some_action ()
goto this_statement
else:
last_action ()
next_statement:

(which, of course, is exactly what Python's current compiler does, but
on the bytecode level).

"break" and "continue" can now be rewritten as "goto next_statement"
and "goto this_statement" .

for "for-in" and "try-except", the code calculating the "some_condition "
value is a bit different, but the rest works in exactly the same way.

here's the for-in version:

<set up the iterator>
this_statement:
<fetch next value from iterator>
if <value found>:
variable = <value>
some_action ()
goto this_statement
else:
last_action ()
next_statement:

and here's the try-except version (somewhat simplified):

this_statement:
<enable error handling>
some_action ()
error_handler:
<disable error handling>
if <matching error occurred>:
some_action ()
else:
other_action ()
The only wrinkle then is that the while loop construct
passes control to the following code after that one
last_action. But we expect that from a while loop.
most Python statements pass control to the next statement
when they're done.
The effect of a break in the suite controlled by the
while is to blow away execution of the whole while
construct, including the else.

As an explanation, I like it.


me too.

</F>


Jul 18 '05 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
2714
by: Andrew Koenig | last post by:
PEP 315 suggests that a statement such as do: x = foo() while x != 0: bar(x) be equivalent to while True:
27
3079
by: Ron Adam | last post by:
There seems to be a fair amount of discussion concerning flow control enhancements lately. with, do and dowhile, case, etc... So here's my flow control suggestion. ;-) It occurred to me (a few weeks ago while trying to find the best way to form a if-elif-else block, that on a very general level, an 'also' statement might be useful. So I was wondering what others would think of it.
4
1425
by: Mohanasundaram | last post by:
Hi All, I saw in some code do{//for error jump /*Some code here*/ }while(0); Can anyone plese tell me what is the purpose of this code? There was a comment saying that //for error jump. What does it mean? There is no
4
2523
by: ECathell | last post by:
I had read an article at one time that suggested a pattern to get around deeply nested if..then..else hell... Can anyone point me in that direction? select case statements wont work for me in this instance -- --Eric Cathell, MCSA
2
1790
by: m.k.ball | last post by:
Thanks Rich - that's great. Before I found this group, I thought I had a reasonable understanding of SQL (well, MySQL's implementation of it, at least) but the truth is there are great chunks that I have no knowledge of. I've read three or four books about MySQL and PHP all of which gave (in retrospect) very basic examples of the use of SQL, and focussed on features such as MySQL's date and time handling functions that are well covered in...
2
8937
by: Curtiosity | last post by:
I have done a create or replace view called creditcard1. If I do a "select * from creditcard1" it retrieves the data just fine. If I try to do a statement where I am listing the column names it doesn't recognize them. create or replace view creditcard1 as select pidm ,tbraccd_term_code as "Term" ,tbraccd_detail_code as "Detail_Code" ,tbbdetc_desc as "Detc_Desc" ,tbraccd_tran_number as "Tran_Number" ,DECODE(tbbdetc_type_ind,...
12
1730
by: Eighty | last post by:
I suggest a new extension of the list comprehension syntax: which would be equivalent to list(itertools.takewhile(cond, xs)) + Since Python favors list comprehensions over map, filter, and reduce, this would be the preferred way to do this
25
1872
by: metaperl.etc | last post by:
A very old thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/2c5022e2b7f05525/1542d2041257c47e?lnk=gst&q=for+else&rnum=9#1542d2041257c47e discusses the optional "else:" clause of the for statement. I'm wondering if anyone has ever found a practical use for the else branch?
5
2397
by: Jyotirmoy Bhattacharya | last post by:
I'm a newcomer to Python. I have just discovered nested list comprehensions and I need help to understand how the if-clause interacts with the multiple for-clauses. I have this small program: def multab(n): print 'multab',n return print
0
9416
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10199
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8861
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7393
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5293
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5433
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3948
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2810
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.