473,753 Members | 7,743 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 #1
33 3857
Diez B. Roggisch 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.


I didn't realize that for...else existed, but according to the language
reference, the else clause gets executed unless the loop body exited due
to a break statement.

David

Jul 18 '05 #2

"David C. Fox" <da*******@post .harvard.edu> wrote in message
news:nr9tb.2005 90$Fm2.189136@a ttbi_s04...
Diez B. Roggisch 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.
I didn't realize that for...else existed, but according to the language
reference, the else clause gets executed unless the loop body exited due
to a break statement.


Yep. It's one of the three termination conditions for a loop. The problem
is that it's a really bad name, and the termination condition I'm most
interested
in catching is the one where the loop didn't execute at all.

John Roth

David

Jul 18 '05 #3
JCM
John Roth <ne********@jhr othjr.com> wrote:
....
Yep. It's one of the three termination conditions for a loop.


What are the three conditions? I know of two:

1 Reaching the end of the iteration
2 Breaking out

Jul 18 '05 #4
Diez B. Roggisch:
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?


To execute code only when the loop terminates normally, not when it
terminates because of a break statement.

It's been discussed before:
http://groups.google.nl/groups?q=%2B...ibm.com&rnum=3
http://groups.google.nl/groups?q=%2B...nxx.com&rnum=7
http://groups.google.nl/groups?hl=nl...com%26rnum%3D7

--
René Pijlman
Jul 18 '05 #5
Diez B. Roggisch wrote:
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?
for item in seq:
if item == target_item:
print "Found", item
break
else:
print "Nothing found, dude!"
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!"


which is usually written as:

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

or

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

</F>


Jul 18 '05 #6

"JCM" <jo************ ******@myway.co m> wrote in message
news:bp******** *@fred.mathwork s.com...
John Roth <ne********@jhr othjr.com> wrote:
...
Yep. It's one of the three termination conditions for a loop.
What are the three conditions? I know of two:

1 Reaching the end of the iteration
2 Breaking out

3. Not executing at all.

John Roth

Jul 18 '05 #7
JCM
John Roth <ne********@jhr othjr.com> wrote:
"JCM" <jo************ ******@myway.co m> wrote in message
news:bp******** *@fred.mathwork s.com...
John Roth <ne********@jhr othjr.com> wrote:
...
> Yep. It's one of the three termination conditions for a loop.


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.
Jul 18 '05 #8

"JCM" <jo************ ******@myway.co m> wrote in message
news:bp******** **@fred.mathwor ks.com...
John Roth <ne********@jhr othjr.com> wrote:
"JCM" <jo************ ******@myway.co m> wrote in message
news:bp******** *@fred.mathwork s.com...
John Roth <ne********@jhr othjr.com> wrote:
...
> Yep. It's one of the three termination conditions for a loop.

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.

John Roth
Jul 18 '05 #9

"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
Jul 18 '05 #10

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

Similar topics

24
2712
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
2522
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
1789
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
8936
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
1727
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
1870
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
9072
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
8896
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
9653
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
9333
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
6151
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4771
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
4942
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3395
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
2284
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.