jpjosey
jpjosey

Reputation: 3

Learning Python - syntax error preventing me from proceeding in tutorial

As the title suggests I'm doing a tutorial. I have however come across this error:

>>> from words import (fetch_words, print_words)
>>> print_words(fetch_words())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\jjosey\Documents\pyfund\words.py", line 12, in print_words
    for word in story_words:
TypeError: 'NoneType' object is not iterable

When calling this file (words.py):

from urllib.request import urlopen

def fetch_words():
    with urlopen('http://sixty-north.com/c/t.txt') as story:
        story_words = []
        for line in story:
            line_words = line.decode('utf-8').split()
            for word in line_words:
                story_words.append(word)

def print_words(story_words):               
    for word in story_words:
        print(word)

def main():
    words = fetch_words()
    print_words(words)          

if __name__ == '__main__':
    main()

I understand that the error suggests I'm calling a null array. But this is exactly what the tutor does in the video, so I'm assuming I've made a typo somewhere that's caused the error to hit me. And this is day one of my learning Python, so I'm not spotting it.

Any help appreciated. Thanks

Upvotes: 0

Views: 312

Answers (2)

Paul Becotte
Paul Becotte

Reputation: 9997

def fetch_words():
    with urlopen('http://sixty-north.com/c/t.txt') as story:
        story_words = []
        for line in story:
            line_words = line.decode('utf-8').split()
            for word in line_words:
                story_words.append(word)

This function has a bug... it does not return a value, though you try to use the returned value later. Try this...

def fetch_words():
    story_words = []
    with urlopen('http://sixty-north.com/c/t.txt') as story:
        for line in story:
            line_words = line.decode('utf-8').split()
            for word in line_words:
                story_words.append(word)
    return story_words

Upvotes: 0

Kevin
Kevin

Reputation: 76244

Try putting a return statement at the end of fetch_words. Without it, words = fetch_words() will cause words to be None.

def fetch_words():
    with urlopen('http://sixty-north.com/c/t.txt') as story:
        story_words = []
        for line in story:
            line_words = line.decode('utf-8').split()
            for word in line_words:
                story_words.append(word)
    return story_words

Upvotes: 4

Related Questions