[Tutor] else syntax error problem
Ivan Van Laningham
Mon, 05 Jun 2000 15:50:43 -0600
Nigel Pauli wrote:
> I am having the strangest problem here.
> I am completely new to python (and programming, really) and am happily
> working my way through the van Laningham book. In the spirit of learning
> by doing rather than just reading I have been typing in his excellent
> screen shots [could be a tad larger for easier reading, mind you]
I'll say. I'm looking into redoing them for the second printing;
failing that, I will try to put larger versions on the book's website.
> and I've
> come unstuck on the ones to do with else and elif. Here's what I see in my
> *Python Shell* window when working through fig 4.8 which is an amusing
> little number that does a rocket countdown leading to Blastoff!
> >>> for i in range(10,-1,-1):
> if i != 0:
> print i
> SyntaxError: invalid syntax
> What should continue after else is...
> print "Blastoff!"
> What it looks like is that the part of python that handles else and elif
> is missing - but that's daft, isn't it? Is it significant that that else:
> below print i isn't hanging indented to be back underneath the if 2 lines
> If it helps, I'm using Python 1.5.2 on Mandrake Linux 7.0.
> Many thanks to anyone who can penetrate the fog for me on this one.
Here's a transcript of an interactive session:
25 [/c/temp/PyXML-0.5.4/extensions] python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> for i in range(10,-1,-1):
... if i!=0:
... print i
... print "Blastoff"
Notice that while Python obligingly lets you know that you need indent
levels by printing the "..." prompt, it does not guess at what level you
want to use (it can't, otherwise it would be too smart to live). In the
example above, I simply used one space for each indent level. "for
i..." is at 0; "if i!=0:" is at one, "print i" is at two, and the
"else:" line *must* match the indent level for "if i!=0:", so it has to
be one. Use the backspace key. "print Blastoff" line is back to indent
Hope this helps,
Ivan Van Laningham
Axent Technologies, Inc.
Army Signal Corps: Cu Chi, Class of '70
Author: Teach Yourself Python in 24 Hours