473,769 Members | 3,567 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 3863
"Fredrik Lundh" <fr*****@python ware.com> wrote in message news:<ma******* *************** **************@ python.org>...
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.


On the other hand, I only think it's in the case of a break
in block that...

while condition:
block
else:
print "Loop finished"

....will behave differently than...

while condition:
block
print "Loop finished"

So, unless you use a break in the block, the else statement
is just noise: an extra line of code and additional whitespace
for the following statement(s).

It's only together with the python idiom of breaking out of
loops with ifs (which is considered bad form in some (non
python) circles that the else part of the for and while statements
make sense.
Jul 18 '05 #31
In article <25************ **************@ posting.google. com>,
Magnus Lyck? <ma****@thinkwa re.se> wrote:

On the other hand, I only think it's in the case of a break
in block that...

while condition:
block
else:
print "Loop finished"

...will behave differently than...

while condition:
block
print "Loop finished"

So, unless you use a break in the block, the else statement is just
noise: an extra line of code and additional whitespace for the
following statement(s).


While technically correct, I don't think you could claim that it's "just
noise" in this example:

try:
for ORlist in includes:
try:
for filter in ORlist:
for field in curr_fields:
for item in record[field]:
if match(item, filter):
raise Found
else:
raise NotFound
except Found:
continue
except NotFound:
continue
else:
result.append(r ecord)
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote
programs, then the first woodpecker that came along would destroy civilization.
Jul 18 '05 #32
aa**@pythoncraf t.com (Aahz) wrote in message news:<bp******* ***@panix2.pani x.com>...
In article <25************ **************@ posting.google. com>,
Magnus Lyck? <ma****@thinkwa re.se> wrote:

On the other hand, I only think it's in the case of a break
in block that...

while condition:
block
else:
print "Loop finished"

...will behave differently than...

while condition:
block
print "Loop finished"

So, unless you use a break in the block, the else statement is just
noise: an extra line of code and additional whitespace for the
following statement(s).


While technically correct, I don't think you could claim that it's "just
noise" in this example:

try:
for ORlist in includes:
try:
for filter in ORlist:
for field in curr_fields:
for item in record[field]:
if match(item, filter):
raise Found
else:
raise NotFound
except Found:
continue
except NotFound:
continue
else:
result.append(r ecord)


First of all, I'm not sure it's a good idea to use
exceptions like a poor (rich?) man's GOTO like this. :)

If you persist, I'm not so sure your code is clearer than:

try:
for ORlist in includes:
try:
for filter in ORlist:
for field in curr_fields:
for item in record[field]:
if match(item, filter):
raise Found
raise NotFound
except Found:
continue
except NotFound:
continue
else:
result.append(r ecord)

With the else clause on the for loop, just after the if
statement, you are bound to confuse people. I would guess
that most people who casually looked at that code would
think that you had made an indentation mistake. Some would
probably "correct" it.
Jul 18 '05 #33
ma****@thinkwar e.se (Magnus Lyck?) wrote in message news:<25******* *************** ****@posting.go ogle.com>...
First of all, I'm not sure it's a good idea to use
exceptions like a poor (rich?) man's GOTO like this. :)

If you persist, I'm not so sure your code is clearer than:

try:
for ORlist in includes:
try:
for filter in ORlist:
for field in curr_fields:
for item in record[field]:
if match(item, filter):
raise Found
raise NotFound
except Found:
continue
except NotFound:
continue
else:
result.append(r ecord)

With the else clause on the for loop, just after the if
statement, you are bound to confuse people. I would guess
that most people who casually looked at that code would
think that you had made an indentation mistake. Some would
probably "correct" it.


I, for one, could get confused. BTW, I don't remember a single case in
all my code where I have used so much indentation. I would write some
helper function and avoid nesting as much as possible.

Michelee
Jul 18 '05 #34

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
1426
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
1791
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
1731
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
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...
1
9981
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9850
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
8862
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
7396
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
6662
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
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
5436
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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.