Introduction to Python
Introduction to Python
Contents
1. Introduction ............................................................................................................................ 2
2. The Programming Platform .................................................................................................... 2
2.1 Installation............................................................................................................................. 2
2.2 Spyder the IDE ................................................................................................................. 3
2.3 Use of the Console Pane ................................................................................................... 4
Simple Problem Using Console Pane ...................................................................................... 5
2.4 Using the Editor Pane ...................................................................................................... 8
2.5 Writing Functions ............................................................................................................ 9
2.6 Writing Classes ................................................................................................................ 12
2.7 Lists and For Loops ......................................................................................................... 14
2.8 Plotting ............................................................................................................................ 15
2.9 Vectors and Arrays ..........................................................................................................18
2.10 Importing Own Modules ................................................................................................ 20
2.11 Importing Data From Excel ........................................................................................... 22
2.12 Fitting Data .................................................................................................................... 23
3. Citation .................................................................................................................................. 25
4. Conclusion ............................................................................................................................. 26
1
Introduction to Python for Scientific Computing
1. Introduction
This is a gentle introduction to a powerful tool for doing science. The main advantage of the
Python programming platform is its almost intuitive syntax (indeed some lines of code are
almost syntactically correct English!) and availability of a large number of libraries. The best
scientific groups around the word provide a Python interface for the code they write. But more
importantly, Python allows any scientist to unlock the power of the computer is a painless
manner. With Python, anybody can be a programmer, anybody can make animated, interactive
graphics and anybody can write code to interface with Excel.
2.1 Installation
To run the program, you need to have the Python interpreter installed on your computer.
To get the Python interpreter, the IDE and a host of other libraries (pre-written programs for
your convenience), we can download the installer from the internet (http://python-
xy.github.io/). The installer is called “Python(x,y)-2.7.3.1.exe”. It is already there on your
machine. The icon for the version 2.7.3.1 looks like Figure 1. It is a 500 MB file. You can copy it
to your pendrive and take it home to install on your own computers if you like. It runs in
Windows.
Once you have this on your machine, double-click it to run. You will soon see the screen in
Figure 2(a) which will invite you do execute a Custom install. Do not do this. From the drop
down menu choose Full install (see Figure 2(b)). Then click on the Next button and wait for
installation to complete. Should take about 5-10 minutes.
2
Introduction to Python for Scientific Computing
Figure 2: Wrong (a) and right (b) configurations for installing Python(x,y)
typing: “Spyder”. You will see an icon that looks like this . Click on it. Things will happen
and then you will get a screen that looks like Figure 3 (without the annotation, of course).
3
Introduction to Python for Scientific Computing
In the Console Pane, you can start programming right away. But you can execute only one line
at a time: so it quickly becomes a drag. To execute multiple lines automatically (as well as do
more fancy coding), you need to use the Editor Pane. But it is not interactive. The trick for good
fun programming is to use both. So let’s begin …
Notice the difference between integer division (where 2/3=0) and float division (2.0/3.0 =
0.666). Also notice that raising to powers is done in the C manner (2**3 = 8) and NOT in the
Excel Manner (2^3=1!). So can you use this Console Pane as a scientific calculator? Sure. But
you have to import the appropriate libraries.
So let’s do that. We would like to use trigonometric functions, exponentials and logarithms. All
of these are held in the Scientific Python library which is called “scipy”. Hence (see Figure 5) we
first import the Scientific Python library using the command “import scipy”. Now the variable
“scipy” will be used to access all the mathematical functions we need.
For instance, if we wish to find the value of 𝑒 −1, we would us the exp function in the scipy
module thus: scipy.exp(-1.0).
Similarly if we wanted to find the sine of a number (say 30.0), we would use the sin function in
the scipy module thus: scipy.sin(30.0). Note that the argument to the function is assumed to be
in radians, not degrees. If we wanted to find the sine of 30o, we would have to first convert it to
radians. We could simply multiply by 𝜋/180, but there is already an inbuilt function to save us
the trouble. We will nest the function scipy.radians within scipy.sin thus:
scipy.sin(scipy.radians(30.0)). Python supports nesting function.
There are a host of other mathematical functions that we can use. All the common
trigonometric, the exponential, the hypergeometric, logarithmic etc. They are all there.
4
Introduction to Python for Scientific Computing
Figure 5: Use of the Scientific Python Library. We first import the library using “import scipy” and then use the
functions in it e.g. exponentiation is accessed using scipy.exp.
Hence, the electricity generated per unit mirror area is given by: 𝑒𝑠𝑝 = 𝐼𝜂𝐷𝑁𝐼 𝜂𝑐𝑎𝑝 𝜂𝑐𝑜𝑛𝑣 .
5
Introduction to Python for Scientific Computing
Solar radiation corresponding to this has to be captured in 𝐷𝑠𝑢𝑛 time, hence the solar-field
𝐸𝑑𝑎𝑖𝑙𝑦
should be designed for a higher power production given by: 𝑃𝑠𝑢𝑛 = 𝐷𝑠𝑢𝑛
.
𝑃𝑠𝑢𝑛
Hence mirror area required is: 𝐴𝑚𝑖𝑟𝑟𝑜𝑟 = 𝑒𝑠𝑝
.
𝐴𝑚𝑖𝑟𝑟𝑜𝑟
Hence land area required is: 𝐴𝑙𝑎𝑛𝑑 = 𝜙𝑙𝑎𝑛𝑑
Hence cost of the project is: 𝐶𝑇 = 𝐴𝑚𝑖𝑟𝑟𝑜𝑟 × 𝐶𝑚𝑖𝑟𝑟𝑜𝑟 + 𝐴𝑙𝑎𝑛𝑑 × 𝐶𝑙𝑎𝑛𝑑 + 𝑃 × 𝐶𝑝𝑙𝑎𝑛𝑡 .
𝑅𝑜𝐼 𝐶𝑇
Hence 𝐶𝑒𝑙𝑒𝑐 = 100 × 𝐸 .
𝑦𝑒𝑎𝑟𝑙𝑦
The storage required is equivalent to they electricity generated over the non-sunny portions of
the day. Hence storage capacity required is: 𝐸𝑠𝑡𝑜𝑟𝑎𝑔𝑒 = 𝑃 × (𝐷𝑜𝑝 − 𝐷𝑠𝑢𝑛 ).
Now lets do everything in Python. See Figure 6. We have converted all units to SI: Hence J, W,
s etc. Notice that we can separate statements using semicolons (‘;’) and that Python ignores
anything on a line that follows a hash (‘#’).
You will also notice that Python has raised an error. That was because we forgot to put a ‘#’
before the ‘Rs/W’ and, of course, ‘Rs/W’ is a meaningless term (we have defined neither ‘Rs’ nor
‘W’).
The result of the calculations is that 𝐶𝑒𝑙𝑒𝑐 = 𝑅𝑠. 11.9/𝑘𝑊ℎ for the plant to get 10% return on
investment and the storage capacity necessary is 9 million kWh.
(Incidentally, if we add the cost of electricity storage (Rs. 24,000/kWh) the cost of storage alone
would be an unthinkable Rs 22,000 crores! The cost of the remaining plant is Rs 48,000 crores
i.e. electricity storage would increase plant costs by nearly 50%! This is why people prefer
thermal storage to electricity storage.)
Now, suppose we want to answer another problem: what is the cost of electricity if solar
insolation were 1000 𝑊/𝑚2 ? We would have to do the calculations all over again: it is very hard
to separate the parts that would change from the parts that would not.
That is a bore! Even worse, that is a recipe for making mistakes. It would be nice if we could go
up in the Console Pane and edit just one thing. Well, we can do that, but not in the Console
Pane. For that we have to write the code in the Editor Pane. So let’s do that …
6
Introduction to Python for Scientific Computing
Interestingly: You can access the python console (something like the console pane) very
quickly without using Spyder. Just open the command-prompt (press the ‘Windows’ button,
type ‘cmd’ and press Enter) and type ‘python’ at the prompt and press Enter. There is your
python Console ☺ (see Figure 7).
Figure 7: Quick access to the Python Console. Press ‘Windows Button’, type ‘cmd’, press Enter, type ‘python’, press
Enter. Compare this is just one more step than accessing the ‘Calculator’ option in Windows, but it gives you far
more calculating power ☺. Try to use it on a regular basis: why not?
7
Introduction to Python for Scientific Computing
Figure 8: The same calculation of section 2.3 except now in the Editor Pane.
You can see that it allows much better organization of the code. To run the code, press the
function key ‘F5’ on your keyboard. The first time you do this, you will see a dialog that lets you
specify how you want the code to run (see Figure 9). Make sure you choose to “Execute in a new
dedicated Python console”. This will open up a new tab in the console pane. You should also
check the option to “Interact with the Python console after execution” which makes it so that the
new tab that opens has all the code in the Editor pane pre-executed (see Figure 10).
8
Introduction to Python for Scientific Computing
Figure 9: Dialog that appears first time you run a program from the Editor Pane. Make sure to choose to “Execute
in a new dedicated Python console” and to “Interact with the Python console after execution”.
Now click the “Run” button. You should see that a new tab has opened in the Console Pane (see
Figure 10) which has the same name as the module we executed (‘solarthermal.py’). You can see
that this console has the line in the Editor Pane pre-executed.
Figure 10: A new tab opens in the Console Pane. The name of the tab is the same as that of the module which was
run. In this tab, all the lines in the Editor Pane are pre-executed. Hence you can access the variables in the Editor
pane e.g. simply type Celec_kWh and press Enter to get the value of that variable.
Now, if we wanted to find out the cost of electricity for an RoI of 20%, we could just change the
line 6 in the Editor Pane (see Figure 8) to “RoI = 20.0” and press ‘F5’ to run again. A dialog box
will open asking whether you want to kill and existing process: say ‘yes’. The ‘solarthermal.py’
tab in the console pane will refresh. Type ‘Celec_kWh’ and press Enter to get the new cost of
electricity. It will be Rs. 23.8.
9
Introduction to Python for Scientific Computing
Figure 11: Writing simple functions in Python. Note that the block of code describing the function is indented with
respect to the def i.e. it is shifted by 4 spaces or 1 tab. Python does not use ‘end’ statements of curly brackets ‘{}’ to
define a function block. Instead Python considers all line indented with respect to the function definition to be part
of the function. The first de-indent closes the function block.
Figure 11 shows five simple functions written in the Console Pane. Each function has a “def” in
front of its name. The name is immediately (no spaces) by an open parenthesis ‘(‘ which may or
may not be followed by a list of arguments separated by commas and terminated by a closed
parenthesis ‘)’ and a colon ‘:’. This tells the Python interpreter that a function of the given name
is being defined and it also tells how many arguments that function takes. What the interpreter
is supposed to do to execute that function is written in the indented block on subsequent lines.
Python uses indentation instead of ‘end’ statement or curly brackets (‘{}’) to delineate a function
block. An indentation means that the line is 4 spaces to the left of the ‘def’ line. The function
block often returns one or more values.
We can now modify the ‘solarthermal.py’ code to include a function to calculate Celec_kWh. We
will save it as a new file called ‘solarthermal_function.py’. The code is shown in Figure 12.
What we have done is put everything from unit conversion downwards into a function block.
The function name is Celec and it takes 13 arguments.
(Note: Notice that there is essentially no limit to the number of arguments that can be passed
to a function. Also, Python allows you to continue a list of arguments over several lines. )
Run it in the same manner as we did before (‘F5’ then choose the appropriate options as shown
in Figure 9 and then ‘Run’). Again, a new tab called ‘solarthermal_function.py’ appears in the
Console Pane (see Figure 13).
10
Introduction to Python for Scientific Computing
We can now call the function Celec as shown in Figure 13. We have called it repeatedly with
different values of RoI. This is a much quicker way than modifying the source code and running
each time: especially when the code can be complex and involve pre-processing.
Figure 13: The code of Figure 12 being run in the Console Pane. The function Celec is called repeatedly for RoI = 10,
20 and 15. It returns, respectively, the values 11.91666…, 23.8333.., 17.875.
11
Introduction to Python for Scientific Computing
Figure 14: Using classes to write more user friendly code. The power of this approach is illustrated in FIG
Here we define a class called ‘SolarThermal’. In like manner to the function definition, this
definition begins with the word ‘class’ followed by the name ‘SolarThermal’ followed
immediately by a colon ‘:’. There are no parentheses!
12
Introduction to Python for Scientific Computing
Everything that follows is indented with respect to the class definition line (line 1 in Figure 14).
We input the standard/default values of the various parameters as shown. Each parameter e.g.
I, Dop, RoI etc are now called attributes of the class SolarThermal.
We now write the definition of the Celec function: only now it is also indented wrt the class
definition. Hence Celec is also an attribute of this class: it is a method attribute.
Now when we write the Celec function, we have to pass just one argument. And that is the
keyword self. This argument self is implicit i.e. the user does not have to pass it. To access the
attributes of the class from within Celec, we use self e.g. to get the value of I we use self.I (see
line 13 in Figure 14). Everything else is as before. Now lets run this (‘F5’, select appropriate
options, press ‘Run’ button). A new tab called ‘solarthermal_classes.py’ opens in the Console
Pane.
Figure 15: Use of classes. Shown are three instances of class SolarThermal (st1, st2, st3) each with their RoI
attributes set to different values. Then the Celec method of each class is called and the results are seen. Then the I
attribute of st1 is modified and st1.Celec called again.
Use of our newly minted SolarThermal class is illustrated in Figure 15. To use a class, we have
to create an instance of that class. In Figure 15 we see three instances of class SolarThermal:
st1, st2, st3. Each instance starts life with the same value for all attributes. But then we can
modify the attributes of each class. Hence, we have changed the RoI value of each class to 10.0,
15.0 and 20.0 for st1, st2 and st3 respectively. Now when we call the method attribute Celec for
each instance, we get different results (11.91666…, 17.875, 23.833… respectively).
We can change another attribute e.g. we have changed the I attribute of st1 to 1000.0 and called
st1.Celec() to yield 9.6833… .
Clearly this is a far more user friendly way of programming. Just as an example of its power,
suppose you want to add a refinement to the model e.g. cost of thermal storage say, you would
need several more parameters to be passed to the function in Figure 13 by the user i.e. you will
have to go back and change several lines of code every time you decide to refine your model.
However, with the use of classes (Figure 15) the user interface remains exactly the same. The
code is now truly modular.
13
Introduction to Python for Scientific Computing
The use of a for loop in Python is slightly different from other common languages. The for loop
iterates over elements of a list. Hence in Figure 16, each element of list_of_RoI is successively
stored in the variable RoI. In the for block, the value of the variable RoI is assigned to the RoI
attribute of the class instance st1. Then the Celec method attribute of st1 is called and the value
returned assigned to the variable celec. Finally RoI and celec are printed out to the screen and
the next element of list_of_RoI is assigned to the variable RoI and the process is repeated until
all elements of the list are used up. Very simple and convenient.
But there is a problem: we can’t do anything with the values of celec. We could copy them and
paste them in Excel (for instance) and plot them etc. But that is tedious. And unnecessary.
Python provides a simple way of making another list of values of celec. Figure 17 shows a way of
creating an empty list (just ‘[]’) and adding element after element to it. Two lists can be
concatenated simply by adding them i.e. [1,2,4,7] + [2,3,7,1] will result in [1,2,34,7,2,3,7,1].
14
Introduction to Python for Scientific Computing
In Figure 18 we see an example of nested for loops (one for loop inside the block of another) as
well as a list of lists. This is a very powerful feature of Python. It enables us to handle
information very efficiently. It also has other benefits, which we will see.
2.8 Plotting
A very useful feature for scientific analysis is the ability to plot data. Excel (well) excels at allows
users to quickly plot and analyse data. Python does the same. In some ways, it is actually easier
15
Introduction to Python for Scientific Computing
to plot data in Python than it is in Excel. And we shall soon see that it need not be either-or.
Our favourite word is both!
So what does it take to plot something in Python. Well, first we need something to plot: that is a
set of x and y coordinates with a one-to-one correspondence i.e. there must be exactly the same
number of x coordinates as there are y coordinates and both sets must be ordered. In other
words, we need two lists: a list of x coordinates and a list of y coordinates.
Let’s plot the sine function between 0 and 2𝜋 (both inclusive) in 20 points. So the points in the
2𝜋
list of x coordinates are given by: 19 𝑖 where 𝑖 = 0,1,2, … ,19. Hence the points in the list of y
2𝜋
coordinates are given by: sin ( 19 𝑖).
Now that we have our lists, we need to put them in a picture. This would have normally been
very heavy work, but Python has a fully equipped library called Matplotlib. We will use the
pyplot sub-module of the matplotlib library. The code is shown in Figure 19.
You will see a new window has opened on your screen (it might be minimized). Expand it and
you should see something like Figure 20.
Now add the lines shown in Figure 21 and you should get Figure 22.
16
Introduction to Python for Scientific Computing
17
Introduction to Python for Scientific Computing
Figure 23: Casting a list into an array and the power of using arrays.
Figure 23 shows how to cast a list into an array and the power of using arrays. Mathematical
operation performed on the array as a whole are broadcast to each element of the array. Hence
we don’t need for loops.
The Figure 21 shows a quick and elegant way of plotting the sine function between 0 and 2𝜋.
The resulting plot is shown in Figure 25.
Note the use of the scipy.linspace function which returns an evenly spaced grid of points
between two end points.
Figure 26 shows some other standard array operations that are available to Python. There are
many many more!
18
Introduction to Python for Scientific Computing
Figure 24: Using the power of arrays to greatly simplify the code of Figure 21
19
Introduction to Python for Scientific Computing
20
Introduction to Python for Scientific Computing
21
Introduction to Python for Scientific Computing
Figure 29: Data in Excel worksheet called ‘Data’ in workbook called ‘Data.xlsx’.
The Figure 30 shows how to get data from the Excel sheet of Figure 29. The code is stored in the
file ‘exceldataimport.py’. Line 1 imports a special library called win32com.client using which we
open the Excel application object as xl (line 5) and hence the workbook called ‘Data.xlsx’ (line 6)
as wb. From wb we get the sheet ‘Data’ as sheet (line 7). The function getdata converts data in
a column in excel into a vector in Python. The code also plots the data.
Run this code to get the graph shown in Figure 31.
22
Introduction to Python for Scientific Computing
Figure 30: Getting data from the Excel sheet shown in Figure 29
23
Introduction to Python for Scientific Computing
Figure 32: Code for fitting data shown in Figure 29. The result of running this appears in Figure 33.
Let’s unpack the code in Figure 32 a bit. Upto line 13 we have already seen in Figure 30. So we
have our x and y arrays. Now we need a likely curve to fit these to. From the nature of the graph
shown in Figure 31, we can hazard that the curve is a hyperbolic tangent i.e.
𝑦 = 𝐴 + 𝐵 × tanh(𝐶(𝑥 − 𝐷))
24
Introduction to Python for Scientific Computing
3. Citation
If you use Python in your research, please cite the following somewhere in your paper:
For Scientific Python (scipy): Oliphant, T. E. “Python for Scientific Computing.” Comput. Sci.
Eng. 9, 10–20 (2007).
25
Introduction to Python for Scientific Computing
4. Conclusion
There is lots more that Python can do. Python has modules for differential equation solution,
data-analysis, machine learning, signal processing, wavelet transforms, computer vision, 3D
visualization, efficient data storage and retrieval, web development, game development and any
number of other fun and useful features. And more are being added every day.
“This is not the end. This is not even the beginning of the end. This is the end
of the beginning”
◼ Winston Churchill
26