<?php include 'HEADER.php' ?>

<h1>Python Recipes</h1>

<h2>any() and all()</h2>

<p>The any() and all() functions were introduced in Python 2.5.</p>

<code class="prettyprint">
#!/usr/bin/env python

numbers = [1,10,100,1000,10000]
if any(number == 10 for number in numbers):
    print '10 found.'

numbers = [1,2,3,4,5,6,7,8,9]
if all(number &lt; 10 for number in numbers):
    print 'All number are under 10.'
</code>

<h2>Loop with enumerate()</h2>

<code class="prettyprint">
#!/usr/bin/env python

for i, color in enumerate(['red', 'blue', 'green']):
    print i, color
</code>

<h2>Loop dictionary with keys &amp; values</h2>

<code class="prettyprint">
#!/usr/bin/env python

monsters = {'skeleton' : '1 HD', 'troll' : '6 HD'}

for key, value in monsters.iteritems():
    print key, value
</code>

<h2>Connect to a MySQL database</h2>

<code class="prettyprint">
#!/usr/bin/env python

import MySQLdb

try:
    conn = MySQLdb.connect(
        host = 'myhost',
        user = 'myusername',
        passwd = 'mypassword',
        db = 'mydbname'
    )
    cursor = conn.cursor()
    query = "SELECT alpha, beta FROM foo;"
    cursor.execute(query)
    rows = cursor.fetchall()
    for row in rows:
        print "%s, %s" % (row[0], row[1])
    print cursor.rowcount + ' rows returned.'

except MySQLdb.Error, e:
     print "Error %d: %s" % (e.args[0], e.args[1])
     sys.exit(1)

finally:
    if cursor:
        cursor.close()
    if conn:
        conn.close()
</code>

<h2>Regex on a Unicode file</h2>

<code class="prettyprint">
#!/usr/bin/env python

import codecs
import unicodedata
import re

myfile = 'myfile.txt'
updates = []

try:
    f = codecs.open(myfile, encoding='utf-16')
    for line in f:
        # Matching unicode is annoying.
        line = unicodedata.normalize('NFKD', line).encode('ascii', 'ignore')
        if re.match('\w{3,}\-*\w*\s+[0-9]+', line):
            updates.append(line.split())
except IOError, e:
    print "Error %d: %s" % (e.args[0], e.args[1])
    sys.exit(1)
finally:
    f.close()
</code>

<?php include '../FOOTER.php' ?>
