Revision 70 as of 2007-06-22 14:04:42

Clear message

Here are some example simple programs. Please feel free to contribute, but see notice at bottom, please.

These examples assume version 2.4 or above of Python. You should be able to run them simply by copying/pasting the code into a file and running Python. Or by inserting this line (#!/bin/env python) at the beginning of your file (Unix/Linux), making the file executable (chmod u+x filename.py) and running it (./filename.py).


1 line: Output

   1 print 'hello world'

2 lines: Input, assignment, comments

   1 name = raw_input('What is your name?\n') # \n is a newline
   2 print 'Hi', name

3 lines: For loop, builtin enumerate function

   1 my_list = ['john', 'pat', 'gary', 'michael']
   2 for i, name in enumerate(my_list):
   3     print "iteration %i is %s" % (i, name)

4 lines: Fibonacci, tuple assignment

   1 parents, babies = (1, 1)
   2 while babies < 100:
   3     print 'This generation has %d babies' % babies
   4     parents, babies = (babies, parents + babies)

5 lines: Functions

   1 def greet(name):
   2     print 'hello', name
   3 greet('Jack')
   4 greet('Jill')
   5 greet('Bob')

6 lines: Import, regular expressions

   1 import re
   2 for test_string in ['555-1212', 'ILL-EGAL']:
   3     if re.match(r'^\d{3}-\d{4}$', test_string):
   4         print test_string, 'is a valid US local phone number'
   5     else:
   6         print test_string, 'rejected'

7 lines: Dictionaries, generator expressions

   1 prices = {'apple': 0.40, 'banana': 0.50}
   2 my_purchase = {
   3     'apple': 1,
   4     'banana': 6}
   5 grocery_bill = sum(prices[fruit] * my_purchase[fruit]
   6                    for fruit in my_purchase)
   7 print 'I owe the grocer $%.2f' % grocery_bill

8 lines: Command line arguments, exception handling

   1 #!/usr/bin/env python
   2 # This program adds up integers in the command line
   3 import sys
   4 try:
   5     total = sum(int(arg) for arg in sys.argv[1:])
   6     print 'sum =', total
   7 except ValueError:
   8     print 'Please supply integer arguments'

9 lines: Opening files

   1 # indent your Python code to put into an email
   2 import glob
   3 # glob supports Unix style pathname extensions
   4 python_files = glob.glob('*.py')
   5 for fn in sorted(python_files):
   6     print '    ------', fn
   7     for line in open(fn):
   8         print '    ' + line.rstrip()
   9     print

10 lines: Time, conditionals

   1 import time
   2 now = time.localtime()
   3 hour = now.tm_hour
   4 if hour < 8: print 'sleeping'
   5 elif hour < 9: print 'commuting'
   6 elif hour < 17: print 'working'
   7 elif hour < 18: print 'commuting'
   8 elif hour < 20: print 'eating'
   9 elif hour < 22: print 'resting'
  10 else: print 'sleeping'

11 lines: Triple-quoted strings, while loop

   1 REFRAIN = '''
   2 %d bottles of beer on the wall,
   3 %d bottles of beer,
   4 take one down, pass it around,
   5 %d bottles of beer on the wall!
   6 '''
   7 bottles_of_beer = 99
   8 while bottles_of_beer > 1:
   9     print REFRAIN % (bottles_of_beer, bottles_of_beer,
  10         bottles_of_beer - 1)
  11     bottles_of_beer -= 1

12 lines: Classes

   1 class BankAccount(object):
   2     def __init__(self, initial_balance=0):
   3         self.balance = initial_balance
   4     def deposit(self, amount):
   5         self.balance += amount
   6     def withdraw(self, amount):
   7         self.balance -= amount
   8     def overdrawn(self):
   9         return self.balance < 0
  10 my_account = BankAccount(15)
  11 my_account.withdraw(5)
  12 print my_account.balance

13 lines: Unit testing with unittest

   1 import unittest
   2 def median(pool):
   3     copy = sorted(pool)
   4     size = len(copy)
   5     if size % 2 == 1:
   6         return copy[(size - 1) / 2]
   7     else:
   8         return (copy[size/2 - 1] + copy[size/2]) / 2
   9 class TestMedian(unittest.TestCase):
  10     def testMedian(self):
  11         self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
  12 if __name__ == '__main__':
  13     unittest.main()

14 lines: Doctest-based testing

   1 def median(pool):
   2     '''Statistical median to demonstrate doctest.
   3     >>> median([2, 9, 9, 7, 9, 2, 4, 5, 8])
   4     7
   5     '''
   6     copy = sorted(pool)
   7     size = len(copy)
   8     if size % 2 == 1:
   9         return copy[(size - 1) / 2]
  10     else:
  11         return (copy[size/2 - 1] + copy[size/2]) / 2
  12 if __name__ == '__main__':
  13     import doctest
  14     doctest.testmod()

15 lines: itertools

   1 import itertools
   2 lines = '''
   3 This is the
   4 first paragraph.
   5 
   6 This is the second.
   7 '''.splitlines()
   8 # Use itertools.groupby and bool to return groups of
   9 # consecutive lines that either have content or don't.
  10 for has_chars, frags in itertools.groupby(lines, bool):
  11     if has_chars:
  12         print ' '.join(frags)
  13 # PRINTS:
  14 # This is the first paragraph.
  15 # This is the second.

16 lines: csv module, tuple unpacking, cmp() built-in

   1 import csv
   2 
   3 # write stocks data as comma-separated values
   4 writer = csv.writer(open('stocks.csv', 'wb'))
   5 writer.writerows([
   6     ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09),
   7     ('YHOO', 'Yahoo! Inc.', 27.38, 0.33, 1.22),
   8     ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49)
   9 ])
  10 
  11 # read stocks data, print status messages
  12 stocks = csv.reader(open('stocks.csv', 'rb'))
  13 status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'}
  14 for ticker, name, price, change, pct in stocks:
  15     status = status_labels[cmp(float(change), 0.0)]
  16     print '%s is %s (%s%%)' % (name, status, pct)

18 lines: 8-Queens Problem (recursion)

   1 BOARD_SIZE = 8
   2 
   3 def under_attack(col, queens):
   4     left = right = col
   5     for r, c in reversed(queens):
   6         left, right = left-1, right+1
   7         if c in (left, col, right):
   8             return True
   9     return False
  10 
  11 def solve(n):
  12     if n == 0: return [[]]
  13     smaller_solutions = solve(n-1)
  14     return [solution+[(n,i+1)]
  15         for i in range(BOARD_SIZE)
  16             for solution in smaller_solutions
  17                 if not under_attack(i+1, solution)]
  18 for answer in solve(BOARD_SIZE): print answer

20 lines: Prime numbers sieve w/fancy generators

   1 import itertools
   2 
   3 def iter_primes():
   4      # an iterator of all numbers between 2 and +infinity
   5      numbers = itertools.count(2)
   6 
   7      # generate primes forever
   8      while True:
   9          # get the first number from the iterator (always a prime)
  10          prime = numbers.next()
  11          yield prime
  12 
  13          # this code iteratively builds up a chain of
  14          # filters...slightly tricky, but ponder it a bit
  15          numbers = itertools.ifilter(prime.__rmod__, numbers)
  16 
  17 for p in iter_primes():
  18     if p > 1000:
  19         break
  20     print p

21 lines: XML/HTML parsing (using Python 2.5 or third-party library)

   1 dinner_recipe = '''<html><body><table>
   2 <tr><th>amt</th><th>unit</th><th>item</th></tr>
   3 <tr><td>24</td><td>slices</td><td>baguette</td></tr>
   4 <tr><td>2+</td><td>tbsp</td><td>olive oil</td></tr>
   5 <tr><td>1</td><td>cup</td><td>tomatoes</td></tr>
   6 <tr><td>1</td><td>jar</td><td>pesto</td></tr>
   7 </table></body></html>'''
   8 
   9 # In Python 2.5 or from http://effbot.org/zone/element-index.htm
  10 import xml.etree.ElementTree as etree
  11 tree = etree.fromstring(dinner_recipe)
  12 
  13 # For invalid HTML use http://effbot.org/zone/element-soup.htm
  14 # import ElementSoup, StringIO
  15 # tree = ElementSoup.parse(StringIO.StringIO(dinner_recipe))
  16 
  17 pantry = set(['olive oil', 'pesto'])
  18 for ingredient in tree.getiterator('tr'):
  19     amt, unit, item = ingredient
  20     if item.tag == "td" and item.text not in pantry:
  21         print "%s: %s %s" % (item.text, amt.text, unit.text)

28 lines: 8-Queens Problem (define your own exceptions)

   1 BOARD_SIZE = 8
   2 
   3 class BailOut(Exception):
   4     pass
   5 
   6 def validate(queens):
   7     left = right = col = queens[-1]
   8     for r in reversed(queens[:-1]):
   9         left, right = left-1, right+1
  10         if r in (left, col, right):
  11             raise BailOut
  12 
  13 def add_queen(queens):
  14     for i in range(BOARD_SIZE):
  15         test_queens = queens + [i]
  16         try:
  17             validate(test_queens)
  18             if len(test_queens) == BOARD_SIZE:
  19                 return test_queens
  20             else:
  21                 return add_queen(test_queens)
  22         except BailOut:
  23             pass
  24     raise BailOut
  25 
  26 queens = add_queen([])
  27 print queens
  28 print "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens)

Hi, I started this page in May 2007, and I provided the first 10+ or so examples (which may have changed since then). -- SteveHowell

All code on this page is open source, of course, with the standard Python license.

Minor cleanups are welcome, but if you want to do major restructuring of this page, please run them by the folks on the Python mailing list, or if you are impatient for a response, please just make your own copy of this page. Thanks, and I hope this code is useful for you!

Some goals for this page:


Examples for discussion

Mensanator, let's agree to disagree. I saw your example on comp.lang.python, but I gently ignored it. Your example was not vetoed, but I also did not see any strong support for it.

It's easy to resolve this conflict. Please clone this page, and you can make it better than mine. I'm leaving your example here for a few days, but I intend to remove it.

Your point about foolishly counting lines is well received, apart from the "foolish" dig. Again, it's easy to fix my foolishness by simply creating your own page. You're welcome to borrow any code that you like from this page. If you think the whole page needs to be better thought, needs more commentary, etc., then that's the perfect reason to create your own version. -- Steve

   1 def partition_generator(depth, width): # a generator (iterates comb(depth - 1, width - 1))
   2     def move_col(c):                   # move item left 1 bin
   3         sv[c-1] += 1
   4         sv[c] -= 1
   5     def find_c():                      # find rightmost bin with >1 items
   6         i = -1
   7         while i < 0:
   8             if sv[i] > 1:
   9                 return i
  10             i -= 1
  11     def rollover(c):                   # move item and swap bins
  12         move_col(c)
  13         sv[-1] = sv[c]
  14         sv[c] = 1
  15     if depth < width:                  # must have at least as many bins as items
  16         print 'depth', depth, 'must be greater than width', width
  17         return                         # invalid depth, terminate generator
  18     max_element = depth - width + 1    # largest amount held by a bin
  19     sv = [1 for i in range(width)]     # list comprehension: init all bins to 1
  20     sv[-1] = max_element               # start with max_element in right bin
  21     yield sv                           # this initial condition is 1st partition
  22     while sv[0] < max_element:         # terminate when all moveable items in leftmost bin
  23         c = find_c()                   # find rightmost bin that has a moveable item
  24         if c < -1:                     # if not THE rightmost bin, rollover
  25             rollover(c)
  26             yield sv                   # and return as next partition
  27         else:                          # otherwise, just need to move item
  28             move_col(c)
  29             yield sv                   # and return as next partition
  30 for p in partition_generator(6, 4): print p

The program below is more appropriate in a tutorial on truth/falseness IMHO than as an example of a simple program. I'm not saying all the examples above are perfect, but I think this is a little too language-lawyerly for the fifth program. -- Steve


5 lines: Truth

   1 for value in [True, False, 1, 0, 'foo', '', [0], [], (0,), (), {'a':1}, {}, None]:
   2     if value:
   3         print repr(value), 'evaluates to True'
   4     else:
   5         print repr(value), 'evaluates to False'


CategoryLanguage

Unable to edit the page? See the FrontPage for instructions.