Introduction to Python

Python is a high-level programming language - this means that you shouldn't have to worry about details like memory management - so you can focus on ideas and trying things out.

Many things should 'just work'. So why bother with Python? For me the main things are:

  • that it now has a rather large selection of libraries
  • large community that is always creating new ones
  • free and readily available.

So if you want to do something, there is a high chance that someone has already done most of the work for you;)

1. What is Python?

2. Why should a scientist use Python?

3. Getting started: four ways to use Python

What is Python?

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.

http://www.python.org/doc/essays/blurb/

What is Python

**Interpreted**No need for a compiling stage
**Object-oriented**Objects: complex data structures with attributes and methods
**High-level**Abstraction from the way the machine actually executes
**Dynamic**Variables can change meaning on-the-fly
**Built-in**Fewer external requirements
**Data structures**Ways of storing/manipulating data
**Script/Glue**Code that controls other programs
**Typing**The kind of variable (int, string, float)
**Syntax**Grammar which defines the language
**Library**reusable collection of code

History of Python

  • Started over Christmas break 1989, by Guido van Rossum
  • Development in the Early '90s
  • Guido is the "BDFL": the Benevolent Dictator for Life (Van Rossum announced on July 12, 2018, that he would be stepping down as BDFL of Python.)
...in December 1989, I was looking for a 'hobby' programming project that would keep me occupied during the week around Christmas. My office ... would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus).

some_text

Aside... the glory of Monte Python

Why should a Mathematician / Applied Mathematician / Scientist use Python?

C, C++, Fortran

Pros:

  • Great performance; lots of legacy scientific computing codes

Cons:

  • Syntax not optimized for casual programming
  • No interactive facilities
  • Difficult Visualization, text processing, etc.

Why should a Mathematician / Applied Mathematician / Scientist use Python?

IDL, Matlab, Mathematica

Pros:

  • Interactive with easy visualization tools
  • Extensive scientific libraries

Cons:

  • Costly and Proprietary
  • Unpleasant for large-scale computing & non-mathematical tasks

Why should a Mathematician / Applied Mathematician / Scientist use Python?

  • Clean (and optional) object-oriented model
  • Rich collection of built-in types, from simple to compound
  • Comprehensive standard library
  • Well-established 3rd-party packages (NumPy, SciPy, Matplotlib)
  • Easy wrapping of legacy code (C, C++, Fortran)
  • Python mastery is a marketable skill-set: Python Job Board

Rank of top languages on GitHub over time.

Ways to Use Python

for better (or worse) there are a number of ways to run python

  • The Python command-line interpreter
  • Editing Python (.py) files
  • The IPython command-line interpreter
  • The Jupyter notebook
  • Interpreted (via Javascript) in a browser

Notebooks

There are several ways to work with python - this is a Jupyter notebook.

The big advantage here is we can make nice, readable documents whilst figuring out how python works. Later on you will be expected to make your own notebooks, and them being readible is one of the things we're looking for.

  • Text can be easily entered using Markdown cell types - Markdown is a simple but quite effective way of typesetting, like a very simple $\LaTeX$.

  • A Markdown cheatsheet might be useful. Even better most $\LaTeX$ can be added by putting it within "\$s".

This presentation is actually a python notebook - in fact you can find it yourself on my Github page . This also contains some containers that will allow you to run python without any installation.

We can combine text and code almost at will.

In [14]:
#It is nice to have all plots appear within the notebook itself. 
# We can perform some 'magic' to make this happen.
%matplotlib inline

That was a code cell, where we can write python code, and a few special notebook functions.

Now figures and graphs will be rendered directly when called...we can grab some fancy examples from the website of one of the main libraries (modules) we will be using, matplotlib.

In [16]:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
        linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()
In [10]:
N = 200
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r ** 2 * np.random.rand(N)
ax = plt.subplot(111, polar=True)
plt.scatter(theta, r, c=theta, s=area, alpha=0.75);

or to go a bit over the top

In [17]:
import requests
# we grab our example file from the internet
r = requests.get('http://matplotlib.org/mpl_examples/pylab_examples/demo_agg_filter.py')
output = open('demo_agg_filter.py','wb')
output.write(r.content)
output.close()
# and we run it from within the notebook
%run demo_agg_filter.py

Don't try and understand these in detail, yet. Something a bit simpler is

Plot the curve $y=f(x)$, where

$$ f(x) = \sin (x),\quad x\in [-5, 5] $$
In [12]:
# Create values to plot
x = np.linspace(-5,5,50)
y = np.sin(x)
# Plot figure
plt.plot(x,y)
plt.show() # Not neccesary in notebooks, but neccesary on python scripts

what is going on? Time to get hands on...