5-minute introduction to Python
From PIMC++
Contents |
[edit] Background
Python is a relatively new programming language designed to be simple, yet powerful. As an interpreted language, it allows one to rapidly test out ideas and build sophisticated interfaces with relatively little code. The downside of an interpreter is that it can be quite slow in comparison to compiled languages, as we shall see in the tutorials on VMC and PIMC.
[edit] Language essentials
Python can be used interactively or in scripts executable from the command line. To start the interactive interpreter, simply type python code>. It will give you a >>> code> prompt.
To execute a python script from the command line, you can give python code> the name of your script as a command-line argument, as in python myscript.py code>.
Alternatively, in Linux or Unix, you can simply add a shell descriptor at the top of you code,
#!/bin/env python a = ['1', '2', '3'] print a
Then, if you make the script executable with chmod u+x myscript.py code>, you can simply execute myscript code> without explicitly invoking python.
[edit] Modules
In Python, you can organize code into modules, which are similar to C++ libraries for Fortran90 modules. To use a module, you use the import code> command. There are several variants. To use everything available in a module, we do
import pylabThis will make pylab code>'s functions available for use as,
import pylab x = [1, 2, 3, 4] y = [4, 5, 6, 7] pylab.plot(x,y) pylab.show()
In the following labs, we will use a module called pylab for plotting.
You can avoid always typing the pylab. code> by doing instead,
from pylab import *
but this can sometime lead to conflicts when more than one module defines a function with the same name.
[edit] Tuples, lists, and arrays
A tuple is an ordered, immutable group of python objects of arbitrary type. By immutable, we mean that it cannot be changed once it has been created. In Python, you create a tuple of objects by using ()'s, e.g.
>>> name = "Harry Smith" >>> id_num = 12345 >>> data = (name, id_num)
The elements of a tuple can be indexed with [ ]'s. Indices start from 0, as in C.
>>> print a[0] Harry
Lists are similar to tuples, but can be changed. They are created using []'s.
>>> fruits = ['apple', 'pear', 'orange'] >>> fruits.append('grape') >>> print fruits ['apple', 'pear', 'orange', 'grape']
Lists are indexed in the same way as tuples, but can be changed, while tuples cannot.
>>> aList = ['a', 'b'] >>> aList[0] = 1 >>> print aList [1, 'b'] >>> aTuple = ('a', 'b') >>> aTuple[0] = 1 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment
[edit] Nesting
Lists and tuples can be nested. As an example
>>> b = [ [1, 2], [3, 4] ] >>> print b[0][1] 2
[edit] Numpy Arrays
numpy is a Python module for efficient handling of single and multdimensional arrays. There now exist good tutorials for using it. Here we will introduce some very basic points:
- You can import it with
import numpy code>. - Declaring an array:
-
myArray=numpy.zeros(4,float) code>generates a 1d array of size 4 filled with floats of zeros. -
myArray=numpy.zeros((4,3),float) code>generates a 2d array of size 4 x 3 filled with floats of zeros. -
myArray=numpy.array([[0.3,1.2,2.3],[0.2,0.1,1.5]]) code>will produce a 2d numpy array initialized with these values
-
- Accessing an element:
-
myArray[1] code>accesses the 1'st element of the array -
myArray[0,2] code>access the 0 x 2 element of a 2d array
-
- Slicing:
-
myArray[1:4] code>returns a new array with the elements myArray[1], myArray[2] and myArray[3] (NOT myArray[4]))
-
- Calling
numpy.shape(myArray) code>will return a tuple that specifies the lengths of each size of the array (i.e. numpy.shape(myArray) would return (3,2) if it is a 2d array with sides 3 x 2 )
[edit] Comments
Comments are denoted by the # sign, as in other scripting languages.
[edit] Indentation
In Python, whitespace is significant. Rather than using begin and end blocks, or {}'s, Python's blocks are denoted by indentation alone. Consider the following statement
if (x < 0.0): x = 0.0 print "Warning: encountered negative value." print "done"
The two lines following the if statement will be executed if x is negative. Because they have the same indentation, they belong to the if block. The last line does not belong to the if block and will always be executed.
[edit] Conditionals
Conditionals are done as in many languages with "if" statements:
if (a < 0.0): n1 = n1 + 1 elif (a < 1.0): n2 = n2 + 1 else: n3 = n3 + 1
Don't forget the : at the end of each statement.
Comparison operators include == (equality), != (inequality), <, and >. These result in the built-in boolean values True or False. These can be combined with boolean operators and and or or negated with not.
[edit] Loops
The most common loop used in scientific program in the for loop. In Python, this is usually accomplished with the in construct:
aList = [1, 2, 3, 4, 5] for a in aList: print a
results in
1 2 3 4 5
To avoid typing out long lists, we can use the range function:
for a in range(1,6): print a
does the same thing as above. range includes the first number, but not the last. To count by twos:
for a in range(0,11,2): print a
The while loop continues as long as its conditional statement is true:
while (n < 4): n = n + 1
[edit] Function definitions
Functions are defined with the def language construct:
def myfunc(x): y = x + 3 return y*y
The function body is delimited by the indentation block as conditionals and loops. The return statement specifies the value returned to the calling code. Functions can have any number of parameters and type specification is not necessary. Python also supports named function parameters, but we will not need these for these tutorials.
[edit] Classes
In object-oriented programming, data is grouped together with functions that act upon that data. These groups are called objects, and the structure that defines them are called classes. In Python, a components of a class are specified in a class definition , which is indicated by the class code> keyword.
class Coulomb: def __init__(self): self.Z1 = 1.0 self.Z2 = 1.0 def SetCharge (self, z1, z2): self.Z1 = z1 self.Z2 = z2 def V(self, r): return (self.Z1*self.Z2/r) def dVdr(self, r): return (-self.Z1*self.Z2/(r*r))
the class definition essentially defines a new data type. To create a new variable of that type, we simply call the class's constructor function.
electron_proton = Coulomb() electron_proton.SetCharge (1.0, -1.0) electron_electron = Coulomb() electron_electron.SetCharge (1.0, 1.0) print electron_proton.V(10.0) print electron_electron.V(10.0)
Above we have created two instances of class Coulomb() code>:
one for the electron-proton interaction and one for the proton-proton interaction. After creating the objects, we set their attributes with a call to their SetCharge code> function. Note that in the class definition, the first parameter to each member function is self code>. The parameter is implicity passed to the function by a call such as electron_proton.V(10.0) code>.
Finally, we can compute the potentials with calls to V code>.
The objects were created with calls to the special function Coulomb() code>, which is created by the class definition.
The call to the Coulomb() code> invokes the class's __init__ code> function.
