no SyntaxError?
Brett g Porter
BgPorter at NOacmSPAM.org
Tue Jun 13 16:39:20 EDT 2000
"Robert W. Bill" <rbill at digisprings.com> wrote in message
news:Pine.LNX.4.10.10006131359020.17071-100000 at localhost.localdomain...
> However, the following snippet generates "0 1 whoops" when it seems like
> it should also generate "SyntaxError: invalid syntax" because there is no
> if before the else.
>
> def test1():
> for i in range(2):
> print i,
> else:
> print "whoops"
>
> test1()
>
> Why is it that I do not get a "SyntaxError" in the second example?
Loops in Python may have an optional else: clause that's only executed if
the loop runs to completion. It's used like this:
def find(list, value):
for i in list:
if i == value:
print 'Found it!'
break
else:
print 'couldn't find %d' % value
More information about the Python-list
mailing list