1 How to write and test a Python program

 

Before we start writing the exercises, I want to discuss how to write programs that are documented and tested using the following principles. Specifically, we’re going to:

  • Write our first Python program to say "Hello, World!"
  • Handle command-line arguments using argparse
  • Run tests for your code with pytest
  • Learn about $PATH
  • Use tools like yapf or black to format your code
  • Use tools like flake8 and pylint to find problems in your code
  • Use the new.py program to create new programs

It’s pretty common to write "Hello, World!" as your first program in any language, so let’s start there. We’re going to work towards making a version that will greet a name that is passed as an argument. It will also print a helpful message when we ask for it, and we’re going to use tests to make sure it does everything correctly. In the 01_hello directory, you’ll see there several versions of a "hello" program we’ll write. There is also a program called test.py that we’re going use to test the program.

Start off by creating a text file called hello.py in that directory. If you are working in VSCode or PyCharm, you can use "File → Open" to open the 01_hello directory as a project. Both tools have something like a "File → New" menu option that will allow you to create a new file in that directory. It’s very important to create the hello.py file inside the 01_hello directory so that the test.py program can find it!

Once you’ve started a new file, add this line:

1.1  Comment lines

1.2  Testing our program

1.3  Adding the shebang line

1.4  Making a program executable

1.5  Understanding $PATH

1.6  Altering your $PATH

1.7  Adding a parameter and help

1.8   Making the argument optional

1.9  Running our tests

1.10  Adding the main() function

1.11  Adding the get_args() function

1.11.1  Checking style and errors

1.12  Testing hello.py

1.13  Starting a new program with new.py

1.15  Summary