Python Tutorial

http://xkcd.com/353/ by Randall Munroe. Please don't sample anything in the cabinets.

Before you begin...


Before you begin, make sure that you have done the following things:

  • Download and install the Anaconda python distribution so that you can run Jupyter notebook.
  • Familiarize yourself with the Jupyter environment by making sure you can open and run files.
    • Download one of the tutorials below, and save it to a folder on your computer. 
    • Open Jupyter Notebook (or alternately open Anaconda Navigator and within that program, launch Jupyter Notebook). A new tab on your internet browser should open up displaying a directory of your computer.
    • Navigate that directory to the place where that file was downloaded. You should be able to double-click on the notebook from within the Jupyter directory, and the file should open in a separate tab.
    • Try to execute the first few cells by selecting the cell with your mouse and hitting “shift+enter” on your keyboard.
  • Read the page An Introduction to Python.
    • This will orient you and give you examples of some some basic syntax and techniques.
Completely new to programming?

These Python tutorials assume that you have some background knowledge of common programming terminology (e.g. variables, strings, for loops) and at least novice coding experience in some programming language.

If you haven't done any programming previously, you will probably need some additional support in getting started. Thus, we've curated a list of resources for learning the basics of programming in Python.

Online Python Resources

Introduction to Python for Data Scientists Online course with a series of video tutorials, designed to introduce you to Python in about 4 hours.

How to Think Like a Computer Scientist / Interactive Version

This online book assumes no previous programming knowledge; working through to chapter 12 should be plenty sufficient to do anything asked of you in the course. The interactive version embeds the programming tasks in your web browser, if you'd prefer to work that way.

A Crash Course in Python for Scientists

Written by Rick Muller at Sandia National Laboratories, this tutorial has a heavy focus on using Python for physics.  Heavily based on using examples.

Lectures on scientific computing with Python Basically an online textbook, written by Robert Johansson at the iTHES Research Group.  Also written primarily for physicists.

Interactive Online Course from the University of Waterloo

Tools to learn & practice Python online, with a computer science emphasis. Their focus will be different from other tutorials, but the change in perspective might be useful.

Introduction to Python Programming for Number Theoretic Applications

While this introduction quickly veers into math-specific topics, the first 3 exercises serve as a good introduction to working in Jupyter notebooks.

Automate the Boring Stuff with Python

Another book that assumes no programming experience. Focuses on accomplishing tasks like sorting / filtering information or automating file organization.

Cracking Codes with Python Invent Your Own Computer Games with Python Making Games with Python & Pygame

These three books are by the previous author, for anyone who would rather work with some more tangential topics. The end result is still transferable skills, so learn whatever way works best for you.

Goals and procedures


To complete this tutorial, set up a folder on your computer where you will download the files and save all your output. (If you will be using Google Colab instead, upload all the files to your Google Colab folder on Google Drive.) As you work through each example you will do the following:

  • read through working example code and comments to understand how certain tasks are done;
  • run and modify the example program to see the output;
  • create new code (usually by copying and modifying existing code) in the labeled “Task” sections; and
  • create one key plot for each example which will be turned in.

These tutorial scripts are meant to give you familiarity with all the features of Python that you will use this year in lab. If you have any trouble completing the tutorial or understanding features of the code, please ask for help and have patience.

Programing well takes practice, but we are using coding here as a tool, not as the goal in itself. If at any point in the year you find yourself struggling with the programming more than the physics, stop and ask a TA for help; we do not want Python to be a major (or even big) part of your time commitment for this class.

For some of the most common issues we've seen in this course, we've set up a Python FAQs and Common Problems page.

Assignments


Example 1

Files needed for Example 1:

In Example 1, we introduce ways to generate and plot data by making two different figures.

Exercise

Work your way through the notebook, and ask for help if you need it!

After completing the notebook, be sure to save the final plot from Task 5. This will be the key plot you turn in for Example 1.

More Plotting Help

If you'd like a broader introduction to what Matplotlib can do, visit J.R.Johansson's tutorial: https://nbviewer.jupyter.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-4-Matplotlib.ipynb

When making subplots like this, python sometimes allows axes labels, titles or other text to overlap in ugly ways. To avoid this, you can use the matplotlib function tight_layout() which will adjust the spacing so that features don't overlap. Insert this function just before saving your file and using the function show().

It sometimes is necessary to also specify an extra amount of space to be added by using the “pad” option – for example, tight_layout(pad = 2) – where the amount of extra padding is in units of the font size. For example, in your code, the last few lines might read as follows:

plt.tight_layout(pad = 2)
plt.savefig('wicked_awesome_plot.png')
plt.show()

Example 2

Files needed for Example 2:

In example 2, we import data from an external file (example2_data.tsv) instead of generating it inside the program. We then fit that data to simple functions and plot both the data and fit on a single plot. See the page on least-squares fitting to understand the notation used in the program.

Open the data file to see how the data is stored, then look through the script file to understand each step. We introduce many new features here; in particular, note how we do fits as this will be a big part of your python work this quarter.

Exercise

After completing the whole notebook, be sure to save the final plot from Task 5.

Example 3

Files needed for Example 3:

In Example 3, we again perform a fit, but this time to a decaying exponential. 

Exercise

In almost every experiment this year, you will have to do some version of the following exercise:

  • record data in your lab notebook;
  • translate this handwritten data into a digital form;
  • manipulate the data;
  • plot the data; and
  • fit the data.

This notebook will step you through not only how to do this, but also how to format your output to look nicer.

After completing the whole notebook, be sure to save the final plot from Task 6. This will be the key plot you turn in for Example 3.

Example 4

Files needed for Example 4:

In Example 4, we again import data from an external file (Example4_Data.tsv), but this time it is more a more elaborate PHA spectrum. The new element here is that we will plot all the data, but only fit a portion of it. In addition, we will use a more elaborate fit function this time with several parameters and more complex background.

Look through the file. Notice how we treat this data and how we write the fit function for a Gaussian. In particular, note the code used to apply our fit only to a portion of the data. Run the file and understand the output.

Exercise

After completing the whole notebook, be sure to save the final plot from Task 3. This will be the key plot you turn in for Example 4.

What to turn in

Once you complete all four exercises, please put the four final plots together into a single document, save it as a PDF, and upload it to Canvas. (Make sure your name appears in the text of the document somewhere.) We do not need to see (nor do we want to see) your raw python code.

If you'd like to do this using LaTeX, we have a barebones template here: Python Plots Template

To use this file with Overleaf, click on the New Project button and select Upload Project. Upload the zip file, and then use the upload file button (just below the menu in the top left) to upload your plots. Be sure to change the name to your name! Finally, navigate to each {figure} section, find the \includegraphics command, and change the filename in curly brackets to one of your figures.