[Tutor] syntax error

Carroll, Barry Barry.Carroll at psc.com
Tue Aug 1 00:58:32 CEST 2006


Hello Chris,

> -----Original Message-----
> Date: Mon, 31 Jul 2006 15:29:13 -0700 (PDT)
> From: Christopher Spears <cspears2002 at yahoo.com>
> Subject: [Tutor] syntax error
> To: tutor at python.org
> Message-ID: <20060731222913.40214.qmail at web51615.mail.yahoo.com>
> Content-Type: text/plain; charset=iso-8859-1
> 
> My brain has gone squishy.  I am combining a linked
> list with a priority queue.  This is the last exercise
> out of How To Think Like A Computer Scientist (Chapter
> 19).
> 
<<snip>>
> 
> 	def insert(self, cargo):
> 		node = Node(cargo)
> 		node.next = None
> 		if self.length == 0:
> 			# if list is empty, the new node is head and
last
> 			self.head = self.last = node
> 		elif node.cargo > self.head.cargo:
> 			node.next = self.head
> 			self.head = node
> 		else node.cargo <= self.head.cargo:
> 			self.last.next = node
> 			self.last = node
> 		self.length = self.length + 1
> 
<<snip>>
> 
> Here is the error message:
> >>> from linkedPriorityQueue import *
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "linkedPriorityQueue.py", line 27
>     else node.cargo <= self.head.cargo:
>             ^
> SyntaxError: invalid syntax
> 
> I am not sure what this means.  Everything is spelled
> correctly.
> 
> -Chris
> 

The syntax error occurs just after the "else".  Unlike "if" and "elif",
"else" does not take an expression. It covers any cases left over after
the "if" clause and all of the "elif" clauses have been tried and
failed.  The expression "node.cargo <= self.head.cargo" is therefore
logically unnecessary. Python (and all other programming languages I
know of) enforces this by making it illegal to put an expression in an
"else" clause.   

I don't have access to "How To Think Like A Computer Scientist", so I
can't point you to the section that discusses this, but I'm sure it's in
there somewhere.  Look in the index for "else clause", "if-elif-else
statement" or some entry like that.  

HTH.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




More information about the Tutor mailing list