0

I am getting the following Name Error in my python program though I declared the function before it is used.

Here is my program:

def __init__(self):
    self.root = None


def insert_at(leaf, value):
    #some code here....


def insert(self,value):
    #some code here....
    insert_at(self.root, value)


def main():
    #some code here
    insert(10)
    #some code here

Here is my error:

File "programs/binary_tree.py", line 38, in insert
insert_at(self.root, value)
NameError: name 'insert_at' is not defined

I did go through the following questions before asking this question, but couldn't understand why I am getting the error.

Make function definition in a python file order independent and Python NameError: name is not defined

Community
  • 1
  • 1
honey
  • 51
  • 1
  • 1
  • 7

1 Answers1

2

Looks like those are methods in a class. You need the following changes:

def insert_at(self, leaf, value): # add self

 

self.insert_at(self.root, value) # add self
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Thanks a lot. This helped. – honey Jul 09 '15 at 19:10
  • Lets say I recusrively call insert_at() inside insert_at().. Should i still use self? i.e, inside insert_at(), should i call it again by self.insert_at() or just insert_at(). I tried both and they are working...Didnt understand the difference though. – honey Jul 09 '15 at 19:15
  • Yes, still use `self`. – TigerhawkT3 Jul 09 '15 at 19:15