global … is not defined python

后端 未结 3 1328
有刺的猬
有刺的猬 2021-01-29 12:24

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:
    fo         


        
相关标签:
3条回答
  • 2021-01-29 12:52

    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
    
    0 讨论(0)
  • 2021-01-29 12:57

    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.

    0 讨论(0)
  • 2021-01-29 13:05

    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)
    
    0 讨论(0)
提交回复
热议问题