Let's organize our words module using functions.
First we'll move all the code except the import statement into a function called fetch_words()
. You do that simply by adding the def
statement and indenting the code below it by one extra level:
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) for word in story_words: print(word)
Save the module, and reload the module using a fresh Python REPL:
$ python3 Python 3.5.0 (default, Nov 3 2015, 13:17:02) [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import words
The module imports, but the words are not fetched until we call the fetch_words()
function:
>>> words...