R. Sweet R. Sweet - 1 month ago 9
Python Question

Why am i getting an error when calling main()?

so here's some code i have that is supposed to take text entered by the user and create a dictionary. Can anyone tell me why I get a traceback error when I call the function main()?

def build_index(text):
index = {}
words = text.split()

position = 0

for x in text:
if x.isalpha() == False and x.isdigit() == False:
text.join(x)
else:
text.replace(x,'')

while position < len(words):
nextword = words[position]

if nextword in index:
ref = index[nextword]
ref.append(position)
index[nextword] = ref

else:
list = []
list.append(position)
index[nextword] = list
position += 1


def displayindex(index):
keys = sorted(index.keys())
for key in keys:
print(key + ':' + str(index[key]))

def main():
text = input("enter text")
build_index(text)
displayindex(index)
main()

Answer

The traceback error contents depends on which version of Python you're running your code in. In Python 3.x, the traceback explains why it's producing the error:

Traceback (most recent call last):
File "./prog.py", line 37, in
File "./prog.py", line 36, in main
NameError: name 'index' is not defined

TLDR: Need to add/change only 3 lines of code. See comments in code below

The NameError is telling us that it doesn't know what the name index refers to, because it's out of the scope of the main method and hasn't gotten defined yet. You could create the global instance of the index variable as mentioned in MeterLongCat's answer, but since index does get created and defined when we call build_index, we can just return index after that method call, save its return value, then pass it to the displayindex function, as follows.

OTOH, in Python 2, as MeterLongCat points out, you're wanting to get a string from the user, which is not what input is for, you want raw_input.

def build_index(text):
    index = {}
    words = text.split()

    position = 0

    for x in text:
        if x.isalpha() == False and x.isdigit() == False:
            text.join(x)
        else:
            text.replace(x,'')

    while position < len(words):
        nextword = words[position]

        if nextword in index:
            ref = index[nextword]
            ref.append(position)
            index[nextword] = ref

        else:
            list = []
            list.append(position)
            index[nextword] = list
        position += 1
    return index                    # Return the index


def displayindex(index):
    keys = sorted(index.keys())
    for key in keys:
        print(key + ':' + str(index[key]))

def main():
    text = raw_input("enter text")  # Use raw_input
    index = build_index(text)       # Assign the index
    displayindex(index)
main()