Python Tutorial

Thursday, December 12, 2013

Context manager API

Python file object support the context manager API to make it easy to ensure they are closed after all reading or writing is done

with open('z.txt', 'r') as f:
    data = f.read()
    print data

Output:
File content

Python enumerate

enumerate returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence.
a = ["Python","easy"]

for i, n in enumerate(a):
    print i, n


Output:
0 Python
1 easy

Python case insensitive dictionary

class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        key = key.lower()
        dict.__setitem__(self, key, value)

    def __getitem__(self, key):
        key = key.lower()
        return dict.__getitem__(self, key)

d = CaseInsensitiveDict()
d["Python"] = "Easy"
print d["PYTHON"]
print d["python"]

Output:
Easy
Easy

Monday, December 9, 2013

Python for loop with else clauses


Python for loop with else condition is very interesting feature. This types of feature makes code more readable and pythonic. Lets see an example.

a = [1, 3, 51, 7, 8]
print a
k = 5
for n in a:
    if n%k==0:
        print "Divisible by",k,"found"
        break
else:
    # This line will working if for loop terminate normally
    print "Divisible by",k,"not found"

print
a = [1, 3, 5, 7, 8]
print a
k = 5
for n in a:
    if n%k==0:
        print "Divisible by",k,"found"
        break
else:
    # This line will working if for loop terminate normally
    print "Divisible by",k,"not found"


Output:
[1, 3, 51, 7, 8]
Divisible by 5 not found

[1, 3, 5, 7, 8]
Divisible by 5 found

Wednesday, November 20, 2013

Tastypie: Django REST API framework

Tastypie is an webservice API framework for Django. It provides a convenient, yet powerful and highly customizable, abstraction for creating REST-style interfaces.
http://django-tastypie.readthedocs.org/en/latest/

Tornado web practical examples


http://tmp.devcharm.com/pages/tornado-examples

Friday, November 15, 2013

Python sqlite example: executemany, search

Previous example

Python sqlite insert many data in a single query.

import sqlite3

connection = sqlite3.connect("sqlite_sample.db")
cursor=connection.cursor()

# create new table
cursor.execute("CREATE TABLE IF NOT EXISTS student (id INT, name TEXT, score INT)")

data =[
    (1, "Joey", 25),
    (2, "Mac", 65),
    (3, "Fin", 85),
    (4, "Jac", 45),
]

cursor.executemany("INSERT INTO student VALUES (?,?,?)",data)
cursor.execute("INSERT INTO student VALUES (?,?,?)", (5, "Roy", 77) )

# commit the changes
connection.commit()

# Fetching data
cursor.execute("SELECT * FROM student")
for row in cursor:
    print "id: ",row[0]," name ",row[1]," score",row[2]

print "Search example: "
data = ("Mac", 20)
cursor.execute("SELECT  * FROM student WHERE name = ? AND score > ?", data)
for row in cursor:
    print "id: ",row[0]," name: ",row[1]," score: ",row[2]

connection.close()

Output:
id:  1  name  Joey  score 25
id:  2  name  Mac  score 65
id:  3  name  Fin  score 85
id:  4  name  Jac  score 45
id:  5  name  Roy  score 77
Search example:
id:  2  name:  Mac  score:  65