473,714 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"for" with "else"?

While trying to print a none empty list, I accidentaly put an "else"
statement with a "for" instead of "if". Here is what I had:

if ( len(mylist)> 0) :
for x,y in mylist:
print x,y
else:
print "Empty list"

which was supposed to be:

if ( len(mylist)> 0) :
for x,y in mylist:
print x,y
else:
print "Empty list"
Is this to be expected?
(python 2.2.2)

+++++++++++++++ +++++++++++++++ =
for x in range(5):

.... print x*x
.... else:
.... print "done"
....
0
1
4
9
16
done
+++++++++++++++ +++++++++++++++ =

Jul 18 '05 #1
23 3570
[Invalid User wrote]
While trying to print a none empty list, I accidentaly put an "else"
statement with a "for" instead of "if". Here is what I had:


From the Python Language Reference

"""
The for statement

for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]

The expression list is evaluated once; it should yield a sequence. The
suite is then executed once for each item in the sequence, in the
order of ascending indices. Each item in turn is assigned to the
target list using the standard rules for assignments, and then the
suite is executed. When the items are exhausted (which is immediately
when the sequence is empty), the suite in the else clause, if present,
is executed, and the loop terminates.
"""

http://www.python.org/doc/current/ref/for.html

A quick glance through the archives confirms that this has been the
case since at least python 1.4:-

http://www.python.org/doc/1.4/ref/ref7.html#HDR2

regards,

--
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/mailto/alan
Jul 18 '05 #2
Invalid User <us**@invalid.d omain> writes:
Is this to be expected?
(python 2.2.2)

+++++++++++++++ +++++++++++++++ =
>>> for x in range(5): .... print x*x
.... else:
.... print "done"
....
0
1
4
9
16
done
+++++++++++++++ +++++++++++++++ =


Yes. The else clause is invoked iff the for loop terminates normally.
Contrast with:

+++++++++++++++ +++++++++++++++
for x in range(5): .... print x*x
.... if x==4:
.... break
.... else:
.... print "did all"
....
0
1
4
9
16

+++++++++++++++ +++++++++++++++

(This happens to be the *reverse* of what my intuition expects - it
would seem more natural if the syntax meant "do this for loop to
completion, else do this extra stuff," but this is the way it is and
one must simply remember it.)

--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
There are no foolish questions and no man becomes a fool
until he has stopped asking questions.
- Charles P. Steinmetz
Jul 18 '05 #3
Invalid User wrote:
While trying to print a none empty list, I accidentaly put an "else"
statement with a "for" instead of "if". Here is what I had:

if ( len(mylist)> 0) :
for x,y in mylist:
print x,y
else:
print "Empty list"

which was supposed to be:

if ( len(mylist)> 0) :
for x,y in mylist:
print x,y
else:
print "Empty list"
Is this to be expected?


Sure. The else branch is executed unless the for terminates
prematurely (via break, return or exception) -- just like the
else branch of a while loop.

Typical use case:

for item in allitems:
if fraboozable(ite m):
print "first fraboozable item is", item
break
else:
print "Sorry, no item is fraboozable"
Alex

Jul 18 '05 #4

"Mark Jackson" <mj******@alumn i.caltech.edu> wrote in message
news:bk******** **@news.wrc.xer ox.com...
Invalid User <us**@invalid.d omain> writes: (This happens to be the *reverse* of what my intuition expects - it
would seem more natural if the syntax meant "do this for loop to
completion, else do this extra stuff," but this is the way it is and
one must simply remember it.)
There's a certain amount of justification, though. You can
already put whatever amount of logic you need in the if
statement that ends with the break. You don't otherwise
have that ability for normal termination of the sequence.

Frankly, I'd like to see special case syntax for an empty
sequence, but it's not that hard to handle now.

John Roth

--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
There are no foolish questions and no man becomes a fool
until he has stopped asking questions.
- Charles P. Steinmetz

Jul 18 '05 #5
"John Roth" <ne********@jhr othjr.com> writes:

"Mark Jackson" <mj******@alumn i.caltech.edu> wrote in message
news:bk******** **@news.wrc.xer ox.com...
Invalid User <us**@invalid.d omain> writes:

(This happens to be the *reverse* of what my intuition expects - it
would seem more natural if the syntax meant "do this for loop to
completion, else do this extra stuff," but this is the way it is and
one must simply remember it.)


There's a certain amount of justification, though. You can
already put whatever amount of logic you need in the if
statement that ends with the break. You don't otherwise
have that ability for normal termination of the sequence.


Sure - I wasn't arguing the other meaning was needed, clearly it is
not. It's the use of the keyword "else" which creates the [purely
mental] problem for me.

--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
There are no foolish questions and no man becomes a fool
until he has stopped asking questions.
- Charles P. Steinmetz
Jul 18 '05 #6

"Mark Jackson" <mj******@alumn i.caltech.edu> wrote in message
news:bk******** **@news.wrc.xer ox.com...
"John Roth" <ne********@jhr othjr.com> writes:

"Mark Jackson" <mj******@alumn i.caltech.edu> wrote in message
news:bk******** **@news.wrc.xer ox.com...
Invalid User <us**@invalid.d omain> writes:
(This happens to be the *reverse* of what my intuition expects - it
would seem more natural if the syntax meant "do this for loop to
completion, else do this extra stuff," but this is the way it is and
one must simply remember it.)


There's a certain amount of justification, though. You can
already put whatever amount of logic you need in the if
statement that ends with the break. You don't otherwise
have that ability for normal termination of the sequence.


Sure - I wasn't arguing the other meaning was needed, clearly it is
not. It's the use of the keyword "else" which creates the [purely
mental] problem for me.


Good point.

John Roth
--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
There are no foolish questions and no man becomes a fool
until he has stopped asking questions.
- Charles P. Steinmetz

Jul 18 '05 #7
Mark Jackson wrote:
(This happens to be the *reverse* of what my intuition expects - it
would seem more natural if the syntax meant "do this for loop to
completion, else do this extra stuff," but this is the way it is and
one must simply remember it.)


I'm with you there--the use of "else" here has seemed a bit confusing to me.

The use case that Alex just posted gave me another way to think about it:

for item in allitems:
if fraboozable(ite m):
print "first fraboozable item is", item
break
else:
print "Sorry, no item is fraboozable"

If I think of the else statement as being related to the if statement inside
the loop, then it makes some sense--the else statement is executed when the
if statement never comes up true. (It's twisted logic, I know, but at least
it helps me keep track of what "else" does here.)

-Mike
Jul 18 '05 #8
In article <vn************ @corp.supernews .com>,
Michael Geary <Mi**@DeleteThi s.Geary.com> wrote:

The use case that Alex just posted gave me another way to think about it:

for item in allitems:
if fraboozable(ite m):
print "first fraboozable item is", item
break
else:
print "Sorry, no item is fraboozable"

If I think of the else statement as being related to the if statement
inside the loop, then it makes some sense--the else statement is
executed when the if statement never comes up true. (It's twisted
logic, I know, but at least it helps me keep track of what "else" does
here.)


Maybe it's twisted logic, but it's the only time I've ever used for/else
in real code. It helps if instead of thinking of the else as connected
to the if, you think of the entire for loop as being an extended if
statement.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
Jul 18 '05 #9

"Michael Geary" <Mi**@DeleteThi s.Geary.com> wrote in message
news:vn******** ****@corp.super news.com...
Mark Jackson wrote:
(This happens to be the *reverse* of what my intuition expects - it would seem more natural if the syntax meant "do this for loop to
completion, else do this extra stuff," but this is the way it is and one must simply remember it.)


I'm with you there--the use of "else" here has seemed a bit

confusing to me.

How I plan to remember now: if the abnormal exit is a return or
exception, then all code end of for block, including any else part, to
the end of the function or try block will be skipped, so else part can
only apply to normal exit.

Terry J. Reedy
Jul 18 '05 #10

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

Similar topics

27
3076
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.
12
2106
by: Robbie Hatley | last post by:
I'm getting a bizarre error with this code: ... case WM_COMMAND: { switch (LOWORD(wParam)) // switch (control ID) { ... case IDC_RAIN_ENABLE_SIMPLE: {
13
2002
by: xz | last post by:
What if I want the following: vector<intv; // v is loaded by push_back() switch( v.size() ) { case 2: //do something
8
1745
by: Twoshots64 | last post by:
Public col, nmb, x, y, z As Variant Public hw(17) As Variant Public buses(17, 200), sht, dt, nme, per, rnk As String ' ' ' ' Function Makelist ' Updated by DEE 5/10/1999 ' Sub Makelist()
0
9311
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
9013
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...
1
6632
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
5946
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
4463
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
4719
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3156
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
2518
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2108
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.