Docstring & doctests

You can type open . on MacOS or start . on Windows to open the current directory in your Finder/File Explorer.


def twenty_eighteen():
    """Come up with the most creative expression that evaluates to 2018,
    using only numbers and the +, *, and - operators.

    >>> twenty_eighteen()

    return ______

The lines in the triple-quotes """ are called a docstring, which is a description of what the function is supposed to do.

The lines that begin with >>> are called doctests. Doctests explain what the function does by showing actual Python code: "if we input this Python code, what should the expected output be?"

Useful Python command line options

When running a Python file, you can use options on the command line to inspect your code further. Here are a few that will come in handy. If you want to learn more about other Python command-line options, take a look at the documentation.

  • Using no command-line options will run the code in the file you provide and return you to the command line.

  • -i: The -i option runs your Python script, then opens an interactive session. In an interactive session, you run Python code line by line and get immediate feedback instead of running an entire file all at once. To exit, type exit() into the interpreter prompt. You can also use the keyboard shortcut Ctrl-D on Linux/Mac machines or Ctrl-Z Enter on Windows.

    ⚠️ If you edit the Python file while running it interactively, you will need to exit and restart the interpreter in order for those changes to take effect.

    python3 -i
  • -m doctest: Runs doctests in a particular file. Doctests are surrounded by triple quotes (""") within functions. Each test consists of >>> followed by some Python code and the expected output.

     python3 -m doctest


Lab 0: Setting up a productive workflow

Creative Commons License