Simple python examples

What you want What it is called Examples
Outputprintprinting1.py
randomwalk4.py
Loopsforloop1.py
dowhile.py
Command-line inputsys.argv commandline1.py
commandline2.py
randomwalk4.py
Function definitiondef fact.py
randomwalk4.py
randomwalk5.py
Reading in lines from standard inputsys.stdin reading1.py
Substitution using regular expressionsre reading1.py
length of a listlencommandline2.py
Convert string to integerintcommandline2.py
find something in listfind1.py
Sort a listsortsort1.py
Split a stringsplit1.py
Reading lines from a fileopen, readlinesreading2.py
Random numbersrandom.random()randomwalk4.py
randomwalk5.py
Automatic execution__name__, __main__randomwalk4.py
randomwalk5.py
Plotting graphsGnuplot randomwalk5.py
Plotting histogramspylab.hist histo1.py
Automated testingdoctest
(explanation)
DocExample.py
DocExample2.py
AlanDice.py
AlanDice2.py
decomposeSquares.py
Recursion decomposeSquares.py

randomwalk4.py

#!/usr/bin/env python
#                    Simple python examples
# python/centrallimit/randomwalk4.py
#                    David MacKay
#
# Make a walk with a fair coin, printing out
# the points reached at times 0, period,
# 2*period, 3*period...
#
# Usage:
# $ randomwalk4.py [R [T [period]]]
# Optional arguments:
#    R      = number of walks
#    T      = duration of walk
#    period = period between plots
#
# Example:
# $ randomwalk4.py 1 10000 1  > 1walk.txt
# $ randomwalk4.py 8 10000 10 > 8walks.txt
import random
import sys

def walk(T=10, period=1):
    """random walk with a fair coin"""
    x=0;    print "0 \t",x # start
    for t in xrange(T+1):
        u = random.random()
        if (u<= 0.5): x+=1 
        else:         x-=1 
        if (t%period == 0 ) :
            print "%d \t %d" % ( t+1 , x )
    pass

def makewalks(R=10, T=100,period=1):
    for r in xrange(R):
        walk(T,period)
        print "\n" ## two blank lines
        ## between runs - useful for gnuplot

if __name__ == '__main__':
    R=2
    T=100
    period=1
    if(len(sys.argv)>1):
        R=int(sys.argv[1])
    if(len(sys.argv)>2):
        T=int(sys.argv[2])
    if(len(sys.argv)>3):
        period=int(sys.argv[3])
    makewalks(R, T, period )
    pass

# This program illustrates
#  - how to read the command line
#  - how to print stuff ready for plotting
#  - how to use random.random()
#      (there are many other random functions
#       available in python; random.random()
#       makes numbers between 0 and 1)
#  - how to write a package that contains
#       functions and that has a default behaviour
#       if run directly from a terminal
#       or from a python development environment


David MacKay / python resources /

David MacKay / Computational Physics wiki (UCAM only) / C++ resources /