0

So i'm trying to make simple hangman game, but while testing i cant append words from txt file to list, so the program can draw the word. Here is the code:

    import random
    words = []
    def wordsChoose(mode, words):
        mode = str(mode)+'.txt'
        for line in open(mode):
            words = words.append(line.rstrip())
        theword = random.choice(words)
        return theword

    wordsChoose('fruits', words)

i get the: 'AttributeError: 'NoneType' object has no attribute 'append''

maybe there is a better option to do this

  • append is in place function and return nothing change `words = words.append(line.rstrip())` line to `words.append(line.rstrip())` – Yefet Nov 23 '21 at 09:58
  • Hi please add line number of code which causes error. – Reza Akraminejad Nov 23 '21 at 10:01
  • I recommend [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for some tips on debugging your code. This won't necessarily solve the problem, but it will help you find the line of code that causes it. – Code-Apprentice Mar 08 '23 at 20:31

1 Answers1

1

You should only call the .append method. You don't need to assign a variable to it -

import random
words = []
def wordsChoose(mode, words):
    mode = str(mode)+'.txt'
    for line in open(mode):
        words.append(line.rstrip())
    theword = random.choice(words)
    return theword

wordsChoose('fruits', words)

You get None Type Error, because .append is an in-place method (therefore, it returns None), so there is no point in assigning variables.

PCM
  • 2,881
  • 2
  • 8
  • 30