Getting Started With Python

Physics 7682 / CIS 6229, Fall 2008 - Computational Methods for Nonlinear Systems

Course web page: www.physics.cornell.edu/~myers/teaching/ComputationalMethods/
This page: www.physics.cornell.edu/~myers/teaching/ComputationalMethods/GettingStarted.html

Starting up ipython

  1. Start a terminal window (Applications -> Accessories -> Terminal).
  2. Type ipython to launch the interactive Python shell.
  3. Type in mathematical expressions, and see how they are evaulated. Try expressions using addition (+), subtraction (-), multiplication (*), division (/), exponentiation (**), and modulo (%). Try division for both integers and floats, e.g., 5/2, 5.0/2, 5/2.0, and 5.0/2.0. (The type-dependent behavior of division in Python is in a state of transition; for now, however, the default behavior of an integer division such as 5/2 is different than you might expect.)
  4. Explore how the double equal sign (==) generates expressions that evaluate to a Boolean variable (True or False), as in 2+2==4, or 2+2==5.
  5. Setting a=5 (a single equal sign denotes assignment), write an expression that tests if a is odd using the modulo operator. (It should evaluate to False.)
  6. Define a function isEven(n) to test if n is even (returning True or False). The syntax for defining a function in Python introduces four new features [def, the colon (:), indents, and return], most easily explained by example:
    def isEven(n):
        blah = XXX       # for some python code XXX
        return blah
    
    or even more simply:
    def isEven(n):
        return XXX
    
    Note the importance of indentation. Unlike other languages, where indenting is used only to make programs readable, Python uses indenting and new lines to delimit the ends of expressions, functions, and code blocks. The ipython shell automatically indents based on context. To end a function, use a blank line. When writing Python code in emacs, the Python editing mode will be automatically loaded, and indentation should be handled properly.

Library importing and plotting

Python is a general-purpose programming language, but does not include in its core "special" topics like mathematical functions, graphics, and plotting. External libraries must be imported for these functions.
  1. Import the package scipy using import scipy, and then try using the function scipy.sin and scipy.pi to evaluate sin(pi/2) as scipy.sin(scipy.pi/2)
  2. Notice that one uses functions from inside packages by preceding them with the package name. This is good programming practice, avoiding name collisions (where two different packages might use the same function name).
  3. Use scipy.linspace to define an array x of 20 points starting at zero and ending at 2 pi, as in x = scipy.linspace(0, 2.*scipy.pi, 20). Applying scipy.sin to the entire array x: y = scipy.sin(x).
  4. Import the plotting package pylab. Plot sin(y) versus y, as in pylab.plot(x, y), followed by pylab.show(). If you want to save the figure you made to an image file, click the icon at the bottom of the the figure window that looks like a floppy disk. (Does anybody still know what a floppy disk is?) Close the figure window to regain control within ipython.
  5. Further information about scipy and pylab is available. Typing help(scipy) will provide some documentation on that package. Next try typing scipy. followed by a Tab. (The ipython shell provides "name completion", listing all possible variable or function names that are valid completions of what you've already typed.)

External editors, %run, and Hints files

  1. Make a directory called "Primes", using the command mkdir Primes or using the graphical tools.
  2. Start up a Web browser (Applications -> Internet -> ...), and find the exercise page on prime numbers www.physics.cornell.edu/~myers/teaching/ComputationalMethods/ComputerExercises/Primes/Primes.html
  3. Save the hints file (PrimesHints.py) into your Primes directory and rename it "Primes.py"
  4. In the terminal window, type
    	     
      cd Primes  	[this changes directory]
      ls		[should show Primes.py]
      ipython       [this starts ipython]
      In[1]: %run Primes    [%run is an ipython "magic" command, not a Python language command]

  5. In a second terminal window, go to the same directory and open the Primes.py file in a text editor. On the lab computers, good editors include emacs, kate, and gedit. Start them with emacs Primes.py or kate Primes.py or gedit Primes.py. It is important that you are in the correct directory. In the text editor, you will make changes to Primes.py, save the file, and once again execute %run Primes in ipython. Changes that have are made in Primes.py should then be reflected in the ipython session.
  6. You may want to explore the various editors and pick out which one you like best. All of the editors offer a "Python" editing mode which is capable of bracket completion, auto indentation, and syntax highlighting. Some of these features need to be manually turned on. For example, in emacs do the following:
  7. The first step in Primes.py is to implement the isEven function that you already defined interactively. You will see the following code in the Primes.py file:
    def isEven(n):
        """
        Function that will "return True" if n is even, False otherwise.
        Uses the modulo operator, which returns the remainder of the
        division of n by m:  e.g., n%m is 0 if n is divisible by m.
        """
        pass
    
    The word pass is a Python keyword that does nothing. It is included here since every function in Python needs a valid body, even if that body does nothing (pass). Even before redefining the function body, you can ask for help about the isEven function (via help(isEven)). You will see the documentation string (docstring) echoed in the ipython window. A good thing to keep in mind is that if you want your function to return a value, you must use the return command.
  8. After implementing isEven, continue to implement other functions that need to be defined. (Some function bodies in this exercise have been left intact, although you could look them over to see what they are computing.) Once you have implemented all the functions in the file, compare the set of generated prime numbers up to 10000 (or whatever limit you choose) with the theoretical density of primes by running the following commands:
    primes = primeList(10000)
    PlotPrimeDensityTheory(primes)
    
  9. Once you've finished with Primes, tackle the Random Text generation module at: www.physics.cornell.edu/~myers/teaching/ComputationalMethods/ComputerExercises/RandText/RandText.html