Learning Python for Science

Here I outline how to learn Python on your own with emphasis on solving science problems. The first section applies to anyone, but the end is specialized towards computational problems that arise in science.

Python Basics

I recommend the following two tutorials:

Some additional resources that may be helpful include:

My suggested workflow:

  1. Do Codecademy and Python the Hard Way at the same time.
  2. If Codecademy/Python the Hard Way is too difficult, also read a Byte of Python.
  3. If Codecademy/Python the Hard Way is easy, use Think Python as an additional resource.
  4. If you are confused about a specific chunk of code, put it into Python Tutor which will walk you step by step through the program.
  5. Additionally, Google and Stack Overflow are extremely useful for coding questions or go to the original Python documentation.

The essential things one needs to learn about Python include:

  • data types: int, float, string
  • data structures: lists, dictionaries, tuples, sets
  • control statements: for, while, if else
  • print function
  • open / write to a text file
  • custom functions and objects
  • list comprehensions – comes up less often in numerical code, but still good to know

 

Numpy and Scipy

Numpy is the essential mathematics module in Python and is part of the larger Scipy project. All standard numerical needs are covered in Numpy, while more advanced functions are in Scipy.

I recommend the following tutorials:

  • Numpy’s tutorial
  • This fun tutorial that programs the Game of Life (GoL). I only recommend the section that implements GoL in Numpy, the rest of it is not essential. It also has a useful quick reference guide.
  • This Numpy tutorial from Scipy Lecture Notes

 

Matplotlib

Visualizing data is essential to understanding and communicating science ideas. Matplotlib is the standard plotting module. While it has its limitations, I still personally use it for my everyday plots. For more advanced plot types, check out Plotly, Seaborn, Mayavi, ggplot, and Bokeh.

And assuming you are new to making scientific figures, there are some good habits you should get into. First, read these tips from Plos. Second, never ever use rainbow colors aka jet. Color challenged people like myself will hate you. Please stick with a color map that uses shading sensible. Besides making me happy, it also is easier to print to gray scale.

 

Advertisements