PHY224 Python Review: Reference

Key Points

Running and Quitting
  • Python programs are plain text files.

  • Use the Jupyter Notebook for editing and running Python.

  • The Notebook has Command and Edit modes.

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

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

  • Markdown does most of what HTML does.

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.

  • Use an index to get a single character from a string.

  • Use a slice to get a substring.

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

  • 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.

  • Strings have a length (but numbers don’t).

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

  • Can mix integers and floats freely in operations.

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

Built-in Functions and Help
  • Use comments to add documentation to programs.

  • 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.

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.

Numpy and Scipy
  • Use the numpy library to get basic statistics out of tabular data.

  • Print numpy arrays.

  • Use mean, sum, std to get summary statistics.

  • Add numpy arrays together.

  • Study the scipy website

  • Use scipy to integrate tabular data.

Reading Tabular Data into arrays
  • Use numpy.loadtxt library to load tabular data.

  • Use numpy.savetxt library to save tabular data.

  • Use delimiters to make your text file cleaner.

  • Use comments in your file to describe the contents.

Plotting
  • matplotlib is the most widely used scientific plotting library in Python.

  • Plot data directly from a Pandas dataframe.

  • Select and transform data, then plot it.

  • Many styles of plot are available: see the Python Graph Gallery for more options.

  • Can plot many sets of data together.

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

  • Use an item’s index to fetch it 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 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.

Looping Over Data Sets
  • Use a for loop to process files given a list of their names.

  • Use glob.glob to find sets of files whose names match a pattern.

  • Use glob and for to process batches of files.

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.

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.

Programming Style
  • Follow standard Python style in your code.

  • Use docstrings to provide online help.

Fitting data to models
  • scipy provides tools and functions to fit models to data.

  • Use curve_fit to fit linear and non-linear models to experimental data

  • Use appropriate errors in the sigma keyword to get a better estimate of parameter errors.

  • Check the fit using a plot if possible

  • Check the χ2 value to compare the fit against the errors in the measurements.

  • Non linear models can be fitted, but may need an initial esimate of the parameters.

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

Reference

Running and Quitting

Variables and Assignment

Data Types and Type Conversion

Built-in Functions and Help

Libraries

Reading Tabular Data into DataFrames

Pandas DataFrames

Plotting

import matplotlib.puplot as plot
plt.plot(time, position, label='label')
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.legend()

Lists

For Loops

for number in range(0,5):
    print(number)

Conditionals

for m in [3, 6, 7, 2, 8]:
    if m > 5:
        print(m, 'is large')
    elif m == 5:
        print(m, 'is 5')
    else:
        print(m, 'is small')

Looping Over Data Sets

for filename in glob.glob(*.txt):
  data = pd.read_csv(filename)

Writing Functions

def add_numbers(a, b):
    result = a + b
    return result

add_numbers(1, 4)

Variable Scope

Programming Style

Glossary

Arguments
Values passed to functions.
Array
A container holding elements of the same type.
Boolean
An object composed of True and False.
DataFrame
The way Pandas represents a table; a collection of series.
Element
An item in a list or an array. For a string, these are the individual characters.
Function
A block of code that can be called and re-used elsewhere.
Global variable
A variable defined outside of a function that can be used anywhere.
Index
The position of a given element.
Jupyter Notebook
Interactive coding environment allowing a combination of code and markdown.
Library
A collection of files containing functions used by other programs.
Local Variable
A variable defined inside of a function that can only be used inside of that function.
Mask
A boolean object used for selecting data from another object.
Method
An action tied to a particular object. Called by using object.method.
Modules
The files within a library containing functions used by other programs.
Parameters
Variables used when executing a function.
Series
A Pandas data structure to represent a column.
Substring
A part of a string.
Variables
Names for values.