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

dowhile.py

#!/usr/bin/python
#
# How to make a 'do-while' loop in python
#
# Solution   do A while B 
while True:
    # A
    print "This line is executed at least once"
    B = False
    if not B: break

# Explanation (from python.faqts)

#
#C, C++, Pascal, and many other imperative languages have a form of a
#loop with the loop test at the bottom, or (equivalently) a loop which is
#always executed at least once. Here is how it would be used in C:
#
#    /* Skip past the header */
#    do {
#        line = file.readOneLine();
#    } while isHeaderLine( line );
#
#Notice that if we were to translate this into a while loop (test-at-top
#loop) then the data preparation step would have to be repeated:
#
#    /* Skip past the header */
#    line = file.readOneLine();
#    while( isHeaderLine(line) ) {
#        line = file.readOneLine();
#    }
#
#Repeating it is bad style, and it gets quite bad if there's more than a
#single line (exception handling, for instance). So what is a programmer
#to do in Python, which has only the test-at-top style of loops? Here it is:
#
#    # Skip past the header
#    while 1:
#        line = file.readOneLine();
#        if not isHeaderLine( line ): break

David MacKay / python resources /

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