Python Tips

If you are new to Python, we’re recommending that you install the Anaconda distribution on your computer. But if you already are up and running and happy with some other Python install, that’s fine too, but you will want to make sure that astropy and its dependencies are installed (Anaconda installs/updates astropy automatically)… Aside: there are two major versions of python in use today, 2.7.x, and 3.x. There are (mostly) minor differences between the two versions relating to syntax, implementation, etc (and notably, print v. print()). I recommend that you use Python 3.x if you’re just starting out – this will be the version that is well-supported going forward – but don’t have a problem with you using 2.7.x if that’s what you know. Just be aware that there are differences, especially when you’re looking for help!

Here is the general documentation for the various packages included in Anaconda.

For writing/debugging python code, an easy recommendation are jupyter notebooks, which work well and print results alongside your code. I am “old school”, and use a text editor and the command line. Spyder, PyCharm, and other IDEs can also be helpful. What’s best for you all depends on your programming style and preference. Use what helps you get your work done well and on time!

Getting help

First of all, try python interactive help or checking the online package documentation. For example, help on the scatter command can be obtained by saying help(plt.scatter) (presuming you’ve already loaded the pyplot package, i.e. import matplotlib.pyplot as plt)

Second, check some online tutorials/references, such as:

Third (or maybe first), try GOOGLE. For example, if I want to figure out how to fit a curve to data using python, I’ll just google fit curve to data python. Or if I have a bizarre error message that I don’t understand, I’ll google <bizarre error message> python, but remember to be careful about what version of python you’re finding answers for. Adding astropy to the search will often give you astro-specific results as well, which can be particularly helpful. You may have to poke around with the results of those searches to find the best answer, but it usually works out. Sometimes you won’t get any results at all about your problem, which brings us to…

Fourth, ask your classmates, or The TA™, or me. I put this last not because we are reluctant to help – we’re happy to do so! – but rather because the first three things are available to you 24/7 and give immediate (although admittedly not always helpful) responses.

Why Python?

A survey of coding tools used by research astronomers at all levels (left) and PhD astronomy students (right). Taken from Momcheva & Tollerud (2015).

python chart