Tips & Tricks

You can use to access the course page (

python3 -i <your script>

python3 -i <your script> runs the script in the interactive mode: after the script finishes, instead of exiting the Python execution and returning the control to shell, Python will enter the REPL mode. The top-level declarations will be available so that you can interact with. This is extremely useful for debugging.


    $ cat
    def square(x): return x*x

    value = [square(x) for x in range(10)]

    $ python3 -i   # this runs the script and then enters the REPL mode
    >>> value              # you can interact with values defined in the script
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    >>> sum(value)
    >>> square(sum(value)) # you can use functions defined in the script
    >>> 285**2
    >>> quit()
    $ _


Doctests are tests in a form of documentation of the function. Often, we provide them in stencil files. For example:

    ## 1: (Task 0.0.0) Absolute
    def my_abs(v):
        Input: a real number
        Output: the absolute value of the input

        >>> x = 7
        >>> my_abs(x)
        >>> my_abs(1 - x) + 2

Doctests are great not only because they are tests that you can use, but also because you can run them via the module doctest. To invoke the module, type python3 -m doctest <a stencil file> in the REPL.

Now, suppose we replace pass with return v (which is wrong), we will get the following:
    $ python -m doctest
    File "", line 10, in mylab.my_abs
    Failed example:
        my_abs(1 - x) + 2
    1 items had failures:
       1 of   3 in mylab.my_abs
    ***Test Failed*** 1 failures.

Now, we change it to the right answer: return v if v >= 0 else -v. After running the doctest again, the output should be nothing since everything is correct.

The doctest module will run every doctests in a file. If you wish not to run them, you might consider commenting out functions that you do not want to test. Lastly, doctest will not work if you call print function in your file! One way to avoid the problem is to remove all print functions. The other way is to import sys at the top of the file, then change all print to print(..., file=sys.stderr) which will avoid the confict with doctest module.

Are there any tips you think should be included here? Please send your tips to our TA list!