Introduction to Python Hands-On Exercises

Exercise 1

Start the iPython interpreter. Use it to calculate the first few Fibonacci numbers.

module load python
ipython
In [1]: terms = [0,1]

In [2]: for i in xrange(0,10):
...:      f = sum(terms)
...:      print f
...:      terms[0] = terms[1]
...:      terms[1] = f
 1
 2
 3
 5
 8
 13
 21
 34
 55
 89

Exercise 2 Run a batch script

Create a new Python source file. Convert the code above to a batch script that that can be run on the command line.

module load python
python fib.py

Exercise 3

Write a program that takes that will read the array from data1.txt and report the sum of all values, max value, and min value.

Exercise 4

Write a program that will estimate the base of the natural logarithm e according to

http://upload.wikimedia.org/math/6/3/9/639ff4900f0b8fac424e099445c50a38.png

Make n a command line argument.

Exercise 5

Calculate PI by summing the first few million terms in the Leibniz formula.
1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = pi/4

Exercise 6

Elevation_Benchmarks.csv contains information on the elevation of many locations around Chicago. Write a script to read the file in, and identify the locations with the highest elevation.

Exercise 7

Develop a simple class to describe circles based on their radius. Write methods to calculate the diameter, circumference, and area.

Save this class in a module (a stand-alone .py file). Import the module from another Python script. Create several circle objects, and print their properties.

Exercise 8

Run and modify the simple harmonic oscillator code.