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

printing1.py

#!/usr/bin/python
#                          Simple python examples
# python/examples/printing1.py
#                 David MacKay and Sanjoy Mahajan 

print "Hello world"
x = "Hello World"
print "The value of x is", x

# You can use either single or double quotes
# to enclose strings

print 'Also, the value of x is', x
print "Multiple lines: The value\n of x\n is", x

i = 123
j = 99
y = 123.45678912345
print "d - an integer: %d" % (i) 
print "f - a floating point number: %f" % (y)
print "f - a floating point number: %6.2f" % (y)
print "f - a floating point number: %6.1f" % (y)
print "g - a float in scientific notation: %g" % (y)
print "g - more scientific notation: %6.2g" % (y)
print "s - The value of my string is %s" % (x)
print "int with 4 characters space: %4d %4d" % (i,j) 
print "int with 4 characters space: %4d %4d" % (j,i)

# The print statement automatically includes a newline
#  at the end of the output.
# To prevent the automatic newline add a comma
print "d - an integer: %d " % (i) ,
print "f - a floating point number: %f" % (y)

# The standard backslash characters (\n, \t, etc.)
# are recognized.
# If you want to print backslashes, you can turn off the
# backslash feature by preceding the string with 'r' -

print r"Raw string with \n and \t in it"
print "String with \n and \t in it"

print """Tripling-quoting is also permitted"""

David MacKay / python resources /

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