Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

1.5.2 for: else:

2 views
Skip to first unread message

Oleg Broytmann

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to Python Mailing List
Hello!

The following program:

----------
for a in ['a', 12]:
print a
else:
print "Empty!"
----------

prints under 1.5.2 on Linux and Solaris:

-----
a
12
Empty!
-----

Is it a bug, or is it just me, who do not understand the feature? I
expected just "a" and "12"...

This:

----------
for a in []:
print a
else:
print "Empty!"
----------

prints:

-----
Empty!
-----

and I think it is correct.

Oleg.
----
Oleg Broytmann Netskate/Inter.Net.Ru p...@emerald.netskate.ru
Programmers don't die, they just GOSUB without RETURN.


Oleg Broytmann

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to Thomas Wouters
On Tue, 27 Jul 1999, Thomas Wouters wrote:
> http://www.python.org/doc/current/tut/node6.html#SECTION006200000000000000000
>
> [..]
> 4.4 break and continue Statements, and else Clauses on Loops
>
> Loop statements may have an else clause; it is executed when the loop
> terminates through exhaustion of the list (with for) or when the condition
> becomes false (with while), but not when the loop is terminated by a break
> statement.
> [..]
[skip]
> Else clauses get executed on normal loop exit, even if the loop was 'empty'.
> It does not get executed when you 'break' out of a loop.

Aha, thanks. I expected "else" to be executed when "for" not executed on
empty list. Wrong assumption.

> --
> Thomas Wouters <tho...@xs4all.net>
>
> Hi! I'm a .signature virus! copy me into your .signature file to help me spread!

Thomas Wouters

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to Oleg Broytmann
On Tue, Jul 27, 1999 at 04:15:44PM +0400, Oleg Broytmann wrote:

> The following program:

> ----------
> for a in ['a', 12]:
> print a
> else:
> print "Empty!"
> ----------

http://www.python.org/doc/current/tut/node6.html#SECTION006200000000000000000

[..]
4.4 break and continue Statements, and else Clauses on Loops

Loop statements may have an else clause; it is executed when the loop
terminates through exhaustion of the list (with for) or when the condition
becomes false (with while), but not when the loop is terminated by a break
statement.
[..]

So,

>>> def do_a(list):
... for a in list:
... if not a:
... break
... print a
... else:
... print "No FALSE items in list!"
...

>>> do_a(['a', 12])
a
12
No FALSE items in list!

>>> do_a(['a', 12, []])
a
12

>>> do_a(['a', 12, 0])
a
12

Else clauses get executed on normal loop exit, even if the loop was 'empty'.
It does not get executed when you 'break' out of a loop.

--

William Tanksley

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to
On Tue, 27 Jul 1999 14:29:43 +0200, Thomas Wouters wrote:
>On Tue, Jul 27, 1999 at 04:15:44PM +0400, Oleg Broytmann wrote:

>> The following program:
>> ----------
>> for a in ['a', 12]:
>> print a
>> else:
>> print "Empty!"
>> ----------

>http://www.python.org/doc/current/tut/node6.html#SECTION006200000000000000000

>4.4 break and continue Statements, and else Clauses on Loops

>Loop statements may have an else clause; it is executed when the loop
>terminates through exhaustion of the list (with for) or when the condition
>becomes false (with while), but not when the loop is terminated by a break
>statement.

Well, I'm suprised. I had also expected the else clause to run on empty
loop. It seems so natural, in line with the meaning of a loop (loop on
this; otherwise do that).

Fortunately I've never actually used it and thus been disenchanted.

Understanding the current semantics seems to require understanding the
nature of loop tests in Python. Since I understand them I can agree that
this makes sense, but I'm still a bit leery, because you're not 'elsing'
on the data but rather on code inside the loop.

I would _definitely_ use exceptions to handle this.

>Thomas Wouters <tho...@xs4all.net>

--
-William "Billy" Tanksley

Chad Netzer

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to
William Tanksley wrote:

> Well, I'm suprised. I had also expected the else clause to run on empty
> loop. It seems so natural, in line with the meaning of a loop (loop on
> this; otherwise do that).

Hmmm, it does seem that "finally" might have been a more descriptive
choice (but historians may point out that "else" appeared before "finally"
and was thus used instead). Of course, if one breaks out of the loop, they
might reasonably expect to avoid the "finally" statement (otherwise, it
becomes redundant), and this is somewhat counter to it's "try" semantics...
Hmmm.

Gordon McMillan

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to William Tanksley, pytho...@python.org
William Tanksley wrote:
> On Tue, 27 Jul 1999 14:29:43 +0200, Thomas Wouters wrote:

> >4.4 break and continue Statements, and else Clauses on Loops
>
> >Loop statements may have an else clause; it is executed when the loop
> >terminates through exhaustion of the list (with for) or when the condition
> >becomes false (with while), but not when the loop is terminated by a break
> >statement.
>

> Well, I'm suprised. I had also expected the else clause to run on
> empty loop. It seems so natural, in line with the meaning of a loop
> (loop on this; otherwise do that).
>

> Fortunately I've never actually used it and thus been disenchanted.

Maybe it violated your expectations, but it's much more valuable than
what you expected. After all, testing for an empty sequence is a
no-brainer. But finding a match in a list, and testing whether you
fell off the end without finding one, is (without the else clause) a
much messier proposal.

your-disenchantment-is-my-pleasure-<wink>-ly y'rs

- Gordon

Hans Nowak

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to

On 27 Jul 99, Oleg Broytmann wrote:

> > Loop statements may have an else clause; it is executed when the loop
> > terminates through exhaustion of the list (with for) or when the
> > condition becomes false (with while), but not when the loop is

> > terminated by a break statement. [..]
> [skip]


> > Else clauses get executed on normal loop exit, even if the loop was
> > 'empty'. It does not get executed when you 'break' out of a loop.
>

> Aha, thanks. I expected "else" to be executed when "for" not executed
> on
> empty list. Wrong assumption.

This one has bitten me too in the past. One of the few non-intuitive
parts of Python, methinks. :(

--Hans Nowak (zephyr...@hvision.nl)
Homepage: http://fly.to/zephyrfalcon
Python Snippets: http://www.hvision.nl/~ivnowa/snippets/
The Purple Kookaburra Forum: http://www.delphi.com/kookaburra/

Donn Cave

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to
wtan...@dolphin.openprojects.net (William Tanksley) writes:
|On Tue, 27 Jul 1999 14:29:43 +0200, Thomas Wouters wrote:
|>On Tue, Jul 27, 1999 at 04:15:44PM +0400, Oleg Broytmann wrote:
|
|>| The following program:
|>| ----------
|>| for a in ['a', 12]:
|>| print a
|>| else:
|>| print "Empty!"
|>| ----------
|
|> http://www.python.org/doc/current/tut/node6.html#SECTION006200000000000000000
|
|> 4.4 break and continue Statements, and else Clauses on Loops
|
|> Loop statements may have an else clause; it is executed when the loop
|> terminates through exhaustion of the list (with for) or when the condition
|> becomes false (with while), but not when the loop is terminated by a break
|> statement.

| Well, I'm suprised. I had also expected the else clause to run on empty


| loop. It seems so natural, in line with the meaning of a loop (loop on
| this; otherwise do that).
|
| Fortunately I've never actually used it and thus been disenchanted.

[(I'm confused? else clause _does_ execute after an empty loop, like
for x in ():
pass
else:
print 'for else'
)]

It seems to me to work the only useful way, so you almost can't
go wrong - at worst, if you mistake its meaning, you won't use it.
That may not be the same thing as "natural", but it's close.
It's one of the neat little things that make me pause for a moment
of appreciation when I get to use it.

| Understanding the current semantics seems to require understanding the
| nature of loop tests in Python. Since I understand them I can agree that
| this makes sense, but I'm still a bit leery, because you're not 'elsing'
| on the data but rather on code inside the loop.
|
| I would _definitely_ use exceptions to handle this.

Note that "try/except" also takes an "else", which also happens to have
the only useful sense and executes when the try block executes with no
exception. It's handy for code that should execute in the normal case
but does not itself need to be enclosed in an exception handler, so you
can focus the try block more precisely on the section that needs it.

Donn Cave, University Computing Services, University of Washington
do...@u.washington.edu

Gordon McMillan

unread,
Jul 27, 1999, 3:00:00 AM7/27/99
to William Tanksley, pytho...@python.org
William Tanksley wrote:

> On Tue, 27 Jul 1999 18:35:10 -0500, Gordon McMillan wrote:

> >Maybe it violated your expectations, but it's much more valuable than
> >what you expected. After all, testing for an empty sequence is a
> >no-brainer. But finding a match in a list, and testing whether you
> >fell off the end without finding one, is (without the else clause) a
> >much messier proposal.

[rant]
> I would also disagree with you that my interpretation would result
> in disutility: you'd merely have to use exceptions instead of
> 'break'.
[more rant]
> class neverMind(): pass
>
> try:
> for x in [1,2,3]:
> print x
> if x == 2: raise neverMind
> except neverMind:
> print "modern else clause here"

--------billy.py--------------------
class neverMind: pass

try:
for x in [1,2,3]:
print x
if x == 2: raise neverMind
except neverMind:
print "modern else clause here"

for x in [1,2,3]:
print x
if x == 2:
break
else:
print "Hi Billy!"
---------------------------------------------------

C:\TEMP>python billy.py
1
2
modern else clause here
1
2

C:\TEMP>

Notice the difference?
You need to raise the exception if you've gone through the loop and
not found 2. The best way to do that <snicker> is with an else
clause.

Or will you now claim that:

lst = [1,2,3]
for i in range(len(lst)):
if lst[i] == 2: break
if i == len(lst):
print "Tanksley else clause here"

is a better solution <wink>?

insufferably-sanctimoniously-y'rs

- Gordon

William Tanksley

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
On Tue, 27 Jul 1999 18:35:10 -0500, Gordon McMillan wrote:
>William Tanksley wrote:
>> On Tue, 27 Jul 1999 14:29:43 +0200, Thomas Wouters wrote:

>> >4.4 break and continue Statements, and else Clauses on Loops

>> >Loop statements may have an else clause; it is executed when the loop
>> >terminates through exhaustion of the list (with for) or when the condition
>> >becomes false (with while), but not when the loop is terminated by a break
>> >statement.

>> Well, I'm suprised. I had also expected the else clause to run on
>> empty loop. It seems so natural, in line with the meaning of a loop
>> (loop on this; otherwise do that).

>> Fortunately I've never actually used it and thus been disenchanted.

>Maybe it violated your expectations, but it's much more valuable than

>what you expected. After all, testing for an empty sequence is a
>no-brainer. But finding a match in a list, and testing whether you
>fell off the end without finding one, is (without the else clause) a
>much messier proposal.

First of all, meeting expectations is one reason why I like Python, and
therefore to me is a very valuable quality. I would go so far as to say
that it's more valuable than any amount of utility to people who have
learned and happen to remember the shibboleth.

I would also disagree with you that my interpretation would result in

disutility: you'd merely have to use exceptions instead of 'break'. This
is more in line with the way the rest of Python works, and makes the
effect of the abnormal termination of the loop perfectly clear.

The very worst part of the current else: behavior is that it changes the
meaning of else. In other constructs, else is an alternate path to take
if the data being tested fails a single expression test. In this
contruct, else is a path taken if the code block belonging to the previous
test executes a certain instruction.

Pretty odd, eh?

class neverMind(): pass

try:
for x in [1,2,3]:
print x
if x == 2: raise neverMind
except neverMind:
print "modern else clause here"

>- Gordon

--
-William "Billy" Tanksley

Fredrik Lundh

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
William Tanksley <wtan...@dolphin.openprojects.net> wrote:
> The very worst part of the current else: behavior is that it changes the
> meaning of else. In other constructs, else is an alternate path to take
> if the data being tested fails a single expression test. In this
> contruct, else is a path taken if the code block belonging to the previous
> test executes a certain instruction.

nope. you've got it all backwards. consider this:

for an "if" statement, "else" is a path taken if the
expression evaluates to false.

for a "while" statement, "else" is a path taken if the
expression evaluates to false. or in other words,
when the loop terminates by natural causes.

for a "for" statement, "else" is a path taken when
there are no more elements to loop over. or
in other words, when the loop terminates by
natural causes.

not that complicated, was it?

now, what you seem to have trouble with isn't
the "else"-clause -- it's the behaviour of "break":

"break" doesn't just break out of the inner
body (the portion between while/for and
else), it breaks out of the ENTIRE construct.
including the "else" clause. just as the docs
say.

"else" always works the same way. and so does
"break". what else did you expect from Guido?

</F>


William Tanksley

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
On 27 Jul 1999 23:33:58 GMT, Donn Cave wrote:

>wtan...@dolphin.openprojects.net (William Tanksley) writes:
>|On Tue, 27 Jul 1999 14:29:43 +0200, Thomas Wouters wrote:

>|> http://www.python.org/doc/current/tut/node6.html#SECTION006200000000000000000

>|> 4.4 break and continue Statements, and else Clauses on Loops

>|> Loop statements may have an else clause; it is executed when the loop
>|> terminates through exhaustion of the list (with for) or when the condition
>|> becomes false (with while), but not when the loop is terminated by a break
>|> statement.

>| Well, I'm suprised. I had also expected the else clause to run on empty
>| loop. It seems so natural, in line with the meaning of a loop (loop on
>| this; otherwise do that).

>| Fortunately I've never actually used it and thus been disenchanted.

>[(I'm confused? else clause _does_ execute after an empty loop, like


> for x in ():
> pass
> else:
> print 'for else'
>)]

Of course. It also executes on a full loop, or a half-full one, or for
that matter a half-empty one. The only time it doesn't execute is when
the code block _inside_ the loop happens to execute a break. Pretty odd
when you think about it.

>It seems to me to work the only useful way,

I'm sorry, I'm allergic to that phrase. I can't deny that it's useful
now, but anyone claiming that any current condition is the ONLY useful
way... Ugh. Obviously hasn't bothered even thinking about alternatives.

If there existed even a _less_ useful way you'd be wrong. And even
supposing myself to be wrong, there does exist such a way. QED.

>so you almost can't
>go wrong - at worst, if you mistake its meaning, you won't use it.

That's the problem! You _will_ use it, under the mistaken impression that
it performs some kind of useful 'else' function. Instead it performs a
hidden exception-handling. Was this leftover from some time when Python
didn't have exception handling or something?

>That may not be the same thing as "natural", but it's close.

I'm also allergic to "intuitive", and since I nearly used the word myself,
my sinuses are completely plugged. ;-)

I can't really claim natural behavior, but I do claim that both of our
problems are easily solved using other means, and my solution is
consistent with other uses of else while the current solution isn't. On
your side, of course, is the fact that the current solution IS the current
solution, no ifs ands ors or elses about it.

>It's one of the neat little things that make me pause for a moment
>of appreciation when I get to use it.

I'm pausing right now for a moment of appreciation. No, this is
incredulity. What is it about this that makes you appreciate it? I can't
see anything in it except a world-class kludge. The alternate solution,
throwing an exception, is SO much nicer that very few people even USE the
current behavior.

>| Understanding the current semantics seems to require understanding the
>| nature of loop tests in Python. Since I understand them I can agree that
>| this makes sense, but I'm still a bit leery, because you're not 'elsing'
>| on the data but rather on code inside the loop.

>| I would _definitely_ use exceptions to handle this.

>Note that "try/except" also takes an "else", which also happens to have
>the only useful sense

Hack, ack, sniffle. ;)

>and executes when the try block executes with no
>exception. It's handy for code that should execute in the normal case
>but does not itself need to be enclosed in an exception handler, so you
>can focus the try block more precisely on the section that needs it.

I agree. It's a wonderfully useful tool, and unlike either of our
solutions is pretty much irreplacable. Not as useful as 'finally', of
course.

It shares a characteristic with my solution: it executes only when the
previous control structure's block has failed to execute.

> Donn Cave, University Computing Services, University of Washington

--
-William "Billy" Tanksley

William Tanksley

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
On Wed, 28 Jul 1999 00:50:14 GMT, Fredrik Lundh wrote:
>William Tanksley <wtan...@dolphin.openprojects.net> wrote:
>> The very worst part of the current else: behavior is that it changes the
>> meaning of else. In other constructs, else is an alternate path to take
>> if the data being tested fails a single expression test. In this
>> contruct, else is a path taken if the code block belonging to the previous
>> test executes a certain instruction.

>nope. you've got it all backwards. consider this:

> for an "if" statement, "else" is a path taken if the
> expression evaluates to false.

Close enough -- I would say it's the path taken if the 'if' block isn't
executed.

> for a "while" statement, "else" is a path taken if the
> expression evaluates to false. or in other words,
> when the loop terminates by natural causes.

In other words, it executes when you'd expect an 'else' to not execute --
'else' doesn't mean "natural causes".

> for a "for" statement, "else" is a path taken when
> there are no more elements to loop over. or
> in other words, when the loop terminates by
> natural causes.

In addition to the above carping, I have to add that the code following
the for (or while) loop is what I'd expect to execute after the loop
terminates.

>not that complicated, was it?

I didn't think it was either, but it seems that in spite of my initial
understanding, I still managed to reverse it accidentally.

>now, what you seem to have trouble with isn't
>the "else"-clause -- it's the behaviour of "break":

>"else" always works the same way. and so does


>"break". what else did you expect from Guido?

I expect consistency, and I expect that the major features (else with if
and else with catch) will define consistency, not minor features like else
with looping.

try:
...
except something:
...
else:
...

The else block here executes iff the except blocks don't execute.

></F>

--
-William "Billy" Tanksley

William Tanksley

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
On Tue, 27 Jul 1999 21:43:00 -0500, Gordon McMillan wrote:
>William Tanksley wrote:
>> On Tue, 27 Jul 1999 18:35:10 -0500, Gordon McMillan wrote:

>> >Maybe it violated your expectations, but it's much more valuable than
>> >what you expected. After all, testing for an empty sequence is a
>> >no-brainer. But finding a match in a list, and testing whether you
>> >fell off the end without finding one, is (without the else clause) a
>> >much messier proposal.

>[rant]


>> I would also disagree with you that my interpretation would result
>> in disutility: you'd merely have to use exceptions instead of
>> 'break'.

>[more rant]

>--------billy.py--------------------
>class neverMind: pass

>try:
> for x in [1,2,3]:
> print x
> if x == 2: raise neverMind
>except neverMind:
> print "modern else clause here"

>for x in [1,2,3]:
> print x
> if x == 2:

> break
>else:
> print "Hi Billy!"
>---------------------------------------------------

>C:\TEMP>python billy.py
>1
>2
>modern else clause here
>1
>2

>C:\TEMP>

>Notice the difference?
>You need to raise the exception if you've gone through the loop and
>not found 2. The best way to do that <snicker> is with an else
>clause.

Sure do! In spite of the fact that I actually did understand the modern
meaning of 'else', in practice I manage to screw it up anyhow. I can
choose to make this a commentary on my programming skill, OR on the
obtuseness of the current definition of 'else'. Hmm, which to choose,
which to choose...

:)

However, you're wrong about the best way to detect a 2 in the list using
this style. To steal the same example:

try:
for x in [1,2,3]:
print x
if x == 2: raise neverMind

print "modern else clause here"

except neverMind: print "found two"
else:
print "another place to put the modern else clause"

Wow, TMTOWTDI. Oops, did I say the wrong thing?

Of course, by demonstrating both ways to do it, I'm making the code more
complex; but you can see that this solution solves the problem quite
elegantly.

The place to use MY definition of 'else', OTOH, is when you're building a
structure during the iteration, but the result of an empty loop is
different than the initial value the variable has to have when going
through the loop.

Here you go. This example might convert a Python list into a Lisp
tree-list -- but to imitate Lisp (okay, it's a toy problem, I'm cheating)
an empty list produces NIL ~= None.

var = Node(None,None)
for x in pyList:
var.car = x
var.cdr = Node()
else:
var = None

>insufferably-sanctimoniously-y'rs

>- Gordon

unstoppably-confidantly y'rs

--
-William "Billy" Tanksley

Fredrik Lundh

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
William Tanksley <wtan...@dolphin.openprojects.net> wrote:
> > for an "if" statement, "else" is a path taken if the
> > expression evaluates to false.
>
> Close enough -- I would say it's the path taken if the 'if' block isn't
> executed.

you can say what you want, but it isn't defined
that way; the language reference says:

"If all expressions are false, the suite of
the else clause, if present, is executed."

(where "all expressions" are the expressions
for all if/elif clauses in the statement)

if you continue reading, you'll find:

"if the expression is false (which may be
the first time it is tested) the suite of the
else clause, if present, is executed"

and

"when the items are exhausted (which is
immediately when the sequence is empty),
the suite in the else clause, if present, is
executed"

for ALL these statements, the else clause is exe-
cuted if and only if ALL controlling expressions
evaluate to FALSE.

> > for a "while" statement, "else" is a path taken if the
> > expression evaluates to false. or in other words,
> > when the loop terminates by natural causes.
>
> In other words, it executes when you'd expect an 'else' to not execute --
> 'else' doesn't mean "natural causes".

huh? the "else" clause isn't involved in the loop's
termination at all; it's executed when the con-
trolling expression becomes false. if you raise
an exception, or use the break statement, or
return to the caller, you don't end up in the
"else" clause by a very simple reason: the con-
trolling expression isn't false.

> > for a "for" statement, "else" is a path taken when
> > there are no more elements to loop over. or
> > in other words, when the loop terminates by
> > natural causes.
>
> In addition to the above carping, I have to add that the code following
> the for (or while) loop is what I'd expect to execute after the loop
> terminates.

huh? the "else" clause is part of the if/while/for
statement. the code that follows the loop isn't.

I repeat:

for ALL these statements, the else clause is exe-
cuted if and only if ALL controlling expressions
evaluate to FALSE.

whether blocks are executed or not isn't part
of the definition; only the conditions are.

> I expect consistency, and I expect that the major features (else with if
> and else with catch) will define consistency, not minor features like else
> with looping.

you have consistency. for-else and while-else works
EXACTLY like if-else. for ALL these statements, the
else clause is executed if and only if ALL controlling
expressions evaluate to FALSE.

you can argue as much as you want, but that's the
way it is. you gotta live with it (unless you have your
own time machine, of course ;-)

</F>


Gordon McMillan

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to William Tanksley, pytho...@python.org
William Tanksley wrote:
> On Tue, 27 Jul 1999 21:43:00 -0500, Gordon McMillan wrote:

[snip Billy's silly error and his entirely insufficient embarassment
<wink>]

> However, you're wrong about the best way to detect a 2 in the list
> using this style. To steal the same example:
>
> try:
> for x in [1,2,3]:
> print x
> if x == 2: raise neverMind
> print "modern else clause here"
> except neverMind: print "found two"
> else:
> print "another place to put the modern else clause"
>
> Wow, TMTOWTDI. Oops, did I say the wrong thing?
>
> Of course, by demonstrating both ways to do it, I'm making the code
> more complex; but you can see that this solution solves the problem
> quite elegantly.

WIth an extra class, and 3 or 4 more lines of code, not to mention
treading on the toes of all who think exceptions should only be used
for exceptional conditions (or maybe it _is_ exceptional when
something you wrote works <1e3 wink>).

> The place to use MY definition of 'else', OTOH, is when you're
> building a structure during the iteration, but the result of an
> empty loop is different than the initial value the variable has to
> have when going through the loop.
>
> Here you go. This example might convert a Python list into a Lisp
> tree-list -- but to imitate Lisp (okay, it's a toy problem, I'm
> cheating) an empty list produces NIL ~= None.
>
> var = Node(None,None)
> for x in pyList:
> var.car = x
> var.cdr = Node()
> else:
> var = None

Not a Lisper, but isn't what you're doing better done thusly:

def test1(lst):
var = None
for x in lst:
var = (x, var)
return var

print `test1([1,2,3])`

print `test1([])`

Produces:
(3, (2, (1, None)))


None

> >insufferably-sanctimoniously-y'rs
>
> >- Gordon
>
> unstoppably-confidantly y'rs
>
> --
> -William "Billy" Tanksley

so-self-righteous-without-the-winks-I-might-almost-be-mistaken
-for-that-other-GM-ly y'rs

- Gordon

Donn Cave

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
wtan...@dolphin.openprojects.net (William Tanksley) writes:
...

| try:
| ...
| except something:
| ...
| else:
| ...
|
| The else block here executes iff the except blocks don't execute.

Beg to differ - it executes iff the try block executes to completion.
Whether an except block executes or not is immaterial.

Donn Cave, University Computing Services, University of Washington

do...@u.washington.edu

Stidolph, David

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
As I am understanding for .. else, the following

for window in self.windows:
self.ProcessWindow(window)
else:
print 'windows processed'

is the same as

for window is self.windows:
self.ProcessWindow(window)
print 'windows processed'

and the only case where the else statement has any value over simply adding
code after the for loop would be if a break statement were executed - in
which case the else would NOT be called. Personally, I would rather have
the else execute if none of the code within the for loop were executed. It
would save a variable assignment/test as in:

executed = 0
for window in self.windows:
executed = 1
self.ProcessWindow(window)
if not executed:
self.HandleProcessWindowNotCalled()

This forces the variable to be set numerous times (needless).

I'm with those that see else being an alternate execution (like the if)
rather than some sort of continuation. I'm also with those that favor "if
it isn't broke, don't fix it".

Fredrik Lundh

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
Greg Ewing <greg....@compaq.com> wrote:
> Not if you go about it the right way. I always
> put such loops in a procedure of their own,
> and use return:
>
> def find_the_holy_grail(stuff):
> for x in stuff:
> if is_holy_grail(x):
> return x
> return None

hey, didn't your MOM tell you to only use a
SINGLE return statement per function, and
put that at the END of the function body? ;-)

> I wouldn't mind if there weren't any break - and
> without break, there would be no need for the
> weird else.

well, I think it's time for a break...

</F>


Vadim Chugunov

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
I would say that else: clause after a loop is really related to the if:
controlling the break,
rather than to the loop itself.

When I first saw Python syntax for loops I said: "A-ha! So in Python I will not
need a goto
in situations like this:
-----
for(Item* pitem=pseq->First(); pitem; pitem=pitem->Next())
if (pitem->key==42)
goto Found;

pitem = pseq->Insert(new Item());
Found:
// use item pointed to by pitem
-----
In fact, I do not see any other good use for else: clause in a loop.
Maybe the docs should just explicitly say what this feature is good for ?

Vadim

William Tanksley <wtan...@dolphin.openprojects.net> wrote in message
news:slrn7pum9t....@dolphin.openprojects.net...


> On Wed, 28 Jul 1999 00:50:14 GMT, Fredrik Lundh wrote:
> >William Tanksley <wtan...@dolphin.openprojects.net> wrote:
> >> The very worst part of the current else: behavior is that it changes the
> >> meaning of else. In other constructs, else is an alternate path to take
> >> if the data being tested fails a single expression test. In this
> >> contruct, else is a path taken if the code block belonging to the previous
> >> test executes a certain instruction.
>
> >nope. you've got it all backwards. consider this:
>

> > for an "if" statement, "else" is a path taken if the
> > expression evaluates to false.
>
> Close enough -- I would say it's the path taken if the 'if' block isn't
> executed.
>

> > for a "while" statement, "else" is a path taken if the
> > expression evaluates to false. or in other words,
> > when the loop terminates by natural causes.
>
> In other words, it executes when you'd expect an 'else' to not execute --
> 'else' doesn't mean "natural causes".
>

> > for a "for" statement, "else" is a path taken when
> > there are no more elements to loop over. or
> > in other words, when the loop terminates by
> > natural causes.
>
> In addition to the above carping, I have to add that the code following
> the for (or while) loop is what I'd expect to execute after the loop
> terminates.
>

Stidolph, David

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
Please show your example using the else .. I'd like to see it.

-----Original Message-----
From: Vadim Chugunov [mailto:che...@yahoo.com]
Sent: Wednesday, July 28, 1999 4:58 PM
To: pytho...@cwi.nl
Subject: Re: 1.5.2 for: else:

Vadim Chugunov

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to
How about this:

8<---------------------------------
class Item:
def __init__(self,key):
self.key = key

seq= [Item(1),Item(2),Item(3)]

for item in seq:
if item.key==42:
break
else:
item = Item(42) # oh well, append() does not return a value
seq.append(item)

print item.key
8<---------------------------------


Stidolph, David <stid...@origin.ea.com> wrote in message
news:11A17AA2B9EAD111BCEA...@molach.origin.ea.com...

Tim Peters

unread,
Jul 28, 1999, 3:00:00 AM7/28/99
to pytho...@python.org
[/F, on the sparkling consistency of for/else, while/else, if/else]

> what else did you expect from Guido?

[Greg Ewing]
> I would have expected Guido to shriek in horror
> and refuse to even consider such a semantically
> ambiguous construct.
>
> It seems quite out of character for both him
> and Python.

Indeed, if for/else hadn't been in Python from the start, anyone suggesting
it would get flamed without mercy! I happen to like it, but it's Guido-like
only in its inscrutablitily at first sight <wink>. The only Pythonism less
Pythonic is that e.g.

4 < "3"

silently returns true.

although-that-would-be-even-less-pythonic-if-it-returned-false-ly y'rs -
tim

Greg Ewing

unread,
Jul 29, 1999, 3:00:00 AM7/29/99
to
Gordon McMillan wrote:
>
> But finding a match in a list, and testing whether you
> fell off the end without finding one, is (without the else clause) a
> much messier proposal.

Not if you go about it the right way. I always


put such loops in a procedure of their own,
and use return:

def find_the_holy_grail(stuff):
for x in stuff:
if is_holy_grail(x):
return x
return None

Not only does this not require a weird else
clause, it doesn't require break either. I
almost never use break - and when I do I usually
regret it later. I wouldn't mind if there weren't


any break - and without break, there would be no
need for the weird else.

Greg

Greg Ewing

unread,
Jul 29, 1999, 3:00:00 AM7/29/99
to
Fredrik Lundh wrote:
>
> what else did you expect from Guido?

I would have expected Guido to shriek in horror


and refuse to even consider such a semantically
ambiguous construct.

It seems quite out of character for both him
and Python.

Greg

Martin Pool

unread,
Jul 29, 1999, 3:00:00 AM7/29/99
to
William Tanksley wrote:
>
> On Tue, 27 Jul 1999 21:43:00 -0500, Gordon McMillan wrote:
> >William Tanksley wrote:
> >> On Tue, 27 Jul 1999 18:35:10 -0500, Gordon McMillan wrote:
>
> >> >Maybe it violated your expectations, but it's much more valuable than
> >> >what you expected. After all, testing for an empty sequence is a
> >> >no-brainer. But finding a match in a list, and testing whether you

> >> >fell off the end without finding one, is (without the else clause) a
> >> >much messier proposal.

If nowhere else, I would have liked something like this in Java for
testing exception-handling code. With this, I can write:

>>> try:
... print 0/0
... except ZeroDivisionError:
... print "caught exception as expected"
... else:
... print "Oops! Exception didn't happen"

whereas in Java I have to write

boolean caught = false;
try {
int a = 0 / 0;
} catch (ArithmeticException a) {
out.println("caught as expected");
caught = true;
}
if (!caught)
out.print("exception didn't happen");

I doubt if I'll often use for: else or try: else, and perhaps they could
have clearer names, but I reckon they're nice to have.

--
/\\\ Mincom | Martin Pool | mar...@mincom.com
// \\\ | Software Engineer | Phone: +61 7 3303-3333
\\ /// | Mincom Ltd. |
\/// | Teneriffe, Brisbane | Speaking for myself only

Hans Nowak

unread,
Jul 29, 1999, 3:00:00 AM7/29/99
to

> William Tanksley <wtan...@dolphin.openprojects.net> wrote:
> > The very worst part of the current else: behavior is that it changes the
> > meaning of else. In other constructs, else is an alternate path to take
> > if the data being tested fails a single expression test. In this
> > contruct, else is a path taken if the code block belonging to the
> > previous test executes a certain instruction.
>
> nope. you've got it all backwards. consider this:
>
> for an "if" statement, "else" is a path taken if the
> expression evaluates to false.
>
> for a "while" statement, "else" is a path taken if the
> expression evaluates to false. or in other words,
> when the loop terminates by natural causes.
>
> for a "for" statement, "else" is a path taken when
> there are no more elements to loop over. or
> in other words, when the loop terminates by
> natural causes.
>
> not that complicated, was it?

I think quite a few people would expect only one of the parts to
execute, like in if..else, and not both of them. So this extension of
the meaning of 'else' may come as a surprise for those (including me,
actually).

But, the feature itself is nice, and the keyword is not going to
change, is I guess it's no use whining about it. ^_^

William Tanksley

unread,
Jul 29, 1999, 3:00:00 AM7/29/99
to
On Thu, 29 Jul 1999 08:51:15 +1200, Greg Ewing wrote:
>Gordon McMillan wrote:

>> But finding a match in a list, and testing whether you
>> fell off the end without finding one, is (without the else clause) a
>> much messier proposal.

>Not if you go about it the right way. I always


>put such loops in a procedure of their own,
>and use return:

>Not only does this not require a weird else


>clause, it doesn't require break either. I
>almost never use break - and when I do I usually
>regret it later. I wouldn't mind if there weren't
>any break - and without break, there would be no
>need for the weird else.

I have to admit that I do the same -- this is why I've never been tripped
up by the else.

>Greg

--
-William "Billy" Tanksley

William Tanksley

unread,
Jul 29, 1999, 3:00:00 AM7/29/99
to
On Wed, 28 Jul 1999 20:11:10 GMT, Fredrik Lundh wrote:
>William Tanksley <wtan...@dolphin.openprojects.net> wrote:
>> > for an "if" statement, "else" is a path taken if the
>> > expression evaluates to false.

>> Close enough -- I would say it's the path taken if the 'if' block isn't
>> executed.

>you can say what you want, but it isn't defined


>that way; the language reference says:

> "If all expressions are false, the suite of
> the else clause, if present, is executed."
> (where "all expressions" are the expressions
> for all if/elif clauses in the statement)

>if you continue reading, you'll find:

> "if the expression is false (which may be
> the first time it is tested) the suite of the
> else clause, if present, is executed"

>and

> "when the items are exhausted (which is
> immediately when the sequence is empty),
> the suite in the else clause, if present, is
> executed"

>for ALL these statements, the else clause is exe-
>cuted if and only if ALL controlling expressions
>evaluate to FALSE.

But that's not even superficially true for the current behavior of a loop.
A loop's else clause is executed even when there were TRUE results of the
controlling expressions.

In fact, the loop's else clause is executed when a single FALSE is
returned from an often hidden evaluation.

>huh? the "else" clause isn't involved in the loop's
>termination at all; it's executed when the con-
>trolling expression becomes false. if you raise
>an exception, or use the break statement, or
>return to the caller, you don't end up in the
>"else" clause by a very simple reason: the con-
>trolling expression isn't false.

This actually makes a lot of sense for a while statement, since there's an
explicit single-valued controlling expression. If the while statement
were the only loop statement with an else, I wouldn't bother arguing about
it; I would just think that I would rather not use a break for that
purpose (but scripting languages are wonderful that way, you get to write
code that makes sense to YOU, not to me or Guido).

>I repeat:

>for ALL these statements, the else clause is exe-
>cuted if and only if ALL controlling expressions
>evaluate to FALSE.

Except 'for', where it executes if and only if _one_ of the "controlling
expressions" (all of which are implicit) evaluates to FALSE.

If it truly was consistent with your own definition, then it would execute
if and only if none of the controlling expressions ever evaluated to TRUE
-- in other words, if the for loop never iterated.

I think I got you by your very own words.

>you can argue as much as you want, but that's the
>way it is. you gotta live with it (unless you have your
>own time machine, of course ;-)

I agree with this, of course :).

I'm nore agitating for Python 2.0. But then I'd be happy to see else go
away or stay the same, too; it's too minor of a feature. I guess, then,
that I'm merely defending my point of view.

William Tanksley

unread,
Jul 30, 1999, 3:00:00 AM7/30/99
to
On Wed, 28 Jul 1999 16:38:24 -0500, Gordon McMillan wrote:
>William Tanksley wrote:
>> On Tue, 27 Jul 1999 21:43:00 -0500, Gordon McMillan wrote:

>[snip Billy's silly error and his entirely insufficient embarassment
><wink>]

:)

>> However, you're wrong about the best way to detect a 2 in the list
>> using this style. To steal the same example:

>> try:
>> for x in [1,2,3]:
>> print x
>> if x == 2: raise neverMind
>> print "modern else clause here"
>> except neverMind: print "found two"
>> else:
>> print "another place to put the modern else clause"

>> Of course, by demonstrating both ways to do it, I'm making the code


>> more complex; but you can see that this solution solves the problem
>> quite elegantly.

>WIth an extra class, and 3 or 4 more lines of code, not to mention
>treading on the toes of all who think exceptions should only be used
>for exceptional conditions (or maybe it _is_ exceptional when
>something you wrote works <1e3 wink>).

You don't need the extra class -- you can raise a string if somebody's
linecounting you. But who really cares? The result is pretty darn clear.
There are no common misconceptions to fight when you're writing or reading
it (I count three people who have posted to say nothing more than "gee,
that wasn't what I expected!" about the current behavior). This code just
works!

And as for exceptions -- anyone who uses break together with else-loop but
shuns exceptions is in serious need of psychological help. That's WAY
tweaked. Exceptions are a wonderful tool; break is a useful hack.

Oh, and if you REALLY like the current behavior of else-loop, you can
still have it if else-loop were gone -- like this:

try:
for x in list:
if iffers(x): raise "no!"
yadda(x)
except "no!": pass
else:
twiddle()

That's two extra lines, and one level of nesting -- for the _exact_ same
functionality, only much more likely to be comprehended.

>> The place to use MY definition of 'else', OTOH, is when you're
>> building a structure during the iteration, but the result of an
>> empty loop is different than the initial value the variable has to
>> have when going through the loop.

>> Here you go. This example might convert a Python list into a Lisp
>> tree-list -- but to imitate Lisp (okay, it's a toy problem, I'm
>> cheating) an empty list produces NIL ~= None.

>> var = Node(None,None)
>> for x in pyList:
>> var.car = x
>> var.cdr = Node()
>> else:
>> var = None

>Not a Lisper, but isn't what you're doing better done thusly:

No no no! Don't be silly -- I was giving an example of how my idea of
else should work. I don't have time to design a system which NEEDS to be
done this way.

but-I-do-have-time-to-whine-about-something-that-isn't-going-to-change-ly
yr's,

--
-William "Billy" Tanksley

Fredrik Lundh

unread,
Jul 30, 1999, 3:00:00 AM7/30/99
to
William Tanksley <wtan...@dolphin.openprojects.net> wrote:
> >for ALL these statements, the else clause is exe-
> >cuted if and only if ALL controlling expressions
> >evaluate to FALSE.
>
> But that's not even superficially true for the current behavior of a loop.
> A loop's else clause is executed even when there were TRUE results of the
> controlling expressions.

huh? there's only ONE *controlling* expression in
the loop: the internal test that checks if the
sequence has any more items. the else clause
is executed if and only if THAT expression eval-
Traceback (innermost last):
File "effbot.py", line 12032, in effbot
File "effbot.py", line 3428, in generate_reply
raise ImpedanceMismatch # bailing out
effbot.ImpedanceMismatch


Patrick Phalen

unread,
Jul 30, 1999, 3:00:00 AM7/30/99
to pytho...@python.org
On Fri, 30 Jul 1999, Fredrik Lundh wrote:

> huh? there's only ONE *controlling* expression in
> the loop: the internal test that checks if the
> sequence has any more items. the else clause
> is executed if and only if THAT expression eval-
> Traceback (innermost last):
> File "effbot.py", line 12032, in effbot
> File "effbot.py", line 3428, in generate_reply
> raise ImpedanceMismatch # bailing out
> effbot.ImpedanceMismatch

The truth is out. "Frederick Lundh" is a bot!

Skip Montanaro

unread,
Jul 30, 1999, 3:00:00 AM7/30/99
to Patrick Phalen

Patrick> The truth is out. "Frederick Lundh" is a bot!

Now we have to deal with the fredbot as well as the timbot. Anybody for a
quick game of RoboWar?

Skip Montanaro | http://www.mojam.com/
sk...@mojam.com | http://www.musi-cal.com/~skip/
847-475-3758


ze5yr

unread,
Jul 30, 1999, 3:00:00 AM7/30/99
to
In article <379FC039...@mincom.com>,

Martin Pool <mar...@mincom.com> wrote:
> I doubt if I'll often use for: else or try: else, and perhaps
> they could have clearer names,

How about for: then?

but-what-about-all-my-variables-named-'then'-ly yrs, Cliff


--
Cliff Crawford -><-
http://www.people.cornell.edu/pages/cjc26
empty-handed I go,
)O( and behold the spade is in my hands


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.

Doug Landauer

unread,
Jul 30, 1999, 3:00:00 AM7/30/99
to
> for an "if" statement, "else" is a path taken if the
> expression evaluates to false.

In my mind, for an "if" statement, "else" is the path taken
when the BODY is not executed at all.

> for a "while" statement, "else" is a path taken if the
> expression evaluates to false. or in other words,
> when the loop terminates by natural causes.

And therefore, the "else:" on either while or for loops, as
defined in Python, is completely counterintuitive.

> not that complicated, was it?

It's not complicated, it's just something that is easily
open to multiple interpretations, depending on how one views
the normal, common usage of the word. As such, it is one of the
very few things in Python that (for some of us) is not clear from
context -- it just doesn't look obvious what the behavior should
be. So, in the spirit of python, we don't use it. Unfortunately,
others do. I hope no one ever uses it without a comment explaining
what it means.

I know it ain't gonna change soon; but one can hope that perhaps
Python 2.0 could choose a better keyword for it -- one that doesn't
come with preconceived notions that the current definition violates.
--
Doug Landauer land...@apple.com (work)
land...@scruznet.com (not-work)

F L

unread,
Jul 30, 1999, 3:00:00 AM7/30/99
to sk...@mojam.com
Skip wrote:
>Now we have to deal with the fredbot as well as the timbot.
>Anybody for a quick game of RoboWar?

note: the correct name is "effbot".

see
http://www.pythonware.com/people/fredrik/status.htm
for more info.

also see:
http://www.robocup.org

and:
http://www.aftonbladet.se/nyheter/9907/30/robocup.html
(in swedish, but you should be able to find the real-
player video links anyway)

and yes, we do apologise for that exception. usually,
such messages should be caught before they end up on
the list.

Cheers,
the eff-bot administrators


_______________________________________________________________
Get Free Email and Do More On The Web. Visit http://www.msn.com

Tim Peters

unread,
Jul 31, 1999, 3:00:00 AM7/31/99
to pytho...@python.org
[William Tanksley]
> ...

> Oh, and if you REALLY like the current behavior of else-loop, you can
> still have it if else-loop were gone -- like this:
>
> try:
> for x in list:
> if iffers(x): raise "no!"
> yadda(x)
> except "no!": pass
> else:
> twiddle()
>
> That's two extra lines, and one level of nesting -- for the _exact_ same
> functionality, only much more likely to be comprehended.

Except that when I see that loop, I'm at a loss to guess whether the
"except" clause is intended to catch otherwise-uncaught "no!" exceptions
raised by list.__getitem__, iffers(), and yadda() too. Presumably the
intent is that it should not, but there's no easy way to stop it from
catching unintended stuff too short of defining a unique exception for each
loop. for+break+else doesn't have this problem.

use-exceptions-for-exceptions-and-break-for-things-that-shouldn't-ly y'rs -
tim

William Tanksley

unread,
Aug 1, 1999, 3:00:00 AM8/1/99
to
On Sat, 31 Jul 1999 01:15:54 -0400, Tim Peters wrote:
>[William Tanksley]

>> Oh, and if you REALLY like the current behavior of else-loop, you can
>> still have it if else-loop were gone -- like this:

>> try:
>> for x in list:
>> if iffers(x): raise "no!"
>> yadda(x)
>> except "no!": pass
>> else:
>> twiddle()

>> That's two extra lines, and one level of nesting -- for the _exact_ same
>> functionality, only much more likely to be comprehended.

>Except that when I see that loop, I'm at a loss to guess whether the
>"except" clause is intended to catch otherwise-uncaught "no!" exceptions
>raised by list.__getitem__, iffers(), and yadda() too. Presumably the
>intent is that it should not, but there's no easy way to stop it from
>catching unintended stuff too short of defining a unique exception for each
>loop. for+break+else doesn't have this problem.

Very good point, Tim.

The best solution of all is to simply not use features of the language
which I find objectionable for whatever reason. I'm just disappointed in
the odd definition of for-else. I'm glad to have learned it this way
rather than by painful debugging, and I don't think any of us are likely
to forget now :).

Memo to self -- don't use for-else, it doesn't do what it looks like it's
doing.

--
-William "Billy" Tanksley

T. C. Mits

unread,
Aug 1, 1999, 3:00:00 AM8/1/99
to
ALL:
I'm a newbie so I may be out of line here, but the for: else: construct
is pretty bad. It just does not read well, and implies the incorrect
operation; it reminds me of some of the weird FORTH stuff. Why not use
another word for this and not overload 'else'? Maybe for: also:, or
something more in line with the intended purpose. Sure there may be good
reasons for else that I (newbie) do not know, but I thought Python was
supposed to enable ease of reading, not only writing (ala Perl).

TC Mits.


Hans Nowak <ivn...@hvision.nl> wrote in message
news:1999072722...@axil.hvision.nl...
>
> On 27 Jul 99, Oleg Broytmann wrote:
>
> > > Loop statements may have an else clause; it is executed when the loop
> > > terminates through exhaustion of the list (with for) or when the
> > > condition becomes false (with while), but not when the loop is
> > > terminated by a break statement. [..]
> > [skip]
> > > Else clauses get executed on normal loop exit, even if the loop was
> > > 'empty'. It does not get executed when you 'break' out of a loop.
> >
> > Aha, thanks. I expected "else" to be executed when "for" not executed
> > on
> > empty list. Wrong assumption.
>
> This one has bitten me too in the past. One of the few non-intuitive
> parts of Python, methinks. :(

bowman

unread,
Aug 1, 1999, 3:00:00 AM8/1/99
to
T. C. Mits wrote:
>
> ALL:
> I'm a newbie so I may be out of line here, but the for: else: construct
> is pretty bad. It just does not read well, and implies the incorrect
> operation;

I would agree that this use of 'else' is counterintuitive, though is
isn't quite as bad as Perl's use of 'continue'. Java's keyword,
'finally', would be another option, but that carries the meaning of a
block that is always executed.

In practice, it doesn't seem to be necessary, so it can be ignored by
old C coders who can't quite remember how it works.

--
Bear Technology Making Montana safe for Grizzlies

http://people.montana.com/~bowman/

John (Max) Skaller

unread,
Aug 4, 1999, 3:00:00 AM8/4/99
to
On Thu, 29 Jul 1999 08:51:15 +1200, Greg Ewing <greg....@compaq.com> wrote:

>Gordon McMillan wrote:
>>
>> But finding a match in a list, and testing whether you
>> fell off the end without finding one, is (without the else clause) a
>> much messier proposal.
>
>Not if you go about it the right way. I always
>put such loops in a procedure of their own,
>and use return:
>

> def find_the_holy_grail(stuff):
> for x in stuff:
> if is_holy_grail(x):
> return x
> return None

Unfortunately, python lacks lexical scoping, which means this technique
cannot be easily generalised. In particular, if the loop body requires
access to the current context, you can't use a function to encapsulate it.


John Max Skaller ph:61-2-96600850
mailto:ska...@maxtal.com.au 10/1 Toxteth Rd
http://www.maxtal.com.au/~skaller Glebe 2037 NSW AUSTRALIA

John (Max) Skaller

unread,
Aug 4, 1999, 3:00:00 AM8/4/99
to
On Fri, 30 Jul 1999 02:40:42 GMT, wtan...@dolphin.openprojects.net (William Tanksley) wrote:

>On Wed, 28 Jul 1999 16:38:24 -0500, Gordon McMillan wrote:
>

>try:
> for x in list:
> if iffers(x): raise "no!"
> yadda(x)
>except "no!": pass
>else:
> twiddle()

Not guarranteed to work. Try instead:

exc = "no!"
... raise exc
..
except exc: ..

Python requires the object of a raise to be the same object
as that in the except clause: it is not enough for them to
compare equal as values. Your example only works because
python interns string constants; an implementation detail.

My python interpreter doesn't intern string constants.
The code above will still work, but only because I have extended
the semantics to allow matching by value (which will break
some technically correct python codes).

John (Max) Skaller

unread,
Aug 4, 1999, 3:00:00 AM8/4/99
to
On Wed, 28 Jul 1999 14:57:55 -0700, "Vadim Chugunov" <che...@yahoo.com> wrote:

>When I first saw Python syntax for loops I said: "A-ha! So in Python I will not
>need a goto
>in situations like this:
>-----
>for(Item* pitem=pseq->First(); pitem; pitem=pitem->Next())
> if (pitem->key==42)
> goto Found;
>
>pitem = pseq->Insert(new Item());
>Found:
> // use item pointed to by pitem
>-----
>In fact, I do not see any other good use for else: clause in a loop.

Isn't this a fine reason for it?

0 new messages