Python for Water Resources Engineering

Jon Herman, University of California, Davis

Getting started

Python is a general-purpose programming language with many powerful open-source libraries for research computing. This will be a beginner tutorial describing how to set up the scientific Python environment on your computer and perform common research tasks in hydrology and water management.

First, install the Anaconda distribution. This includes a number of useful packages (a full list here) and is much easier than managing these packages individually. Choose the Python 2.7 version for your operating system, since not all packages have adopted Python 3 standards yet.

Once the installation completes, you should see a new program called the Anaconda Launcher. You can run this to access Spyder, the interactive development environment (IDE) included with the installation. Spyder should open a new Python file (.py), where you can run:

In [18]:
print("hello world!")
hello world!

In general you should be able to copy and paste any code from this tutorial into your file and run it. When you have this file open (call it helloworld.py for example) and press "Run" in the Spyder interface, behind the scenes Spyder is calling python helloworld.py. In other words, it is running the Python interpreter on your file to execute the code you wrote. Importantly, Spyder is not the only way to run Python code! There are other IDEs out there, and you could even use a simple text editor and call the interpreter yourself from the command line. You may want to explore other editors/IDEs as you get more comfortable with the language.

Some general tips

  • Using the code in these notebooks as a starting point, make your own modifications and see what happens. Try to think about what you expect to happen before running the program.
  • The computer will do exactly what you tell it to do, which is not always what you want it to do. The correctness of your program is up to you!
  • Much like writing a paper, writing code is a process of drafting and revising. Aim for a working version first, then worry about efficiency. The latter step will go a long way toward making your research reproducible.
  • Google is your friend. One of the many benefits of Python is the online community, where most problems you'll encounter have already been answered.
  • Don't reinvent the wheel. Many numerical operations are already included in packages like NumPy and SciPy; check first before writing them yourself.

Table of Contents

  1. Python language basics - variables, loops, lists, and dicts
  2. Numpy and Matplotlib - array/matrix operations and plotting
  3. Optimization - LP, QP, NLP