Python
Python is an object oriented and scripting language, developed in late 90s, whereas C, Fortran77 etc are
procedural languages, making use of functions.
It comes as an open source software and is included in various linux/unix distributions
like ubuntu, fedora, open suse etc.
An object in OOP (programming) is a state, well defined behaviour and an unique identity.
A class represents a set of objects having comman structure and comman behaviour, i.e.
class = state+ behavior.
Law of OOP is that data is private i.e. hidden from outside world. Further encapsulation and
inheritance (or multiple inheritance) is also there.
What does encapsulation do ? It hides the details of implementation of an object/class.
Inheritance makes use of the already available code, so no need to write a new code from scratch.
In inheritance base class (parent class) and derived class (child class) terminology is used.
Book suggestion: The book "A Primer on Scientific Programming with Python" by Prof. H. P. Langtangen.
Example1a: Class/object/self :
#!/usr/bin/python
class Computer:
'Common base class for all computers <-- a documentation string'
comp_count = 0
def __init__(self, os, cost):
self.os = os
self.cost = cost
Computer.comp_count += 1
def How_many_computer(self):
print "Total no. of computers %d" % Computer.comp_count
def Display_info(self):
print "os : ", self.os, ", cost: ", self.cost
"creation of first object of computer class"
comp1 = Computer("Windows", 40000 )
"creation of second object of computer class"
comp2 = Computer("Linux", 35000)
comp1.Display_info()
comp2.Display_info()
print "Total computers = %d" % Computer.comp_count
print "1. variable 'comp_count' is a class variable whose value is shared among all instances of this \
class and can be accessed as 'Computer.comp_count' from inside the class or outside the class.\n"
print "2. The first method __init__() is a special method which is called class constructor (or initialization method) \
which is called by Python when we create a new instance of this class i.e. Computer. \n "
print "3. Also to other methods, first argument by convention is 'self'.\n"
print "... job ends.\n"
output:
os : Windows , cost: 40000
os : Linux , cost: 35000
Total computers = 2
1. variable 'comp_count' is a class variable whose value is shared among all instances of this class and can be accessed as 'Computer.comp_count' from inside the class or outside the class.
2. The first method __init__() is a special method which is called class constructor (or initialization method) which is called by Python when we create a new instance of this class i.e. Computer.
3. Also to other methods, first argument by convention is 'self'.
... job ends.
Example 1b: Class/object/self :
#!/usr/bin/python
#class declaration
class atom():
atomic_no=11.
charge=1
# inside the class, function is called method.
def myname(self,name): # self is temporary place for the object.
self.name=name
def bye(self):
print "just basics, %s" %self.name
print "\nIn the class 'atom', i created two varibale, one flaot, one int and two methods."
print "\nHow to access the data and methods inside the class atom.? \n"
atom1=atom() # atom1 is the created object
print "atom1.atomic_no = %3.0f" % atom1.atomic_no # accessing the float type data of object atom1
print "atom1.charge = %1d" % atom1.charge # accessing the int type data of object atom1
atom1.myname(' Mr. Sonu Kumar') ## accessing the method of object atom1
atom1.bye()
output:
In the class 'atom', i created two varibale, one flaot, one int and two methods.
How to access the data and methods inside the class atom.?
atom1.atomic_no = 11.0
atom1.charge = 1
just basics, Mr. Sonu Kumar
Excercise 2: script to convert hexagonal unit cell parameters to rhombohedral
unit cell.
#!/usr/bin/python
import math
import datetime
a_R=6.0305
deg=26.067
#a_R = array([5, 5])
#deg = array([26.,27.])
alpha=math.radians(deg)
a_H=2*a_R*math.sin(alpha/2)
print "a_H = %0.5f" % a_H
equation_here=9*a_R**2-3*a_H**2
c_H=math.sqrt(equation_here)
print "c_H = %0.5f" % c_H
ratio_c_by_a=c_H/a_H
print "c_H/a_H = %0.5f" % ratio_c_by_a
now = datetime.datetime.now()
print "Current date and time:" # using str method of datetime object:"
print str(now)
print "...job done."
Output :
a_H = 2.72001
c_H = 17.46731
c_H/a_H = 6.42179
Current date and time:
2012-08-02 12:04:46.697992
...job done.
Comments about excercise 1: We can use also "list" statament for the unit cell
parameters a_R and deg.
====================================================================
BASICS of PYTHON:
====================================================================
Variables: interger, float type. On python prompt, variables are typed dynamically, like
>>> x=2 #integer type
>>> y=2. # float type variable
>>> z=2.*x # float type
Strings: is a sequence of characters within single or double quotes. Strings are
immutable entities, i.e. they cann't be changes by the assignment statement. They are
concatenated by + operator and sliced by : operator.
e.g.
>>> mystring= 'hi brother'
>>> yourstring='hello Mr.'
>>> ourstring=mystring + ' ' + yourstring
>>> print ourstring
hi brother hello Mr.
Tuples: is a sequence of arbitrary entities (string, numeric data etc. ) separated by
commas and enclosed in parenthesis, ( ).
e.g.
>>> a=(1, 'mohan', 'samual')
>>>number, name1, name2 = a # assigning elements of a to number, name1, name2
>>> print number
1
>>> print name2
samual
>>> print a[0:1]
1
Lists : it resemble with the tuples. It is recognized by square brackkets and is mutable.
e.g.
>>> density_list = [1.1, 0.9999, 1.0001]
>>>density_list.append(1.000)
>>> print density_list
[1.1, 0.9999, 1.0001, 1.000]
>>>c=[1, 2, 3]
>>> c[0:2]=[5, 6]
>>> print c
[5, 6, 3]
>>> copy_of_c=c
>>> print copy_of_c
[5, 6, 3]
>>> len (c)
3
>>> a=[[1 , 2 ], \
[4, 5], \
[6, 7]]
>>>print a
[[1, 2], [4, 5], [5, 6]]
Arithmetic operations are +(sum), - (subtract), * (multiply), /(divide), ** (exponentiation),
%(modular division).
To know more about math functions, type:
>>> import math
>>> help(math.sin) # information of sin function is obtained.
Help on built-in function sin in module math:
sin(...)
sin(x)
Return the sine of x (measured in radians).
Now, These operations can be assigned for sequences and strings in python.
e.g.
>>>operation1=[1,2,3]
>>> print operation*2
[1,2,3,1,2,3]
similarly for string also.
Comparison operations are same as that for fortran90.
i.e. <, > , <=, >=, ==, !=
e.g.
>>>x=2;y=3.0
>>>print x<y
True
>>>z =1.
>>> print x<y and x==z
False
Now i will tell about the decision making in python :
using examples
if/elif/else construct:
#!/usr/bin/python
def decision(x):
if x==0.0:
result= 'neutral '
elif x<0.0:
result='negative charge'
else :
result ='positive charge'
return result
x=0.00001
print ' result is' ' ' + decision(x)
output:
result is positive charge
Repetitive structures:
while loop:
syntax is
while condition:
statement block
while loop with else
while condition:
statement block
else:
statement block
Note when the statement block is executed, again the while loop is executed, and if the condition
is false, control comes out of the while loop and goes to the next statement in the program.
Here is an example:
===========================
#!/usr/bin/python
count=10
start=0
list1=[] # empty list
while start < count:
list1.append(1+start)
start=start+1
print list1
else:
print "now start = %1d is is equal to count = %2d" %(start, count)
print "...........job ends !!!"
output:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
now start = 10 is is equal to count = 10
...........job ends !!!
=============================
For loop:
syntax is: for target in sequence:
statement block
Here for loop requires target which loops over sequence.
Here is an example,
==================================
#!/usr/bin/python
maxval=5
list1=[] # empty list
for i in range(1, maxval):
list1.append(1./i)
print list1
print "Below is the output outside the for loop."
print list1
output:
[1.0]
[1.0, 0.5]
[1.0, 0.5, 0.33333333333333331]
[1.0, 0.5, 0.33333333333333331, 0.25]
Below is the output outside the for loop.
[1.0, 0.5, 0.33333333333333331, 0.25]
==================================
About raw_input, continue, break, file opening, closing, writing in python:
Here i am just giving example to demonstrate above commands.
======================================================
#!/usr/bin/python
list1 = ['dft', 'xc', 'paw'] # list
# Giving input from prompt
# here i am using eval function to convert the
# string value to numeric value
#inp_py_prompt = eval(raw_input('Please enter the name:\n'))
#print inp_py_prompt
inp_py_prompt = raw_input('Please enter the name: ')
print 'you entered', inp_py_prompt
for i in range(len(list1)):
print 'list number =', i, ' is list item =', list1[i]
if list1[i] == inp_py_prompt:
print 'well',inp_py_prompt , 'is on the list1'
#break # if break is exceuted then elif/else is skipped and control
# goes to the start of if statement.
print 'list range =',range(len(list1))
output:
Please enter the name: paw
you entered paw
list number = 0 is list item = dft
list number = 1 is list item = xc
list number = 2 is list item = paw
well paw is on the list1
list range = [0, 1, 2]
======================================================
Few more things:
int(x) => x is converted to in integer
long(x) long integer
float(x) real type
complex(x, y) complex x+yj
Print output in different formats:
wd integer, w.df float, w.de exponential format, similarly others.
For more format , go to http://docs.python.org/tutorial/inputoutput.html and
http://docs.python.org/release/1.4/tut/tut.html
Note:
sometimes, we want to control the error, it can be controlled by using the following
statement,
try:
normal block statement
except error:
error you want to print.
Opening, closing and reading/writing data files:
To access the data in file, we need to create a file object (a value that represents an open
file).
file-object = open (filename, action)
filename is the name of the file to be opened, whereas action can read, write,
append etc specified by following keywords:
'r' = read an existing file
'w' = write to file, if file is not there it will be created.
'a' = append existing file at its end
'r+' = read and write to an existing file
'w+' = r+, with creation of file it doesn't exist.
'a+' = ...hmm, i don't know, .......oh,..... it like 'w+', but if you add the data to it, then that
will be appended to the end of the file.
Now, to read and write data:
TO READ:
use file-object.read(p)
file-object.readline(p) -> reads p characters in a line
file-object.readlines()
NOTE: always close your file, if it is no longer required by using file-object.close()
TO WRITE:
use file-object.write()
file-object.writelines()
example:
==============================================
#!/usr/bin/python
print "1.)..........\n"
file_object = open("function.py", 'r+')
print 'reading data from function.py file...'
strg = file_object.read()
print strg
print 'closing function.py file....\n'
file_object.close()
print "2.)..........\n"
data = ['This the first line', 'This one is second']
print data
mifile = open('input.txt', 'r+')
st = mifile.read()
print st
mifile.close()
==============================================
Functions, modules and arrays:
structure of the function is:
def function_name(parameter1, parameter2,....);
statement block/blocks
return values_to_return
if values_to_return is/are omitted, then a null value is returned.
example: to find the derivative of f(x) = sin(x)+2cos(x) using function by
the following formula, (finite difference formula).
===================================================================
#!/usr/bin/python
from math import sin, cos
# here i am loading sinx, cosx from
# module 'math'.
# you can also load the whole of the module
# by using " from math import * " OR
# " import math "
# function definition
def find_derivative(f,x,h = 0.0001): # stepsize=h, you know!!
df1 = (f(x+h)-f(x))/h
return df1
expr = lambda x: sin(x)+2*cos(x)
# this is the way an expression is loaded in the
# function in python
x = 0.5
df1 = find_derivative(sin, x)
print 'df1 = d (sin(x)) =', df1
df1 = find_derivative (expr, x)
print 'df1 = d (sin(x)+2*cos(x)) =', df1
print "now checking the results by direct derivatives: "
print 'df1 = d (sin(x)) =', cos(x)
print 'df1 = d (sin(x)+2*cos(x)) =', cos(x)-2*sin(x)
output:
df1 = d (sin(x)) = 0.877558589151
df1 = d (sin(x)+2*cos(x)) = -0.0813802447164
now checking the results by direct derivatives:
df1 = d (sin(x)) = 0.87758256189
df1 = d (sin(x)+2*cos(x)) = -0.081268515318
===================================================================
Arrays in python:
To use array, you have to use numpy module in python program.
No empyt entries in arrays are allowed.
Array is created using the following statement
array(list, dtype = data-type)
>>> from numpy import array, float
>>> a= array ([[1, 2, 3], [2, 4, 5], [7., 4, 9]])
>>> print a
[[ 1. 2. 3.]
[ 2. 4. 5.]
[ 7. 4. 9.]]
>>> a= array ([[1, 2, 3], [2, 4, 5], [7., 4, 9]], dtype=int)
>>> print a
[[1 2 3]
[2 4 5]
[7 4 9]]
>>> a= array ([[1, 2, 3], [2, 4, 5], [7., 4, 9.2]], dtype=int)
>>> print a
[[1 2 3]
[2 4 5]
[7 4 9]]
>>> a= array ([[1, 2, 3], [2, 4, 5], [7., 4, 9.2]], dtype=float)
>>> print a
[[ 1. 2. 3. ]
[ 2. 4. 5. ]
[ 7. 4. 9.2]]
>>> print zeros((2,2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'zeros' is not defined
>>> from numpy import *
>>> print zeros((2,2))
[[ 0. 0.]
[ 0. 0.]]
>>> print ones((2,2))
[[ 1. 1.]
[ 1. 1.]]
>>> print ones((2,2), dype=float)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ones() got an unexpected keyword argument 'dype'
>>> print ones((2,2), dtype=float)
[[ 1. 1.]
[ 1. 1.]]
Operation on arrays: note that when dealing with arrays in numpy, operation is applied
on every element of the array.
>>> from numpy import *
>>> print B
[[2 3 2]
[3 4 5]
[4 5 1]]
>>> print conjugate(B)
[[2 3 2]
[3 4 5]
[4 5 1]]
>>> print inv(B)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'inv' is not defined
>>> from numpy.linalg import inv
>>> print inv(B)
[[-3. 1. 1. ]
[ 2.42857143 -0.85714286 -0.57142857]
[-0.14285714 0.28571429 -0.14285714]]
For any explaination of basics of python, please contact me at this email contact.
More about numerical and scientific Python will be added.
=============================================================