Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Python: How to create Power function

def power(x, n):
    if n == 0:
        return 1
        return x * power(x, n-1)
print power(2,8) # 256

Python: read the entire contents of a file at once

myFile = "c:/test.txt"
#Read entire file into a buffer
buffer = "buffer contains:
buffer += open(myFile, 'rU').read()
# show file's content

Python: apply function to variable

def multiply(x, y):
  return x * y
param = (6, 7)
print param
# apply multiply function to sequence
print apply(multiply, param)

Python: Check if a string begins or ends with a specific prefix or suffix

import os
for f in os.listdir(myDir): # list current dir
    if f.endswith('.py'):
        print "Python file: " + f
    elif f.endswith(

Python: How to Define simple function in Python

def test(name, email, age=18):
    print "%s/%s/%d" % (name, email, age)
if __name__ == '__main__': test("jhon deer", "demo@gmail.com")

Python: Check if all of the numbers are positive

numbers=[1, 5, 7, 9,]
if all(x>0 for x in numbers):
    print "all of the numbers are positive"
    print "some of the numbers are not positi

Python: How to return a lambda function

def produit(x):
     return (lambda y: x * y)
calcul = produit(12) 
print calcul(8)#  96

Python: Using map to Apply a Function to Sequence Items

def sum(x, y):
    return x + y
# Apply  function 'sum'  to numbers between 1 and 10
print map(sum, [1, 2, 3, 4], [5, 6, 7 ,8])
# apply lambda to t

Python-List: How to remove duplcate

def duplicateRemover(sequence):
    for i in sequence:
        if i not in liste:
    return liste
# main

Python: calculate the numbers in the Fibonacci series

def fibonacci(number):
    if number<2:
        return 1
    return fibonacci (number - 1) + fibonacci(number - 2)
for x in range(11):

Python: How to check if a default parameter value being used

def demo(x=None):
     if x is None:
         print "no argument passed"
         print "thank you"

Python: basic HTTP authentication Example

import urllib2
x = urllib2.HTTPPasswordMgrWithDefaultRealm( )
x.add_password(None, 'http://user.com/login.php', 'myusername', 'mypassword')
auth =

Python: Loading an XML Document

from xml.dom import minidom
#Open XML document
DOMTree = minidom.parse('c:/user.xml')
#Print XML contents
print DOMTree.toxml()

Python: Creating Recursive Functions

def factorial( nombre ):
   if nombre <= 1:
      return 1
      return nombre * factorial( nombre - 1 )  # recursive call
# calculate the

Python: Using filter to Remove Sequence Items Conditionally

def isEven(number):
    return number % 2==0
# Removes odd numbers between 1 and 10 and return the even numbers
print filter(isEven, range(10))
# D