Organizing code in a .py file

Let's start with the snippet we worked with in Chapter 2Strings and Collections. Open a text editor – preferably one with syntax highlighting support for Python – and configure it to insert four spaces per indent level when you press the tab key. You should also check that your editor saves the file using the UTF 8 encoding as that's what the Python 3 runtime expects by default.

Create a directory called pyfund in your home directory. This is where we'll put the code for the chapter.

All Python source files use the .py extension, so let's get the snippet we wrote at the REPL at end of the previous module into a text file called pyfund/words.py. The file's contents should looks like this:

from urllib.request import urlopen

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)

You'll notice some minor differences between the code above and what we wrote previously at the REPL. Now that we're using a text file for our code we can pay a little more attention to readability, so, for example, we've put a blank line after the import statement.

Save this file before moving on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset