473,769 Members | 1,882 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
Terry Reedy wrote:
"Diez B. Roggisch" <de************ @web.de> wrote in message
news:bp******** *****@news.t-online.com...
I imagined that the else-clause would only be executed if the loop


body
wasn't entered, so I could write this


...
waiting for enlightment,

Try the following which I recently thought up.
You are familiar with this:

if cond: t()
else: f()

meaning, if cond is false, do f(). Now

while cond: t()
else: f()

means if and when cond is false, do f(). To make the parallel
clearer, consider this C-like pseudopython equivalent:

label: loop
if cond:
t()
goto loop
else: f()

If (and now when, because of the looping) cond is false, do f(). Now,

for i in seq: t()
else: f()

translates to something like

__i, __istop = 0, len(seq)
while __i < __istop:
i = seq[__i]
t()
else: f()

which in turn could be translated to an if with goto, so that f
executes if/when the sequence is exhausted.

In summary, the else clause executes if/when the loop condition
evaluates as false, just as with else clauses and if conditions. The
difference is the repeated instead of just once testing of the
condition. Break aborts this repeated testing and bypasses the else
clause, as it should because the condition was always true, as also
happens with true if conditions.

Terry J. Reedy


terry,

thnak you for your very clear and consice explanation.

bryan

Jul 18 '05 #11
I personally consider the "else" clause a wart of Python.
I never remember exactly what it is doing, and I have to look at the
manual each time; moreover I don't see it giving any significant advantage
to the language (other languages live very well without). So, I would be
happy to have it removed, even if I am sure it will never happen :-(
Am I the only one who think so?

Michele
Jul 18 '05 #12
Michele Simionato wrote:
I personally consider the "else" clause a wart of Python.
I never remember exactly what it is doing, and I have to look at the
manual each time; moreover I don't see it giving any significant
advantage
to the language (other languages live very well without). So, I would
be
happy to have it removed, even if I am sure it will never happen :-(
Am I the only one who think so?


I actually like it, and have used it with the `for' and `while' control
structures (although I only recently found out it is also available with
`try' and had that functionality to EmPy). For some reason I can always
remember what it does, even though I agree it's not very memorable. I
will readily admit that `else' is not a particularly enlightening name
for the functionality it represents, but I'm not sure I could come up
with a one-word substitute that would be much more enlightening.

I do think it is highly ironic that a unified try...except... finally
construct was removed because it was allegedly not intuitive enough, but
for...else, while...else, and even try...except... else (!) stayed with
no such complaint.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \
\__/ There's this perfect girl / Someone no one can see
-- Lamya
Jul 18 '05 #13
Erik Max Francis <ma*@alcyone.co m> wrote in message news:<3F******* ********@alcyon e.com>...
I do think it is highly ironic that a unified try...except... finally
construct was removed because it was allegedly not intuitive enough, but
for...else, while...else, and even try...except... else (!) stayed with
no such complaint.


It is strange that I do feel try...except... else very natural and I use
the construct all the time... mah!

My complaint is only against else in while and for.

Michele
Jul 18 '05 #14
Michele Simionato wrote:
I personally consider the "else" clause a wart of Python.
I think it depends on what statements we're talking about, but, yes,
restricting the discussion to for/else and while/else (if/else and
try/except/else being very different) I understand why you would.
I never remember exactly what it is doing, and I have to look at the
I haven't had the problem, myself, but I have seen others believe that the
else clause would run if the body was never run (for on an empty sequence,
while on a condition that's false since the first check), as in
(hypothetically )

for item in bought:
print 'Bought item', item
else:
print "No items were bought"

being short for

if bought:
for item in bought:
print 'Bought item', item
else:
print "No items were bought"

which might make sense (if bought were a non-reiterable, the if/else
construct has problems while the imaginary interpretation of the for/else
one would still work just fine). In this way, Python's for/else and
while/else do fail the least-astonishment test for at least some learners
(taking "else" to mean "no break was executed in the body" is hardly
obvious or most particularly "the only obvious" interpretation) .
manual each time; moreover I don't see it giving any significant advantage
to the language (other languages live very well without). So, I would be
The fact that other languages lack a construct isn't necessarily
significant, of course -- most lack, e.g., classes as first-class objects,
yet Python's vastly better for having them. Still, it is indeed arguable
that for/else buys you little -- just a flag setting and checking when you
do use it, i.e., at most.
happy to have it removed, even if I am sure it will never happen :-(
Right, it's unlikely -- I haven't it seen proposed as a candidate to go
away in 3.0.
Am I the only one who think so?


Probably not; even though on the whole I disagree, I don't consider your
position at all "strange", nor my opposition particularly strong, therefore
I suspect that many at least mildly agree with you.

The classic homework one should do when considering a language
construct is "how is it used in the standard library". Have you examined
the uses of for/else and while/else there?
Alex

Jul 18 '05 #15
Alex Martelli wrote:
(taking "else" to mean "no break was executed in the body" is hardly
obvious or most particularly "the only obvious" interpretation) .


that's not what it means, of course.

in every single case, it means "run once, if and only if the
controlling condition is false".

</F>


Jul 18 '05 #16
JCM
John Roth <ne********@jhr othjr.com> wrote:
....
>> What are the three conditions? I know of two:
>>
>> 1 Reaching the end of the iteration
>> 2 Breaking out
> 3. Not executing at all.
I see that as an example of #1.

But it isn't. See what your code looks like with an
empty file, for example. Or even worse, see what it
would look like if you have to use a generator where
you can't test for an empty sequence.


Iterating over an empty file behaves as I expect--the loop terminates
after zero iterations, one time for each line. I'm not sure what you
mean about generators... If you have a generator that never yields
anything:

def g():
if 0:
yield 'nothing'

(is there a better way of writing one?)
then the loop

for x in g():
print x

also terminates after zero iterations.
Jul 18 '05 #17
Fredrik Lundh wrote:
Alex Martelli wrote:
(taking "else" to mean "no break was executed in the body" is hardly
obvious or most particularly "the only obvious" interpretation) .


that's not what it means, of course.

in every single case, it means "run once, if and only if the
controlling condition is false".

</F>


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

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".

A reasonably-common newbie error is to code, for example:

for purchase in purchases:
print 'Purchased:', purchase
else:
print "Nothing was purchased"

taking "the controlling condition" to be the obvious one, i.e., the
sequence the 'for' is iterating on. Or, similarly:

while current_value < threshold:
process_high_va lue(current_val ue)
current_value = compute_next_va lue()
else:
alert_no_high_v alues(threshold )

taking "the controlling condition" to be the obvious one, i.e., the
"current_va lue < threshold" conditions that controls the 'while'.

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:-).
Alex

Jul 18 '05 #18
Fredrik Lundh wrote:
that's not what it means, of course.

in every single case, it means "run once, if and only if the
controlling condition is false".


Where's the controlling condition in

for x in sequence:
...
else:
...

?

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \
\__/ Get married, but never to a man who is home all day.
-- George Bernard Shaw
Jul 18 '05 #19
Erik Max Francis wrote:
that's not what it means, of course.

in every single case, it means "run once, if and only if the
controlling condition is false".


Where's the controlling condition in

for x in sequence:
...
else:
...

?


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)

</F>


Jul 18 '05 #20

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
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
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
9849
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
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...
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
2
3551
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.