Helpful Hints for Homework

A few thing about Python will help you with your homework. We will discuss these later in class; for now, you can just use the code here. But feel free to look ahead!

Exiting your program

In general, a Python program ends when it reaches the end of the program. If you want to exit before then, put

import sys

in your file before any Python code.

If you want to exit and indicate your program worked, put this line where you want to quit:

sys.exit(0)

If you want to exit and indicate your program didn’t work as expected (for example, the user entered incorrect input and you need to quit), put this line where you want to quit:

sys.exit(1)

The “0” is a standard code indicating sucess and the “1” is an exit code indicating a failure of some kind.

The math library

Some problems will use mathematical functions. Python provides them in a module. To invoke the functions, put

import math

Then, for example, to call the function e5 (that is, the base of the natural logarithms raised to the power 5), use this:

math.exp(5)

If you want to see what math functions are available in this module, enter

help(math)

and you will get a detailed list. If you just want the function names,

dir(math)

will give them to you in a compact, cryptic format (it’s actually a Python expression that we will discuss later).

These work for any standard Python module, by the way.


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
MHI 289I, Programming for Health Informatics
Version of October 1, 2020 at 12:17PM

You can also obtain a PDF version of this.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh