Python

Python is a high level scripting and programming language that is commonly used in computational science. As a high level language, like Matlab and Mathematica, it can solve many problems with just a few lines of code. The main advantage Python has over other high level languages is that it is completely free.

Installation

To get started with Python one first needs to make sure it is installed on your machine. Python often comes preinstalled for many operating systems; however, since some parts of the operating system may use python for some tasks, it is usually wise to install a separate version for research use. The easiest way to install python for scientific use is to install Anaconda python. You can either install Anaconda python with all of the extra packages, or you can use the mini-conda installer to just install python and then install any additional packages you may want using the conda package manager.

Packages

One of the things that makes python so powerful is that many thousands of packages have been developed to perform specific tasks. The easiest way to install packages is to use a package management system like conda or pip.
The Anaconda python distribution will start you with dozens of packages preinstalled. You can use conda or pip to see which packages are installed. Some of the packages commonly used for various aspects of scientific computing are:

  • numpy
  • scipy
  • matplotlib (for plotting)
  • astropy  (for astronomy)
  • yt (for visualization)
  • argparse (for passing arguments on the command line)

Data Types

Python starts with a number of built in data types. These are;

  1. boolean, ints, floats, complex
  2. strings, bytes, lists, tuples
  3. dictionaires

The first four of these types are used to hold a number. The second four types hold a sequence of things. The final type, dictionaries, hold a sequence of mappings between things. You can check the type of a variable using the function type(). There is a special value None which all data types can be set to that means they haven’t been set to anything.  Other packages can add other types to python as defined in those packages.  The numpy package adds the data type ndarray, called a numpy array which is very useful for scientific calculations. While this is a sequence of values like a list it has extra methods associated with it and will behave differently under some operations.

File Input/Output

Python can print to the command line with the print command

print("Hello World")

Note that the parenthesis are not needed in Python 2 but are need in Python 3. One can print a variable by passing it without quotation marks.

first="Hello"
second="World"
print(first,second)

One can use Python’s string formatting to control how variables will be printed. The basic idea is that curly brackets stand for where a variable will be placed in a string. At the end of the string one uses .format() and passes the variables one wants to print. Inside the curly brackets one can give a formatting code that determines how the variable will appear. The list of formatting codes can be found here.  For example if one wanted to print “3.50 dived by 7 is 0.50” one could use the following code:

a=3.5;b=7
print("{:4.2f} divided by {:1n} is {:3.2f}".format(a,b,a/b))

In order to read or write to a file you’ll need to open the file with Python’s open function

 f=open(filename,mode='r')

The argument given is the filename. Mode refers to how the file is treated, ‘r’ means it will be read as opposed to written to. The list of possible modes can be found here.
To read in the text of your file there are a few options

all_text=f.read() #returns the whole file as a string
one_line=f.readline() # returns one line of the file as a string
all_lines=f.readlines() # returns a list of all lines of the file

Note that files are always read in as strings, so if you want to read in numbers you’ll have to convert your strings to numbers. Here is an example for a file that contains three space separated numbers per line.

x=[];y=[];z=[]
with open(filename,mode='r') as f:
   for line in f.readlines(): #will stop when no more lines
       numbers=line.split() #returns a list, split on whitespaces
       x.append(float(numbers[0]))
       y.append(float(numbers[1]))
       z.append(float(numbers[2]))

Writing to a file is just like printing except you use the write command

var='Jane'
f=open(filename,mode='w')
f.write("Hello World from {}".format(var))

Comments are closed.