NGCM Summer Academy 2017:

Intermediate Python

Lucy Upton and Ryan Pepper

lru1e15@soton.ac.uk

ryan.pepper@soton.ac.uk

Introduction

Prerequisites

  • Python $>=$ 3.4
  • Jupyter (Notebook)
  • Numpy module
  • Matplotlib module

If you are following this course and do not know how to obtain the above requirements, see Setup Instructions.

Material

Objectives

  • 2 sessions:
    • 10:00-11:00 Basics
    • 11:30-13:00 Object Oriented Programming (OOP)

Material Outline

Basics Revision

  • Lists
  • Tuples
  • Numpy arrays
  • Dictionaries
  • For loops
  • Functions
  • Matplotlib (Plotting)

Object Oriented Programming

  • Classes
  • Initialization and __init__, self
  • Encapsulation
  • Inheritance
  • Magic operators

Hello World for Jupyter Notebook

  1. In command line, type: jupyter notebook &
  2. Click: New, Python 3
  3. Type: print(Hello world!)
  4. Press: shift+enter

Data Storage

Lists

Lists are:

  • Defined with square brackets
  • Mutable
  • Able to have mixed data types
  • Indexed
  • Able to be sliced
  • Useful for sequential data

Example: Indexing & Slicing

Example: Mutable & Mixed Data Types

Tuples

Tuples are:

  • Defined with parenthesis
  • Immutable
  • Able to have mixed data types
  • Indexed
  • Able to be sliced
  • Useful for structured data

Example: Immutable

Why use tuples?

  1. Tuples are faster than lists as they use fixed memory.
  2. Tuples are useful good for structured data as they keep the same structure (e.g. length) indexing

Example: Tuples are faster

Example: Python is Call by value

Numpy Arrays

Numpy Arrays are not included by default.

To use numpy array, you need to include the following line of code:

import numpy as np

For a tutorial on modules, visit: https://docs.python.org/3/tutorial/modules.html

Numpy arrays are are:

  • Defined using np.array()
  • Mutable
  • Indexed
  • NOT able to have mixed data types - numpy arrays are homogeneous and contain elements of the same dtype.

    dtypes are data type objects used within numpy. There are built in dtypes representing

     - np.int8, np.int16, np.int32, np.uint8, np.float32, np.bool_, np.complex_, etc...
    

    Also you can create a dtype to suit your needs, e.g. structures of fields of the built in dtypes. For more information, see the documentation: https://docs.scipy.org/doc/numpy-1.12.0/reference/arrays.dtypes.html

  • Useful for linear algebra - mathematical operations act quickly on numpy arrays
  • Allow integration between C/C++ and Fortran

See user guide: https://docs.scipy.org/doc/numpy-dev/user/

See other documentation: https://docs.scipy.org/doc/

If you're a MATLAB user, you may find this page useful, which sets out the difference between MATLAB and NumPy syntax:

https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html

Example: How to use

There are many mathematical functions that can be applied to arrays which come built into the numpy package.

A list of mathematical functions available within numpy is found here: https://docs.scipy.org/doc/numpy-1.12.0/reference/routines.math.html

Example: Useful functions

Numpy arrays are also useful for working with matrices and other 2d arrays and displaying these.

Example: 2d Arrays

Numpy can also be used to create numpy arrays from data in a file using np.loadtxt(). The file must contain data in rows with equal numbers of entries.

Example: Loading data with np.loadtxt()

Dictionaries

Dictionaries are:

  • Groups of key-value pairs
  • Defined with curly braces or with dict() on some list
  • Mutable - you can add pairs to a dictionary after defining it
  • Ordering follows hash table rules
  • Able to have mixed data types

Example: How to use

Example: Mutable

Example: Iteration - we will see for loops here!

Functions

  • def followed by function name and parameters in a parenthesis
  • return output_var(s) ends the function
  • Args parsed by assignment: Mutability dictates whether the function can update args directly

Example: Simple function

Example: Arguments and mutability

Plotting

Matplotlib

The most common plotting module is matplotlib.

It's simple to use but can be also be used to produce publication quality plots.

It can be used with LaTex formatting.

The best way to understand is to see some examples:

Example: Simple Plot

Example: Labels, ticks and other appenditories

For a tutorial on matplotlib.pyplot, try: https://matplotlib.org/users/pyplot_tutorial.html

This has examples of line graphs, scatter graphs and histograms.

For more details and examples, visit: https://matplotlib.org/contents.html

Reading from and writing to files

The function open() can be used to read from, write to or append a file. It creates a file object

It takes two arguments, the filename and the mode indicating what you want to do with the file:

  • 'r' for reading (this is the default)
  • 'r+' for reading and writing
  • 'w' for writing
  • 'a' for appending

Once a file object is created, you can then use many functions including the following:

  • read()
  • readline()
  • readlines()
  • list()
  • iterate over lines
  • write()

For a tutorial on input and output, visit: https://docs.python.org/3/tutorial/inputoutput.html

Examples:

Other common modules

So far we have imported numpy and matplotlib. In python there is lots of pre-written code to take advantage of, usually by importing modules.

Other common modules you may come across are :

- math: for common maths functions and numerical constants
- scipy: a library of algorithms and mathematical tools.
         For example there are built in algorithms for minimising/maximising functions

For a tutorial on modules, visit: https://docs.python.org/3/tutorial/modules.html