Python for Physicists

Key Points

Running Python
  • Python programs are plain text files.

  • Use the Jupyter Notebook for editing and running Python.

  • Use the keyboard and mouse to select and edit cells.

  • The Notebook will turn Markdown into pretty-printed documentation.

Variables and Assignment
  • Use variables to store values.

  • Use print to display values.

  • Variables persist between cells.

  • Variables must be created before they are used.

  • Variables can be used in calculations.

  • Python is case-sensitive.

  • Use meaningful variable names.

Data Types and Type Conversion
  • Every value has a type.

  • Use the built-in function type to find the type of a value.

  • Types control what operations can be done on values.

  • Strings can be added and multiplied.

  • You can convert numbers to strings or vice versa when operating on them.

  • You can mix integers and floats freely in operations.

  • Variables only change value when something is assigned to them.

Built-in Functions, Help and Errors
  • A function may take zero or more arguments.

  • Commonly-used built-in functions include max, min, and round.

  • Functions may only work for certain (combinations of) arguments.

  • Functions may have default values for some arguments.

  • Use the built-in function help to get help for a function.

  • The Jupyter Notebook has two ways to get help.

  • Every function returns something.

  • Python reports a syntax error when it can’t understand the source of a program.

  • Python reports a runtime error when something goes wrong while a program is executing.

  • Fix syntax errors by reading the source code, and runtime errors by tracing the program’s execution.

Lists
  • A list stores many values in a single structure.

  • Use the built-in function len to find the length of a list.

  • Use an item’s index to fetch it from a list.

  • Use slicing to fetch multiple items from a list.

  • Lists’ values can be replaced by assigning to them.

  • Appending items to a list lengthens it.

  • Use del to remove items from a list entirely.

  • The empty list contains no values.

  • Lists may contain values of different types.

  • Character strings can be indexed and sliced like lists.

  • Character strings are immutable.

  • Indexing beyond the end of the collection is an error.

For Loops
  • A for loop executes commands once for each value in a collection.

  • The first line of the for loop must end with a colon, and the body must be indented.

  • Indentation is always meaningful in Python.

  • A for loop is made up of a collection, a loop variable, and a body.

  • Loop variables can be called anything (but it is strongly advised to have a meaningful name to the looping variable).

  • The body of a loop can contain many statements.

  • Use range to iterate over a sequence of numbers.

  • The Accumulator pattern turns many values into one.

Conditionals
  • Use if statements to control whether or not a block of code is executed.

  • Conditionals are often used inside loops.

  • Use else to execute a block of code when an if condition is not true.

  • Use elif to specify additional tests.

  • Conditions are tested once, in order.

  • Create a table showing variables’ values to trace a program’s execution.

Writing Functions
  • Break programs down into functions to make them easier to understand.

  • Define a function using def with a name, parameters, and a block of code.

  • Defining a function does not run it.

  • Arguments in call are matched to parameters in definition.

  • Functions may return a result to their caller using return.

Variable Scope
  • The scope of a variable is the part of a program that can ‘see’ that variable.

Libraries
  • Most of the power of a programming language is in its libraries.

  • A program must import a library module in order to use it.

  • Use help to learn about the contents of a library module.

  • Import specific items from a library to shorten programs.

  • Create an alias for a library when importing it to shorten programs.

Storing data in Numpy arrays
  • Use the NumPy library to work with numerical data in Python

  • The loadtxt function is used to read in .csv data

  • Built-in Python functions can be used to read file headings

  • To save the data to memory we can assign it to a variable

  • An array is a central data structure of the NumPy library

  • Extra information about an array are stored as attributes

  • The savetxt function is used to write data to a file

  • numpy.linspace generates evenly spaced numbers over a given interval

  • The enumerate function allows us to have an automatic counter within a for loop

Retrieving data from Numpy arrays
  • All the indexing and slicing that we’ve used on lists and strings also works on arrays.

  • Use array[x, y] to select a single element from a 2D array

  • Use data[:,x] to select a column

Visualizing data with Matplotlib
  • Use the pyplot library from matplotlib for creating simple visualizations

  • Basic plots can be generated quickly with matplotlib

  • To group similar plots we use a figure and subplots

  • There are many ways to plot and customise plots using matplotlib

Analysing data using Numpy
  • There are often multiple ways to approach a programming task

  • Fit a polynomial function to data using the numpy.polyfit function

  • Use the scipy.constants module for physical constants

  • Numpy simplifies and speeds up array operations

  • There are Numpy functions for statistical analysis

  • Numpy functions can be applied across an axis

Code Quality
  • Follow standard Python style in your code.

  • Use assertions to check for internal errors

  • Use docstrings to provide online help.

  • Use __version__ to increase code reproducibility.

Running your Code as a Python Script
  • Copy/paste or use the %%writefile myfile.py notebook magic to export a single cell

  • Use jupyter nbconvert --to script my_notebook.ipynb to export a complete notebook

  • Use python3 script_name.py to run a script from the terminal

  • Import the sys module and use sys.argv to take a command line argument

Wrap-Up
  • Python supports a large community within research.