[Tutor] Unsupported operand types for +: 'NoneType' and 'int' - HUH?!
Neil Schemenauer
nas@python.ca
Fri Jun 6 17:11:02 2003
Eladio Ventura wrote:
> I try to make a function which calculates the total number of nodes
> and get the following error:
>
> TypeError: unsupported operand types for +: 'NoneType' and 'int'
You are trying to add an integer to None.
>
> The culprit is the following function:
>
> def size(self, tree):
> if tree == None: return
> else:
> return self.size(tree.left) + 1 + self.size(tree.right)
Your problem is with the line "if tree == None: return". You want:
if tree is None:
return 0
Note that a bare return statement is the same as "return None".
> class Tree:
> def __init__(self, cargo=None, left=None, right=None):
> self.cargo = cargo
> self.left = left
> self.right = right
>
> def build123a(self):
> root = Tree(2)
> left = Tree(1)
> right = Tree(3)
> root.left = left
> root.right = right
> return root
>
> def printTreeInorder(self, tree):
> if tree == None: return
> self.printTreeInorder(tree.left)
> print tree.cargo,
> self.printTreeInorder(tree.right)
>
> def size(self, tree):
> if tree == None: return
> else:
> return self.size(tree.left) + 1 + self.size(tree.right)
There is no reason for build123a(), printTreeInorder() and size() to be
methods. They would be simpler as functions since you don't use "self".
Eg:
class Tree:
...
def build123a():
left = Tree(1)
right = Tree(3)
root = Tree(2, left, right)
return root
def printTreeInorder(tree):
...
HTH,
Neil