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

commandline2.py

#!/usr/bin/python
#                 Sanjoy Mahajan and David MacKay
# python/examples/commandline2.py
#
Usage = """
A python program to sum the integers from 1 to n,
where n is given on the command line.

$ commandline2.py 15
120

To make this file executable,
$ chmod +x commandline2.py
"""
import sys
total = 0
if (len(sys.argv)<2):
    print "error - usage:\n $ commandline2.py "
else:
    for i in range(int(sys.argv[1])+1):
        total += i
    print total

print """
The int function converts the string sys.argv[1]
to an integer.
Notice the +1 in the range function.
"""


David MacKay / python resources /

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