global … is not defined python

2019-03-07 04:01发布

问题:

I need to read some words text by text in python, and I am getting this error. "NameError: global name 'wordList' is not defined.

i=0
with fitxer as f:
    for line in f:
        for word in line.split():
              wordList[i]=word
              i+1
return wordList

回答1:

You need to define wordList to begin with. And you cannot randomly assign indexes in an empty list. You can easily 'extend' the list with new values.

worldList = []
with fitxer as f:
    for line in f:
        wordList.extend(line.split())
return wordList


回答2:

wordList is not instantiated as a list or not in scope.

If wordList is a global variable, the beginning of your function will need global wordList Not needed because the object is mutated

If the list should only be in scope of the function you will need to instantiate it as a list.

wordList = []

Edit: as deceze pointed out

Within the function itself you should be appending to the list since the index does not exists.

wordList.append(word)


回答3:

You haven't defined wordList before you try to use it in your loop or return it.

Try adding wordList = [] below i=0 to declare wordList as an empty list.

Also, you should use wordList.append(i) to add your word this list.



标签: python global