Jun 13, 2013

Sorting The List Elements in Python

The list elements can be sorted using sort() method or sorted() function. This code shows you the difference between list's sort() method and sorted() function.
>>> # using sort() method
>>> li = [99, 28, 45, 30, 40]
>>> li.sort()
>>> li
[28, 30, 40, 45, 99]
>>> 
>>> # using sorted() function
>>> originalList = [99, 28, 45, 30, 40]
>>> sortedList = sorted(originalList)
>>> sortedList
[28, 30, 40, 45, 99]
>>> originalList
[99, 28, 45, 30, 40]
>>>

Jun 7, 2013

Creating Recursive Function in Python

This example code shows you how to create a recursive function in Python.
>>> def factorial(num):
          if num < 0:
             print("ERROR: Invalid parameter value")
             return
          elif num == 0 or num == 1:
             return 1
          else:
             return num * factorial(num-1)
 
>>> factorial(4)
24
>>> factorial(5)
120
>>>

May 31, 2013

Defining a Class Variable in Python

Class variable is a variable that is shared by all instances of a class. It is defined within a class but outside any of the class's methods. This code shows you how to define it.

>>> class Book(object):
          counter = 0    # class variable
          def __init__(self, isbn, title, author, publisher):
             Book.counter += 1
             self.isbn = isbn
             self.title = title
             self.author = author
             self.publisher = publisher
          def displayBook(self):
             print("Book #%d" % Book.counter)
             print("%s\t%s\t%s\t%s" %
                   (self.isbn,self.title,self.author,self.publisher))
		
>>> a = Book('978-0-672-32862-6','Python','David Beazley','Addison-Wesley')
>>> a.displayBook()
Book #1
978-0-672-32862-6  Python David Beazley  Addison-Wesley
>>> b = Book('978-0-321-56615-7','Objective-C','Stephen G. Kotchan','Addison-Wesley')
>>> b.displayBook()
Book #2
978-0-321-56615-7  Objective-C  Stephen G. Kotchan  Addison-Wesley
>>> c = Book('978-0-321-68056-3','Python 3','Mark Summerfield','Addison-Wesley')
>>> c.displayBook()
Book #3
978-0-321-68056-3  Python 3  Mark Summerfield  Addison-Wesley
>>> 

May 30, 2013

Copying a File in Python

To copy a file in Pyhton, we can use shutil.copy().
budi@linux:~$ sudo gedit test.py
[sudo] password for budi: 
budi@linux:~$ cat test.py
#!/usr/bin/python3.2

print("Hello World!")
budi@linux:~$ python3.2
Python 3.2.3 (default, Oct 19 2012, 20:13:42) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import shutil
>>> dir = os.getcwd()
>>> sourcefile = "test.py"
>>> destfile = "dest.py"
>>> shutil.copy(os.path.join(dir, sourcefile), os.path.join(dir, destfile))
>>> exit()
budi@linux:~$ cat dest.py
#!/usr/bin/python3.2

print("Hello World!")
budi@linux:~$

May 29, 2013

Displaying Thousands Separator in a Number

The other way to add thousands separator in a number:
>>> def addthousandseparator(number, separator=','):
          lstr = list(str(number))
          n = len(lstr) - 3
          while n > 0:
            lstr.insert(n, separator)
            n -= 3
          return "".join(lstr)

>>> addthousandseparator(1234567)
'1,234,567'
>>> addthousandseparator(1234567890, '.')
'1.234.567.890'
>>>

May 28, 2013

Opening an URL in Python

We can open an URL from Python code using open(), open_new() or open_new_tab() function on webbrowser module.
>>> import webbrowser
>>> webbrowser.open("http://www.python.org")
True
>>> webbrowser.open_new("http://www.python.org")
True
>>> webbrowser.open_new_tab("http://www.python.org")
True
>>> 

May 26, 2013

Method Overloading in Python

Unlike C++, Python doesn't support method overloading. To impelement this C++'s feature in Python, we can use the variable-length argument or isinstance() function. These codes show you how to implement method overloading both in C++ and Python.

budi@linux:~$ sudo gedit overload.cpp
budi@linux:~$ cat overload.cpp
/* C++ code */

#include 

class Example {
public:
  int div(int a, int b) { return a / b; }
  double div(double a, double b) { return a / b; }
};

int main() {
  Example *obj = new Example();
  std::cout<<"Integer division: "
           <<obj->div(10, 3)<<std::endl;
  std::cout<<"Floating-point division: "
           <<obj->div(10.0, 3.0)<<std::endl;
  delete obj;
  return 0;
}
budi@linux:~$ sudo g++-4.6 overload.cpp -o overload.o
budi@linux:~$ sudo chmod 755 overload.o
budi@linux:~$ ./overload.o
Integer division: 3
Floating-point division: 3.33333

budi@linux:~$ sudo gedit overload.py
budi@linux:~$ cat overload.py
#!/usr/bin/python3.2

# Python code

class Example(object):
   def __init__(self):
      pass
   def div(self, a, b):
     if isinstance(a, int) and isinstance(b, int):
        return a // b
     else:
        return a / b

if __name__ == '__main__':
   obj = Example()
   print("Integer division: ", obj.div(10, 3))
   print("Floating-point division: ", obj.div(10.0, 3.0))
budi@linux:~$ sudo chmod 755 overload.py
budi@linux:~$ ./overload.py
Integer division: 3
Floating-point division: 3.3333333333333335

May 25, 2013

Passing Variable-length Arguments

This following code shows you how to pass variable-length argument in a function.
budi@linux:~$ python3.2
Python 3.2.3 (default, Oct 19 2012, 20:13:42) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def func(*args):
...   for i in args:
...     print(i, end=' ')
... 
>>> func(10)         # one argument
10
>>> func(10,20)      # two arguments
10 20 
>>> func(10, 20, 30) # three arguments
10 20 30 
>>>

May 24, 2013

Creating A "tar" File

The following shell commands and Python codes show you how to create a tar archive file with no compression.
budi@linux:~$ cd pythoncode/
budi@linux:~/pythoncode$ ls -la
total 20
drwxr-xr-x  2 root root 4096 May 24 08:42 .
drwxr-xr-x 38 budi budi 4096 May 24 08:21 ..
-rwxr-xr-x  1 root root  714 May 24 08:23 test1.py
-rwxr-xr-x  1 root root 2143 May 24 08:22 test2.py
-rwxr-xr-x  1 root root 1429 May 24 08:22 test3.py
budi@linux:~/pythoncode$ sudo python3.2
[sudo] password for budi:
Python 3.2.3 (default, Oct 19 2012, 20:13:42) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getcwd()
'/home/budi/pythoncode'
>>> import tarfile, glob
>>> tfile = tarfile.open("test.tar", 'w')
>>> for filename in glob.glob("*.py"):
...    tfile.add(filename)
... 
>>> tfile.close()
>>> exit()
budi@linux:~/pythoncode$ ls -la
total 32
drwxr-xr-x  2 root root  4096 May 24 08:43 .
drwxr-xr-x 38 budi budi  4096 May 24 08:21 ..
-rwxr-xr-x  1 root root   714 May 24 08:23 test1.py
-rwxr-xr-x  1 root root  2143 May 24 08:22 test2.py
-rwxr-xr-x  1 root root  1429 May 24 08:22 test3.py
-rw-r--r--  1 root root 10240 May 24 08:45 test.tar
budi@linux:~/pythoncode$ 

May 23, 2013

Importing Excel File into SQLite Table

The following steps show you how to import data from Excel file into SQLite table.
>>> # STEP 1: Create your Excel file
>>> import csv
>>> data = [(1,10), (2,20), (3,30), (4,40), (5,50)]
>>> with open("data.csv", 'w', newline='', encoding='utf-8') as csvfile:
          w = csv.writer(csvfile, delimiter=';')
          w.writerows(data)
          csvfile.close()
 
>>> # STEP 2: Create a table with two integer fields on your SQLite database
>>> import sqlite3
>>> conn = sqlite3.connect("sqlite3db.db")
>>> c = conn.cursor()
>>> c.execute("create table test(a integer, b integer)")
<sqlite3.Cursor object at 0x020CDE20>
>>> c.close()
>>> conn.close()
>>> 
>>> # STEP 3: Import your data.csv into test table
>>> # import csv, sqlite3
>>> with open("data.csv", 'r', newline='', encoding='utf-8') as csvfile:
          conn = sqlite3.connect("sqlite3db.db")
          c = conn.cursor()
          r = csv.reader(csvfile, delimiter=';')
          for row in r:
             c.execute("insert into test values(?,?)", (row[0], row[1]))
          conn.commit()
          csvfile.close()
 
<sqlite3.Cursor object at 0x020CDEA0>
<sqlite3.Cursor object at 0x020CDEA0>
<sqlite3.Cursor object at 0x020CDEA0>
<sqlite3.Cursor object at 0x020CDEA0>
<sqlite3.Cursor object at 0x020CDEA0>
>>> # now, check your data on the table
>>> for (a, b) in c.execute("select a, b from test"):
          print("%s\t%s" % (a, b))
 
1     10
2     20
3     30
4     40
5     50
>>> conn.close()
>>>
QH6X8NHXHVP8