1 How to write and test a Python program

 

Before you start working on the exercises, I want to discuss how to write programs that are documented and tested. Specifically, we’re going to

  • Write a Python program to say “Hello, World!”
  • Handle command-line arguments using argparse
  • Run tests for the code with Pytest.
  • Learn about $PATH
  • Use tools like YAPF and Black to format the code
  • Use tools like Flake8 and Pylint to find problems in the code
  • Use the new.py program to create new programs

1.1 Creating your first program

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 toward making a version that will greet whichever name is passed as an argument. It will also print a helpful message when we ask for it, and we’ll use tests to make sure it does everything correctly.

In the 01_hello directory, you’ll see several versions of the hello program we’ll write. There is also a program called test.py that we’ll use to test the program.

Start off by creating a text file called hello.py in that directory. If you are working in VS Code 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:

print('Hello, World!')

1.2 Comment lines

1.3 Testing your program

1.4 Adding the #! (shebang) line

1.5 Making a program executable

1.6 Understanding $PATH

1.6.1 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

sitemap