Python Tutorial

Thursday, August 26, 2010

Python Unzip a tar file

'''
   This class use for Unzip a tar file
'''

import os
import tarfile
import sys

class UnZipFolder():
    def __init__(self, location):
        self.location=location
        # Set output directory here
        self.outputLocation="C:/"

    def decompress(self):
        try:
            if os.path.exists(self.location):
                decompressTar = tarfile.open(self.location)
                decompressTar.extractall(self.outputLocation)
                decompressTar.close()
                print "Extracted"
            else:
                print "No Such Folder"
        except:
            print str(sys.exc_info())
            
if __name__=='__main__':
    # Set input directory here
    location="C:/test.tar"
    unZipFolder=UnZipFolder(location)
    unZipFolder.decompress()

python zip a folder or file



Zip a folder or file is very easy in python. You need to set variable location by your file or folder location.

'''
    This class use for zip a folder
    - Create a folder named "testFolder" on C drive or reset the location
'''

import os
import tarfile
import sys

class ZipFolder():
    # Constructor of ZipFolder
    def __init__(self, location):
        self.location=location

    def makeCompress(self):
        try:
            if os.path.exists(self.location):
                compressTar = tarfile.open(self.location+".tar", "w:gz")
                compressTar.add(self.location)
                compressTar.close()
                print "Compress complete ",self.location
            else:
                print " (ZipFile)No Such Folder ",self.location 
        except:
            print str(sys.exc_info())

if __name__=='__main__':
    location="C:/testFolder"
    zipFolder=ZipFolder(location)
    zipFolder.makeCompress()

python multidimentional array

'''
   This code use python array syntax
'''
# declare a 2D array
array = [ [0 for col in range(3) ] for row in range(3)]

print array
# update array
array[1][1]=5
print array



Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 5, 0], [0, 0, 0]]

python set

'''
   This code use python set syntax
   - Set always holds unique data/object
'''
data=[7,1,2,3,1,4]
setA=set(data)
# Unique numbers of setA
print "setA: ",setA

data=[9,0,5,3,2,9]
setB=set(data)
# Unique numbers of setB
print "SetB: ",setB

'''
   All elements either in setA or setB
'''
setC=setA | setB
print setC

'''
   All elements both in setA and setB
'''
setC=setA & setB
print setC

'''
   All elements in setA or setB, but not both
'''
setC=setA ^ setB
print setC

'''
   All elements in setA but not in setB
'''
setC=setA - setB
print setC



Output:
setA:  set([1, 2, 3, 4, 7])
SetB:  set([0, 9, 2, 3, 5])
set([0, 1, 2, 3, 4, 5, 7, 9])
set([2, 3])
set([0, 1, 4, 5, 7, 9])
set([1, 4, 7])

python stack data structure


Stack is very important data structure. Here a simple stack implementation.
All source code available on github

 #DA_Stack.py

class MyStack():
    stack = []
    max_stack_size = 2

    def push(self, value):
        if len(self.stack) == self.max_stack_size:
            return "Overflow"
        self.stack.append(value)
    def pop(self):
        if(len(self.stack)):
            return self.stack.pop()
        return "Underflow"

myStack = MyStack()
myStack.push(2)
myStack.push(5)
print myStack.stack
print myStack.push(6)
print myStack.stack
print myStack.pop()
print myStack.stack
print myStack.pop()
print myStack.pop()
print myStack.stack



Output:
[2, 5]
Overflow
[2, 5]
5
[2]
2
Underflow
[]

python queue data structure


Queue implementation using collections.deque.
All source code available on github

#DA_Queue.py

from collections import deque
class MyQueue:
    queue = deque()

    def enqueue(self, value):
        self.queue.append(value)
    def dequeue(self):
        if len(self.queue):
            return self.queue.popleft()
        print "Impossible"


myQueue = MyQueue()
myQueue.enqueue(8)
myQueue.enqueue(4)
print myQueue.queue
myQueue.dequeue()
myQueue.dequeue()
print myQueue.queue
myQueue.dequeue()
print myQueue.queue


Output:
deque([8, 4])
deque([])
Impossible
deque([])

Python list

'''
   This Code use python list syntax
'''

myList=list()

myList.append(1)
myList.append(5)
myList.append(1)
myList.append(2)
myList.append(3)

'''
   Access list data
'''
for i in range(0,len(myList)):
    print myList[i]

'''
   Counting occurance of a data/object
'''
print "myList.count(1) ",myList.count(1)

'''
   Remove a list object
   - remove only first occured value
'''
myList.remove(1)
print myList

myList.append(1)

'''
   Reverse objects of list
'''
print myList
myList.reverse()
print myList

'''
   Find a data/object to list
   - return the lowest index of object
   - raise exception if data not found
'''
print "myList.index(5): ",myList.index(5)

'''
   Sort objects of list
'''

myList.sort()
print myList

'''
   Insert a data/object into list
'''
myList.insert(2,100)
print myList






Output:
1
5
1
2
3
myList.count(1)  2
[5, 1, 2, 3]
[5, 1, 2, 3, 1]
[1, 3, 2, 1, 5]
myList.index(5):  4
[1, 1, 2, 3, 5]
[1, 1, 100, 2, 3, 5]

Friday, August 20, 2010

python Object-oriented programming : Use existing object

'''
   This code use python class syntax
     - save this class named "MyClass.py" 
'''
class MyClass():
    # Class constructor
    def __init__(self,data):
        self.data=data

    def showSring(self):
        print self.data

    def reverseString(self):
        return self.data[::-1]

if __name__=='__main__':
    myClass=MyClass("Life is very easy Python")
    myClass.showSring()
    print myClass.reverseString()





'''
   This code use class object
     -save this code named "AnyName.py"
'''
import MyClass

class MyClassUser():
    def __init__(self,data):
        self.data=data
        self.myClass=MyClass.MyClass(self.data)
        
    def callMyClass(self):
        self.myClass.showSring()
        print self.myClass.reverseString()
        
if __name__=="__main__":
    myClassUser=MyClassUser("Life is very easy with Python")
    myClassUser.callMyClass()




Must save class "Myclass.py" and "AnyName.py" in same folder then run "AnyName.py"



Output:
Life is very easy with Python
nohtyP htiw ysae yrev si efiL

python Object-oriented programming

'''
   This code use python class syntax
     - save this class named "MyClass.py" 
'''
class MyClass():
    # Class constructor
    def __init__(self,data):
        self.data=data

    def showSring(self):
        print self.data

    def reverseString(self):
        return self.data[::-1]

if __name__=='__main__':
    #declare object
    myClass=MyClass("Life is very easy Python")
    #use object
    myClass.showSring()
    print myClass.reverseString()




Output:
Life is very easy Python
nohtyP ysae yrev si efiL

python import class

'''
   saved this class named "A.py"
'''
def printStringNTimes(s,n):
    for i in range(0,n):
        print s

def stringReverse(s):
    return s[::-1]

def stringLength(s):
    return len(s)




'''
   This code use class import syntax
    - must import class "A"
    - Not need to create any object, just use all functionality of class
    - call you desired function by "classname.finction name" 
         (example : A.printStringNTimes("Python",5))
    - put class A.py and current class on same folder
'''
import A
'''
   print a string n times
'''
A.printStringNTimes("Life is very easy with Python",5)
'''
   get length os a string
'''
print "Length :",A.stringLength("Life is very easy with Python")
'''
   reverse a string
'''
print "string reverse :",A.stringReverse("nohtyP htiw ysae yrev si efiL")





Output:
Life is very easy with Python
Life is very easy with Python
Life is very easy with Python
Life is very easy with Python
Life is very easy with Python
Length : 29
string reverse : Life is very easy with Python

python get all files of desired type from a directory

'''
   This code use for get all files of desired type from a directory
'''
import os

directory="C:/inputFolder/"
fileType=".doc"
files=[]
files=os.listdir(directory)
fileCounter=0
for fileName in files:
    if fileName.endswith(fileType):
        fileCounter=fileCounter+1
        print fileName
if fileCounter==0:
    print "No doc file found at ",directory

python exception handling

'''
   This code use exception handling syntax
'''

directory ="C:/pythonInputFile.txt"
try:
    f=open(directory,'r')
    print f.read()
    f.close()
except:
    print "File not found/problem on reading file"
finally:
    print "It always works"

python remove/delete file or folder

'''
   This code use for remove a file/folder
'''
import os
import sys
import shutil

def deleteFileOrFolder(directory):
    if os.path.exists(directory):
        try:
            if os.path.isdir(directory):
                # delete folder
                shutil.rmtree(directory)
            else:
                # delete file
                os.remove(directory)
        except:
            print "Ecxeption ",str(sys.exc_info())
    else:
        print "not found ",directory

'''
   Function call
'''
#directory="C:/pythonFile.txt"
directory="C:/inputFolder/"
directory=deleteFileOrFolder(directory)





Output:
Check current directory

python remove/delete file

'''
   This code use for remove a file
'''
import os
import sys

directory="C:/pythonInputFile.doc"
if os.path.exists(directory):
    try:
        os.remove(directory)
    except:
        print "Exception: ",str(sys.exc_info())
else:
    print 'File not found at ',directory




Output:
Check current directory

python rename a file

'''
   This code use for rename a file
      - also change the file format
      - example of exception handling
'''
import os
import sys

currentDirectory="C:/pythonFile.txt"
if os.path.exists(fileDirectory):
    try:
        newFileName="pythonInputFile.doc"
        newDirectory=fileDirectory[0:fileDirectory.rfind("/")+1]+newFileName
        print newDirectory
        os.rename(currentDirectory,newDirectory)
    except:
        print "Exception: ",str(sys.exc_info())
else:
    print "File Not found"





Output:
Check current directory folder

Thursday, August 19, 2010

python file seek

'''
   This code use python file syntax
'''
'''
   Read data from file seek position
        pointer seek n'th byte, then start read data
'''
directory="C:/pythonFile.txt"
n=10
f=open(directory,'r')
f.seek(n)
for line in f.readlines():
    print line
f.close()




Output:



python calender

import calendar
'''
   This code use python calender class syntax
'''

print calendar.monthcalendar(2010,8)
print calendar.month(2010,8)





Output:

[[0, 0, 0, 0, 0, 0, 1], [2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15], 
[16, 17, 18, 19, 20, 21, 22], [23, 24, 25, 26, 27, 28, 29], 
[30, 31, 0, 0, 0, 0, 0]]
    August 2010
Mo Tu We Th Fr Sa Su
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 


python : time

'''
   This code use python time class syntax
'''
import time

'''
   return current date and time
'''
print "time.ctime() ",time.ctime()
'''
   Return current CPU time
'''
print "time.clock() ",time.clock()





Output:
time.ctime()  Thu Aug 19 14:46:02 2010
time.clock()  107.072719637

python file operation

'''
   This code use python file read/write syntax
'''

directory="C:/pythonFile.txt"

'''
   Open file in write mode
'''
f=open(directory,'w')
f.write("Life is easy with Python")
f.close()

'''
   Open file for writeing data in binary format
'''
f=open(directory,'wb')
f.write("Life is easy with Python")
f.close()


'''
   Open file in append mode
'''
f=open(directory,'a')
f.write("Life is easy with Python")
f.close()


'''
   Read data from file
'''
f=open(directory,'r')
for line in f.readlines():
    print line
f.close()






Output:

Check "C:" drive

python:Number

import math

'''
   This code use python math class syntax
'''
n=2.5
'''
   return the smallest integer not less than n
'''
print "math.ceil(2.5) ",math.ceil(n)
'''
   return the largest integer less than x
'''
print "math.floor(2.5) ",math.floor(n)
'''
   return value of n^m 
'''
n=2
m=3
print "math.pow(2,3) ",math.pow(n,m)
'''
   compare two number
      return 0 in n==m
      return 1 if n>m
      return -1 if n0 
'''
n=100
print "math.log10(100) ",math.log10(n)
'''
   return natural logarithm of n, n>0
'''
print "math.log(100) ",math.log(n)
'''
   return absulate value of floating number
'''
print "math.fabs(-2.5) ",math.fabs(-2.5)
'''
   get maximum and minimum number from a array
'''
myArray=[]
myArray.append(5)
myArray.append(1)
myArray.append(6)
myArray.append(2)
print "max(myArray) ",max(myArray)
print "min(myArray) ",min(myArray)
'''
   return exponential of n(e^n)
'''
print "math.exp(5) ",math.exp(5)
'''
   round n to m digit from decimal point 
'''
n=math.pi
m=5
print "round(3.14159265359,5) ",round(n,m)
'''
   python random number
'''
import random
print "random.random() ",random.random()
'''
   random number from a array
'''
print "random.choice(myArray) ",random.choice(myArray)
'''
   random number in a range
'''
print "random.randint(1,100) ",random.randint(1,100)
'''
   python trigonometric function
'''
n=30
'''
   return sin of n in radian
'''
print "math.sin(30) ",math.sin(n)
'''
   return cos of n in radian
'''
print "math.cos(30) ",math.cos(n)
'''
   return tan of n in radian
'''
print "math.tan(30) ",math.tan(n)
n=1
'''
   return arc sin of n in radian
'''
print "math.asin(1) ",math.asin(n)
'''
   return arc cos of n in radian
'''
print "math.acos(1) ",math.acos(n)
'''
   return arc tan of n in radian
'''
print "math.atan(1) ",math.atan(n)
'''
   conver n radian to degree
'''
n=5
print "math.degrees(5) ",math.degrees(n)
'''
   conver n degree to radian
'''
print "math.radians(5) ",math.radians(n)



Output:
math.ceil(2.5)  3.0
math.floor(2.5)  2.0
math.pow(2,3)  8.0
cmp(2,3)  -1
math.sqrt(25)  5.0
math.pi  3.14159265359
math.log10(100)  2.0
math.log(100)  4.60517018599
math.fabs(-2.5)  2.5
max(myArray)  6
min(myArray)  1
math.exp(5)  148.413159103
round(3.14159265359,5)  3.14159
random.random()  0.32172452922
random.choice(myArray)  1
random.randint(1,100)  82
math.sin(30)  -0.988031624093
math.cos(30)  0.154251449888
math.tan(30)  -6.40533119665
math.asin(1)  1.57079632679
math.acos(1)  0.0
math.atan(1)  0.785398163397
math.degrees(5)  286.478897565
math.radians(5)  0.0872664625997

Wednesday, August 18, 2010

python function,method,module

'''
    This code use function syntax
'''

def getMaxValue(data):
    '''
       this method use for get maximum data of a integer array
    '''
    return max(data)

def getMinValue(data):
    '''
       this method use for get minimum data of a integer array
    '''
    return min(data)

def sortData(data):
    '''
       this method use for sort data of a integer array
    '''
    data.sort()
    return data

myArray=[]
myArray.append(1)
myArray.append(2)
myArray.append(6)
myArray.append(3)
'''
   call function
'''
print getMaxValue(myArray)
print getMinValue(myArray)
print myArray
print sortData(myArray)



Output:
6
1
[1, 2, 6, 3]
[1, 2, 3, 6]

python array example

'''
    This code use array syntax
'''
myArray=[]
myArray.append(1)
myArray.append(2)
myArray.append(6)
myArray.append(3)

print "Array length ",len(myArray)

'''
   access array data
'''
print myArray
for n in myArray:
    print n
for i in range(0,len(myArray)):
    print myArray[i]

'''
   sort array
'''
myArray.sort()
print myArray



Output:
Array length  4
[1, 2, 6, 3]
1
2
6
3
1
2
6
3
[1, 2, 3, 6]

python map

'''
    This code use python map syntax
'''
myMap={}
myMap["Life"]=1
myMap["is"]=1
myMap["easy"]=1
myMap["Python"]=1
'''
   check map key
'''
if myMap.has_key("Python"):
    print "Python found"
'''
   map length
'''
print len(myMap)
'''
   map to tuple
'''
myTuple=tuple(myMap)
print myTuple
'''
   access map
'''
for n in myMap:
    print n
print myMap



Output:
Python found
4
('Python', 'Life', 'is', 'easy')
Python
Life
is
easy
{'Python': 1, 'Life': 1, 'is': 1, 'easy': 1}

python tuple

'''
    This code use tuple syntax
    tuple have no append,remove,index method
'''
mytuple=("i","am","the",1)
print mytuple
print mytuple[0]
print mytuple[-1]
print "tuple length ",len(mytuple)

'''
   print tuple data
'''
for n in mytuple:
    print n
print mytuple[0:2]

    
'''
   compare two tuple
   return 0 if two tuple are equal 
'''
newtuple=mytuple
print cmp(mytuple,newtuple)

'''
   get max data from a tuple
'''
integertuple=(1,2,6,3)
print max(integertuple)

'''
    list array to tuple
'''
listArray=[]
listArray.append(2)
listArray.append(5)
listArray.append(3)
newtuple=tuple(listArray)
print newtuple



Output:
('i', 'am', 'the', 1)
i
1
tuple length  4
i
am
the
1
('i', 'am')
0
6
(2, 5, 3)

Python : Dictionary

'''
    This code use dictionary syntax
'''
myDictionary={"name":"anyName","age":500,"subject":"CSE"}

'''
   insert new data into dictionary
'''
myDictionary["address"]="dhaka"
'''
    access index of a dictionary
    if there is no data it will raise an exception
'''
print myDictionary["age"]

'''
   find dictionary length
'''

print "Dictionary Length : ",len(myDictionary)

'''
   access all dictionary data
'''
for n in myDictionary:
    print n ," ", myDictionary[n]

myDictionary["temp"]="data"
print myDictionary
'''
   delete dictionary item
'''
del myDictionary["temp"]
print myDictionary

'''
   compare two dictionary
   if two dictionary have same content return 0
'''
newDictionary=myDictionary
print cmp(myDictionary,newDictionary)
'''
   get all dictioany data as a tupple
'''

myTupple=()
myTupple=myDictionary.items()
'''
   syntax of access tupple
'''
print myTupple
print myTupple[0]
print myTupple[0][0]
'''
   clear dictionary
'''
myDictionary.clear()

print myTupple



Output:

500
Dictionary Length :  4
age   500
address   dhaka
name   anyName
subject   CSE
{'age': 500, 'address': 'dhaka', 'name': 'anyName', 'temp': 'data', 'subject': 'CSE'}
{'age': 500, 'address': 'dhaka', 'name': 'anyName', 'subject': 'CSE'}
0
[('age', 500), ('address', 'dhaka'), ('name', 'anyName'), ('subject', 'CSE')]
('age', 500)
age
[('age', 500), ('address', 'dhaka'), ('name', 'anyName'), ('subject', 'CSE')]

while loop

'''
    this code use python while loop syntax
'''
i=0
while i<5:
    print i
    i=i+1

print
i=0
while i<10:
    print i
    i=i+2


Output:
0
1
2
3
4

0
2
4
6
8

python: for loop

'''
    this code use python for loop syntax
'''
for i in range(0,3):
    print i

print "xrange"
for i in xrange(0,3):  # xrange is memory efficient
    print i

print "steps"
for i in range(0,10,3):
    print i



Output:
0
1
2
xrange
0
1
2
steps
0
3
6
9

python If else

'''
    This code use python if else syntax
'''
n=16
if n%2==0:
    print n," is a even number"
elif n%5==0:
    print n," is divisible by 5"
else:
    print n," is a odd number"

if n%2==0 and n%4==0:
    print n," is divided by both 2 and 4"

if n%2==0 or n%6==0:
    print n," is divided by 2 or 6"


Output:
16  is a even number
16  is divided by both 2 and 4
16  is divided by 2 or 6

python count occurrence of a string

'''
   this code is use for count occurrence of string
'''
data="Life is very very easy with Python"
print data.count("very")
print data.count("Python")



Output:
2
1

python String padding or adjust

'''
   this code is use for padding a string
'''
data="Life is very easy with Python"
'''
   padding from left
'''
print data.ljust(35,'#')
'''
   padding from right
'''
print data.rjust(35,'#')
'''
   padding from both sides
'''
print data.center(35,'#')



Output:
Life is very easy with Python######
######Life is very easy with Python
###Life is very easy with Python###

python find alphabetically maximum and minimum characters from string

'''
   this code is use for find alphabetically maximum and minimum characters
'''
data="LifeIsVeryEasyWithPython"
print max(data)
print min(data)



Output:
y
E

python String reverse

'''
   this code is use for reverse a string
'''
data="nohtyP htiw ysae yrev si efiL"
print data[::-1]



Output:
Life is very easy with Python

python find a string in another string

'''
    This code use for find one string in another string
    return the index from where string is found, otherwise return -1
'''
data="Life is very easy is with Python"

print data.find("is")
print data.rfind("is")
'''
   find in a range(startIndex,endIndex)
'''
print data.find("is",0,5)
print data.find("is",0,10)

'''
   find from last
'''
print data.rfind("is",0,10)
print data.rfind("is",0,5)



Output:
5
18
-1
5
5
-1

python print string fixed length

'''
   This code use for print string fixed length
'''
data="Life is very easy with Python"
print data[0:4]
'''
   print from where first "Py" found
'''
print data[data.find("Py"):]
'''
   print last six character
'''
print data[-6:]
print data[len(data)-6:len(data)]
'''
   from last six characters ignore last two characters
'''
print data[-6:-2]



Output:
Life
Python
Python
Python
Pyth

Tuesday, August 17, 2010

python String lower/upper conversion

'''
    This code is use for lower to upper/upper to lower conversion
'''
data="Life is VERY EASY with Python"
print data
data=data.lower()
print data
data=data.upper()
print data



Output:
Life is VERY EASY with Python
life is very easy with python
LIFE IS VERY EASY WITH PYTHON

python String to integer

'''
   this code is use for convert string to integer
   Check also type of data
'''
data="123"
number=int(data)
print data
print type(data)
print number
print type(number)



Output:
123
< type 'str'>
123
< type 'int' >

python String replace, replcerange

'''
    This code is use for string replace
'''
data="Life is very hard with Python"
print data
data=data.replace("hard","easy")
print data



Output:
Life is very hard with Python
Life is very easy with Python

python String Array

'''
    This code use string array syntax
'''
words=[]
words.append("Life")
words.append("is")
words.append("very")
words.append("easy")
words.append("with")
words.append("Python")

for word in words:
    print word

wordLed=len(words)
for i in range(0,wordLed):
    print words[i]

print words



Output:
Life
is
very
easy
with
Python
Life
is
very
easy
with
Python
['Life', 'is', 'very', 'easy', 'with', 'Python']

python String Strip

'''
    This code is use for strip a string/line
'''
data = " Life is very easy with Python   "
print data
data=data.strip()
print data
data = "  Life is very easy with Python   "
'''
    Remove only trailing space
'''
data=data.rstrip()
print data
'''
    Remove only leading space
'''
data=data.lstrip()
print data
data=",,,,Life is very easy with Python,,,,,"
print data
'''
    remove leading and trailing commas
'''
data=data.strip(",")
print data



Output:
Life is very easy with Python   
Life is very easy with Python
  Life is very easy with Python
Life is very easy with Python
,,,,Life is very easy with Python,,,,,
Life is very easy with Python

python String length

'''
   This code show example how to find string length
'''
data = "  Life is very easy with Python   "

dataLen=len(data)
print dataLen

data=data.strip()

dataLen=len(data)
print dataLen



Output:
34
29

python String Split

'''
    This code is use for split a string
'''
data = " Life#is#very#easy#with#Python  "
data=data.strip()
words = []
words=data.split("#")
print words



Output:
['Life', 'is', 'very', 'easy', 'with', 'Python']

python input

'''
   This code use for python input
'''

data = raw_input("Enter a number: ")
'''
    Now data is a string
    You need to type cast for making this string to integer
'''
print "The number is: ", data

Install Python

Download python from:
python
Download pythonWin form:
pythonWin

pythonWin run using python. It has very good coding interface and with debugging facilities.



python Hello World

print "Life is very easy with Python"



Output:
Life is very easy with Python