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

loop1.py

"""
To add the integers from 1 to 10:
"""

total=0
for i in range(11):
    total += i
print total

""" The range function generates a list of 11 numbers
 starting with 0, so the numbers from 0 to 10.
 The for loop goes through assigning each element of
 the list to the variable i.
"""

## To print a list of names, one per line:

names=['sanjoy', 'jan', 'ian']
for person in names:
    print person

""" Or you can more simply do
    >>>    print names
    which prints the list of names on one line.
"""


David MacKay / python resources /

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