St. Xavier's College: Python Language Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Python Language Lab

Dr. Shibaji Banerjee and Dr. Suparna Roychowdhury

M.Sc Physics, SEM I

St. Xavier’s College


A Pinch of Python
Dr. Shibaji Banerjee
Department of Physics,
St. Xavier’s College, Kolkata

Pictures add variety to our sense experiences. In this session we would be busy drawing
diagrams, and learn Python as a side effect.

Interactive session
To open an interactive session, open a shell and say ’Python’ (Press enter). Python replies
back with a triple prompt. We would need a canvas to try our skills and we can get one
from the ’turtle’ module that any python distro has. Type from turtle import * to
avail all functions from the turtle module (you can check what is now in the workspace by
executing dir()). Now hang your (yet empty) canvas on the screen by typing reset() at
the triple prompt. Let us try to draw a square on the screen. LOGO!

forward(50)
right(90)
forward(50)
right(90)
forward(50)
right(90)
forward(50)
right(90)

You are right - this is an very dull way of drawing a square, but the effect looks good on
screen. Lets make it a bit compact now: for loop

l=range(4)
for x in l:
forward(50)
right(90)

In the first line of the above code, we create a Python list. The rest of the code is an
example of a python loop / iterative sequence, in which we make x take on the values 1,2,3
and 4 in succession. These values just mark the current iteration cycle. Note the colon,
which marks the beginning of a scope and the indented lines which indicate a compound
statement contained within the scope.
We have seen how to loop over a list in python. Another way to loop is to conditionally
execute a set of statements using the while construct – see the following example which
achieves the same feat as the above code segment but using the while loop. while loop

reset
test=4
while test > 0
forward(50)
right(90)
test=test-1
Logic
To formulate a logical condition we need comparison operators (>,<,>=,<=,<>), logical
connectives (and, or, not). A logical condition evalutes to a Boolean value: True or
False. Variables can take boolean values too.
Let us now try to draw a square with alternate side colored with red and blue respec-
tively. The following code achieves this with the help of an if construct. The code is

1
somewhat longer and at this point you might want to put it a file (say in csqr.py). You
can run this file from the Python shell itself by saying e.g execfile(’csqr.py’) after
importing stuff from ‘turtle’. Branching with if

reset
test=4
width(2)
c=’red’
reset()
while test > 0:
if c==’red’:
c=’blue’
elif c==’blue’:
c=’red’
color(c)
forward(50)
right(90)
test=test-1

We could have run the above program from the shell prompt itself by saying python csqr.py.
The file would run but the canvas would disappear immediately after drawing the square
is over, leaving us with little chance to sit back and appreciate the artistic quality of our
work!. This could be prevented if we add the following two lines at the beginning and the
end of the code respectively. Calling member function

import time #at the beginning


time.sleep(10) #at the end

Note that the import structure here is different and therefore we have to invoke the sleep
function as a call to a member function belonging to the time module. Time is ripe for
writing our very own module, a function to draw a square with a side and color specified
at the time of call. We put the following piece of code in a file called func.py User Functions

’’’
module to draw a square.
’’’
from turtle import *
def sqr(l=50,c=’red’):
’’’
func.sqr(length,color): draw a square with edge
length <length> and color <color>
By default, the square is drawn with side 50 and color red.
Copyleft Shiva, March 2008
’’’
color(c)
for i in range(4):
forward(l)
right(90)

You can get help on this module by typing help(func) and help(sqr) at the triple prompt.
The help flows from what you have written in the file itself: Python refers to the help text
as docstrings.
This is roughly all we need to know to get started with python. Hope it helped!

2
Date

Python Starter Lab

FactSheet

1. Invoke python shell: say python from a terminal.

2. Invoke a python script: say python <scriptname>.py

3. Single line comments start with a #, Line extensions: \, Multiple statement separator: ;, strings are quoted
using a single, double or triple quote.

4. Python supports integers, floats and strings as data types. Strings must be single, double or triple quoted.
Strings are immutable sequences of characters. Read help(str)

5. To print variables a,b,c use print a,b,c To print something to a file, open the file and print to it,

f=open(’test.txt’,’wt’)
print >> f, a,b

6. To read in a variable a, use a=input(’a: ’)

7. Module Imports: import sys or import math

8. Way to pass arguments to a python script:

import sys
s=sys.argv[1]

9. A decision block is implemented as:

if this:
−i|do that

else:
−i|do something else

More elif clauses can be added. Remember that indenting is significant in python

10. A loop is implemented typically as:

for i in ’kolkata’:
−i|print i

The range function is useful with loops. range(1,11) will return the list [1, 2, . . . , 10], while range(1,11,2)
will return the list [1, 3, 5 . . . , 10] Loops can also be implemented as a while condition:

while a<10:
−i|a=a+1

−i|print a

11. The pass statement is how we say “do nothing” in python.

12. Functions are defined in the following way in Python

def add(x,y):
−i|return x+y

1
1 Python Starter Lab
ASSIGNMENTS

1. Invoke the python interpretor and make it read and divide two complex numbers. Complex numbers are
entered as in a=2+3J. Print out a sequence of test values in the console.

2. Write code to print a triangle on the console using asterisks. In python you can concatenate strings using
the multiplication operator (So ’*’*3 is ***). You can also print a justified string using the string member
functions ljust,rjust,center The output should look like

*
***
*****
*******
*********
***********

3. Loop twenty times using the for loop, printing out a sequence of 0, 1 and 2s, e.g 0,1,2,0,1,2, . . . using the
modulo operator.

4. Write a program to print out the sum of a 5 digit number.

5. Load the math module and read the help on its atan2 function. Use this function to calculate the polar
angles of the vectors (±3.3,±4.6). Express your answer in degrees.

6. Draw a triangle on the canvas using a for loop. You can optionally run this from a file, keep the window
open for n seconds, where n is read on the command line(e.g python triangle.py 5).

7. Draw a 20 step ascending / descending staircase on the canvas using the for loop.

8. Write a program to generate the multiplication table of any number (request input) between 1 – 100.

> mtable
Which number? 17 (ret)
Table of 17
17 x 1 = 17
17 x 2 = 34
. . .
17 x 10 = 170

9. Define a function to draw any regular polygon on the canvas. It should take two arguments: the length of
a side and the number of sides. Test it out for several polygons. Modify the function to take in an optional
color argument.

10. Generate a discrete random walk sequence (for, say 50 steps) on the canvas using the function ‘randint’
available in the ‘random’ module.

11. Create a program called ”add” to sum two arguments supplied at the command line. [Use the eval function
to convert input strings to numbers first]

> add 2 3
5.0
>

12. Modify this script so that it gives a helpful error message if both arguments are not present:

2
> add 2
Please provide two numeric arguments
>

13. loop through the contents of dir() and print them each on a line.

14. Calculate the ratio of the magnitude of the force of gravitational and electrostatic interaction between
two protons when they are separated by a distance equal to a0 = 5.29177 × 10−11 m and also when they
are separated by R = 6378140m. At which distance does the two forces become comparable? Declare all
Constants (G = 6.673 × 10−11 , mp = 1.67262 × 10−27 , 0 = 8.85419 × 10−12 e = 1.60218 × 10−19 in MKS units)
in a file physconsts.pi and load this file in the workspace using the execfile command. Subsequebtly,
carry out the calculations in the workspace.

3
Date

Python Lab 2

FactSheet

1. Quote strings either by a single, double or triple quote.


2. Strings are immutable. An empty string can be created, e.g using the
phrase s="".
3. Strings can be iterated letter by letter in a for loop.
4. Read help(str) to find out all about string operations. Important meth-
ods are join,strip,split
5. Lists are mutable. An empty list can be created using the phrase l=[].
6. To add elements to the end of a list, use the append method, to remove
elements, use the remove method.
7. Lists can be sorted (lst.sort()) and reversed (lst.reverse()) in place.
8. Strings may be converted to lists using the list ufunc.
9. Lists can be iterated element by element in a for loop.
10. Read help(list) to find out all about list operations.
11. A dictionary can store values against a key, e.g d={’Rim’:21,’Raj’:23}
is a dictionary with key-value pairs (Rim,21) and (Raj,23). An empty
dictionary can be created using the phrase d={}. The Keys() method
of a dictionary. retrieves all the keys of a dictionary object in an un-
sorted list. Key-value pairs can be inserted in an existing dictionary using
d[’Sid’]=22. d[’Rim’] just returns the associated value ‘21’. The get
method for dictionaries is suitable when someone needs to query about an
inexistent key, so that d.get(’Pathan’,10) will fetch ‘10’ even when no
values are listed for this key in the dictionary. Note that d.get(’Rim’,10)
will get ‘21’, as expected.
12. Read help(dict) to find out all about list operations.

1
1 Python Strings Lists & Dictionaries
ASSIGNMENTS

1. Print a sequence of stars, 10 on the first, 9 on the second, . . . . The


sequence will look like -

**********
*********
********
*******
******
*****
****
***
**

Key Ideas: Concatenation using the ∗ operator, for loop, range() with
negative step.
2. Print butterfly wings, as shown

********** **********
********* *********
******** ********
******* *******
****** ******
***** *****
**** ****
*** ***
** **

Key Ideas: for loop, String padding methods


Hint: Read the help on str objects to find the necessary methods.
3. Use the String padding functions to print a pyramid, like

*
***
*****
*******

Key Ideas:Center justified Strings, non unit step in for loop.


4. A dna string is specified as ’gcatgactattccttgac’. What is the 6th base from
the beginning?, from the end? Answer this question both using negative
indexing and also without assuming negative indexing. Key Ideas:Element
extraction using the str[index], negative indexing, len ufunc.

2
5. Three restriction sites are:
(a) EcorI = gaattc
(b) BamHI = ggatcc
(c) HindIII = aagctt
Enter a sequence (like AGATTC), say which restriction sites are present?
Key Ideas: Testing with the in conjugator, boolean data types.
6. Count the number of a in a dna (say gcatgactattccttgac).
Key Ideas: Single line if condition in for loop used for incrementing
counts. Strings can be iterated letter by letter in a for loop.
7. List the occurrences of all the bases in a dna string. The output will look
like

A: 6
C: 4
T: 2
G: 4

8. Make the above action into a function (say basecount(dna) ) and allow
for the case when both lowercase and uppercase letters may be present
in the input(See next problem for ispiration). You can now take the easy
track and use the count method for counting the number of appearances
of a,c,t,g.
9. use the count method to calculate the GC content of dna. The output
should appear as

%GC Content: 68.24

Key Ideas: C style printing using % operator, float mask.

10. Read the help on string objects and attempt the following for dna strings.
(a) replace all occurances of ’a’ with ’A’ and revert back.
(b) return capitalized version.
(c) join two dna strings.
11. Modify the last but two problem to return a list of dna counts, e.g [6,4,2,4]
Key Ideas: append method of list objects.
12. Read the help on the find method of strings to prepare a list of all posi-
tions of ‘a’ in the dna. Hint:

3
>>>dna=’gcatgactattccttgac’
>>>dna.find(’a’)
>>>2
>>>dna.find(’a’,3)
>>>5
>>>dna.find(’a’,6)
>>>8
>>>dna.find(’a’,9)
16
>>>dna.find(’a’,17)
-1

Key Ideas: Preparing logical conditions from flag variables, append method
of list objects.
13. Write a function to look for non ambiguous restriction sites in the supplied
data file(dna.dat) for EcoRI, BamHI, HindIII.
14. Modify the last but three problem to return a dictionary of dna counts, e.g
[’a’:4,’c’:5,’t’:6,’g’:3] Key Ideas: Updating dictionary contents.
15. Calculate the complement of a dna using a dictionary of replacements.
16. Write a function to reverse a string by turning it into a list, reversing it
and then stitching the elements together to get the reversed string.
17. Analyze a dna string to extract its codon count(codon vs frequency data),
by loading an empty dictionary. Hint: Use the % operator to find the last
index of the sequence divisible by three. Codon counts can be incremented
by the get method of dictionary objects. Print a sorted list of codon
counts. The output will look like:

aga = 1
atc = 1
cca = 2
cgc = 1
gtg = 1
tct = 1

for a dna tctccaagacgcatcccagtg.


18. Generate all possible combinations of the letters A, B, C.

4
Date

Python Lab 3

FactSheet

1. Use the shallow copy operation from the copy module to copy a list by
value.
2. List comprehensions are ways of applying an operation to all list members,
e.g applying [3*x for x in lst] to lst=[2,3,9] will return [6,9,27]
3. List comprehensions can be used to choose a subset of list members to
which the operations are applied, e.g [3*x for x in lst if x%3==0]
will return only [9,27]
4. List comprehensions can be applied to two (or more) lists, e.g
[x+y for x in lst1 for y in lst2] will yield a list whose members
are the sum of all pairs of elements of lst1 and lst2.

5. The function reduce(f,seq) returns a single value constructed by ap-


plying the binary function f to first two items of the sequence, then
on the result and the next item, and so on. For example, to compute
the sum of the numbers in a list of integers a, use the following code:
reduce((lambda x,y:x+y),a) The lambda construct is a way of defining
a scratch function for which we donot bother to assign a name. lambda
functions can have any number of arguments, but must return only a
single expression constructed out of its arguments. In order for reduce
to work, the lambda function must contain two (only two) arguments.
You can also use a regular function in place of a lambda function, e.g
def add(x,y): return x+y followed by reduce(add,a) works equally
well.
6. Tuples are just like lists, except that they are immutable(no append method)
and must be enclosed within parenthesis. To pack a tuple use: a=1,2,3
to unpack a sequence say, x,y,z=a
7. python supports recursive function definition, e.g to define something
equivalent to the defintion of a factorial, use:

>>> def fac(n):


if n==1 or n==0:
return 1
else:
return n*fac(n-1)
>>> fac(5)
120

1
8. Python functions can take default values for arguments, e.g def f(a,b=10):return a+b
can be called as f(2) or f(2,3) to return 12 and 5 respectively. Argu-
ments with default values must occur after the regular argument list.
9. Python functions can take key-value pairs in the argument list too e.g
def f(x=2,y=3):return x+2*y can be called as f() → 10, f(0,2) → 4
and also as f(y=2,x=3) → 7. This is useful if we do not want to remember
the positions of the arguments in the functions call list.
10. Python functions can take an arbitary number of arguments beyond the
standard list. These functions are defined using form f(x,y,*a). If you
call this with f(2,3,-1,-3) the function would internally make the as-
signments x->2,y->3,a=(-1,-3)

2
1 List comprehensions, Tuples and Functions
ASSIGNMENTS

1. Read a list of numbers and find out the median of the dataset without
destroying the original list.
2. Input an array of floats. Then print out an array of reciprocals using list
comprehension.
3. Do the same program but now include some zero elements in the list.
Can you avoid the division by zero error using list comprehension(with
conditions testing)?
4. Input a list of integers. Make use of list comprehension and function defi-
nition to return a list of integers which are triples of the original numbers
if the original number is even and unchanged otherwise, i.e [2,3,7,4] →
[6,3,7,12]
5. Define a list of lowercase vowels. Use this list to extract the consonants
from an input string, e.g "kolkata” → "klkt"
6. Use the reduce function to calculate the Arithmatic, Geometric and Har-
monic Mean of a list of floats.
7. Define a recursive function fib which can calculate the nth member of the
Fibonacci sequence: f1 = 1, f2 = 1, fn = fn−1 + fn−2 when n > 2
8. Define a function which can return n members of a Fibonacci sequence.
9. Define a function which can return members of a Fibonacci sequence which
are less than a given number (supplied as argument)
10. The (u)function zip takes two(or more) sequences and puts out a list
of tuples with one member from each sequence. Try this on two vectors
x=[1.0,2.0,3.0] and y=[4.0, 5.0, 6.0] and verify this. Use Zip, tuple
notation and list comprehension to implement vector addition(elementwise
addition).
11. Use Zip, tuple notation and list comprehension
Pn to find out the dot product
between two vectors (defined as ~a · ~b = i=1 ai bi ) of arbitary length n.
You can either use reduce to find the sum or just the sum (u)function.
12. Define a function which can take a cartesian coordinate pair and con-
vert it to its polar equivalent. The function would assume that the de-
fault values of x and y are 10,10 and we can call it in any of the fol-
lowing forms: c2p(),c2p(20),c2p(x=5,y=10),c2p(y=10,x=5) Do not
forget the math.atan2 function!.

You might also like