Python Quick Notes :: Part - 2


Bhaskar S 02/16/2013

Hands-on With Python - II

User defined functions in Python are used for defining a block of reusable code and have the following syntax:

def function-name(parameter-list):     docstring     function-body     return value

where:

Important facts about user-defined functions in Python:

The following is the python program named sample-07.py:

sample-07.py
#
# Name: sample-07.py
#

# ----- Start of Function definitions -----

# Function returns the result of summation from 1 to n

def sum(n):
    "This function returns the result of summation from 1 to n"
    s = 0
    for i in range(1, n+1):
        s += i
    return s

# Function that takes a list and changes it (pass by reference)

def mutate(list):
    i = 0
    while i < len(list):
        list[i] *= 2
        i += 1
    return

# Function that defines variable (local scope)

def localvar():
    b = "Python"
    print("b (inside) = ", b)
    return

# Function that access global variable

def globvar():
    global b
    b = b.upper()
    print("b (inside) = ", b)
    return

# Function with default parameter value

def defval(list, n = 3):
    if n > 0 and n <= 5:
        i = 0
        while i < len(list):
            list[i] *= n
            i += 1
    return

# ----- End of Function definitions -----

a = [1, 2, 3, 4, 5]
b = "hello python"
c = [1, 2, 3, 4, 5]
d = [1, 2, 3, 4, 5]

# Call function sum(10) that returns the summation value

val = sum(10)
print("sum(10) = ", val)

# Call function mutate(a)

print("a (before mutate(a)) = ", a)
mutate(a)
print("a (after mutate(a)) = ", a)

# Call function localvar()

print("b (before localvar()) = ", b)
localvar()
print("b (after localvar()) = ", b)

# Call function globvar()

print("b (before globvar()) = ", b)
globvar()
print("b (after globvar()) = ", b)

# Call function defval(c, 4)

print("c (before defval(c, 4)) = ", c)
defval(c, 4)
print("c (after defval(c, 4)) = ", c)

# Call function defval(d)

print("d (before defval(d)) = ", d)
defval(d)
print("d (after defval(d)) = ", d)

Execute the following command:

python sample-07.py

The following is the output:

Output (sample-07.py)

sum(10) =  55
a (before mutate(a)) =  [1, 2, 3, 4, 5]
a (after mutate(a)) =  [2, 4, 6, 8, 10]
b (before localvar()) =  hello python
b (inside) =  Python
b (after localvar()) =  hello python
b (before globvar()) =  hello python
b (inside) =  HELLO PYTHON
b (after globvar()) =  HELLO PYTHON
c (before defval(c, 4)) =  [1, 2, 3, 4, 5]
c (after defval(c, 4)) =  [4, 8, 12, 16, 20]
d (before defval(d)) =  [1, 2, 3, 4, 5]
d (after defval(d)) =  [3, 6, 9, 12, 15]

A Python module is a regular Python code file containing functions and related objects. The following are some facts about Python modules:

The following is the python module named MyMath.py:

MyMath.py
#
# Module: MyMath.py
#

# Function returns the result of summation from 1 to n

def summation(n):
    "This function returns the result of summation from 1 to n"
    s = 0
    for i in range(1, n+1):
        s += i
    return s

# Function returns the factorial of n

def factorial(n):
    "This function returns the result of factorial of n"
    f = 1
    for i in range(2, n+1):
        f *= i
    return f

# Function returns the fibonacci of n (uses recursion)

def fibonacci(n):
    "This function returns the fibonacci of n"
    if n == 0 or n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

The following is the python program named sample-08.py that uses the module MyMath:

sample-08.py
#
# Name: sample-08.py
#

# ----- Using Python module MyMath -----

import MyMath

# List of all symbols including object and faction names

list = dir(MyMath)
print("dir(MyMath) = ", list)

# Call summation

print("MyMath.summation(10) = ", MyMath.summation(10))

# Call factorial

print("MyMath.factorial(10) = ", MyMath.factorial(10))

# Call fibonacci

print("MyMath.fibonacci(10) = ", MyMath.fibonacci(10))

Execute the following command:

python sample-08.py

The following is the output:

Output (sample-08.py)

dir(MyMath) =  ['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'factorial', 'fibonacci', 'summation']
MyMath.summation(10) =  55
MyMath.factorial(10) =  3628800
MyMath.fibonacci(10) =  89

Python standard library comes with many modules and in the following we will mention only a few:

The following is the python program named sample-09.py that uses some of the above mentioned standard modules:

sample-09.py
#
# Name: sample-09.py
#

# ----- Using Python modules math, os, re, sys -----

import math, os, re, sys

# Print the command line arguments

print("---> Module sys operations")

i = 0
for arg in sys.argv:
    print("arg[%d] = %s" % (i, arg))
    i += 1

# Print the operating system

print("Operating platform: ", sys.platform)

# Print the Python module search path

print("Module search path: ", sys.path)

# Print all the accessible Python modules

print("Module list: ", list(sys.modules.keys()))

print("---> Module math operations")

# Print value of math symbol PI

print("Pi: ", math.pi)

# Print the square root of 75

print("math.sqrt(75): ", math.sqrt(75))

print("---> Module os operations")

# Print current working directory

print("Current working directory: ", os.getcwd())

# Create the TEMP directory

print("Create directory TEMP ...")
os.mkdir("TEMP")

# Print the size of TEMP directory

ds = os.stat("TEMP")
print("Size of directory TEMP: ", ds.st_size)

# Remove the TEMP directory

print("Remove directory TEMP ...")
os.rmdir("TEMP")

# Execute the ls -l command
print("Execute ls -l ...")
os.system("ls -l")

print("---> Module re operations")

st = "Hello Python"
m = re.match("\w+", st)
if m:
    print("First word: ", m.group(0))

st = "16 Feb 2013"
m = re.match("(\d{2}) (\w+) (\d{4})", st)
if m:
    day, month, year = m.group(1, 2, 3)
    print("Day = %s, Month: %s, Year: %s" % (day, month, year))

Execute the following command:

python sample-09.py

The following is the output:

Output (sample-09.py)

---> Module sys operations
arg[0] = sample-09.py
arg[1] = Hello
arg[2] = Python
Operating platform:  linux2
Module search path:  ['/home/bswamina/Projects/Python', '/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7']
Module list:  ['copy_reg', 'sre_compile', '_sre', 'encodings', 'site',
'__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc',
'posixpath', '_weakrefset', 'errno', 'encodings.codecs', 'sre_constants',
're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings',
'math', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings',
'UserDict', 'encodings.utf_8', 'sys', 'codecs', '_sysconfigdata_nd',
'os.path', 'sitecustomize', 'signal', 'traceback', 'linecache', 'posix',
'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']
---> Module math operations
Pi:  3.14159265359
math.sqrt(75):  8.66025403784
---> Module os operations
Current working directory:  /home/bswamina/Projects/Python
Create directory TEMP ...
Size of directory TEMP:  4096
Remove directory TEMP ...
Execute ls -l ...
total 44
-rw-r--r-- 1 bswamina bswamina  631 Feb 16 17:32 MyMath.py
-rw-r--r-- 1 bswamina bswamina  957 Feb 16 17:35 MyMath.pyc
-rw-r--r-- 1 bswamina bswamina 1843 Feb 10 16:00 sample-01.py
-rw-r--r-- 1 bswamina bswamina 1035 Feb 10 16:30 sample-02.py
-rw-r--r-- 1 bswamina bswamina  951 Feb 10 17:07 sample-03.py
-rw-r--r-- 1 bswamina bswamina 1400 Feb 10 17:58 sample-04.py
-rw-r--r-- 1 bswamina bswamina  835 Feb 10 18:10 sample-05.py
-rw-r--r-- 1 bswamina bswamina  719 Feb 10 20:42 sample-06.py
-rw-r--r-- 1 bswamina bswamina 1645 Feb 15 23:16 sample-07.py
-rw-r--r-- 1 bswamina bswamina  408 Feb 16 20:09 sample-08.py
-rw-r--r-- 1 bswamina bswamina 1484 Feb 16 22:07 sample-09.py
---> Module re operations
First word:  Hello
Day = 16, Month: Feb, Year: 2013

Python is an object oriented language and hence allows us to defined object classes. A class is nothing more than an encapsulation of data and related functions. The following are some facts about Python classes:

The following is the python program named sample-10.py that defines and uses the Python class Contact:

sample-10.py
#
# Name: sample-10.py
#

# ----- Start Definition the class Contact -----

class Contact:
    "This class encapsulates contact information"

    def __init__(self):
        self.email = ""
        self.home = ""
        self.mobile = ""

    def getEmail(self):
        return self.email

    def setEmail(self, email):
        self.email = email

    def getHome(self):
        return self.home

    def setHome(self, home):
        self.home = home

    def getMobile(self):
        return self.mobile

    def setMobile(self, mobile):
        self.mobile = mobile

# ----- End Definition the class Contact -----

# Use class Contact

john = Contact()
john.setEmail("john@space.com")
john.setHome("111-222-3333")
john.setMobile("999-888-7777")

print("John's Email = ", john.getEmail())
print("John's Home = ", john.getHome())
print("John's Mobile = ", john.getMobile())

Execute the following command:

python sample-10.py

The following is the output:

Output (sample-10.py)

John's Email =  john@space.com
John's Home =  111-222-3333
John's Mobile =  999-888-7777

Some more facts about Python classes:

The following is the python program named sample-11.py:

sample-11.py
#
# Name: sample-11.py
#

# ----- Start Definition the class Account -----

class Account:

    """ This class encapsulates account information. It has two
        instance variables - acctNo and balance. It also defines
        a class variable INTEREST. It defines methods - credit(),
        debit(), and getBalance()"""

    INTEREST = 0.75

    def __init__(self, acctNo, balance):
        self.acctNo = acctNo
        self.balance = balance

    def getAcctNo(self):
        return self.acctNo

    def getBalance(self):
        return self.balance

    def credit(self, amount):
        if amount > 0:
            self.balance += amount

    def debit(self, amount):
        if amount > 0 and self.balance > amount:
            self.balance -= amount

    def __del__(self):
        print("Account [", self.acctNo, "] will be deleted")

    def __str__(self):
        return "*** Account [" + self.acctNo + "], Balance: " + str(self.balance)

# ----- End Definition the class Account -----

# Use class Account

print("Account.INTEREST = ", Account.INTEREST)
print("Account.__name__ = ", Account.__name__)
print("Account.__doc__ = ", Account.__doc__)

acct = Account("12345", 100.00)

print(acct)

print("---> Credit of 25")

acct.credit(25)

print("Balance after credit: ", acct.getBalance())

print("---> Debit of 50")

acct.debit(50)

print("Balance after debit: ", acct.getBalance())

Execute the following command:

python sample-11.py

The following is the output:

Output (sample-11.py)

Account.INTEREST =  0.75
Account.__name__ =  Account
Account.__doc__ =   This class encapsulates account information. It has two
        instance variables - acctNo and balance. It also defines
        a class variable INTEREST. It defines methods - credit(),
        debit(), and getBalance()
*** Account [12345], Balance: 100.0
---> Credit of 25
Balance after credit:  125.0
---> Debit of 50
Balance after debit:  75.0
Account [ 12345 ] will be deleted

Python supports class inheritance. The following is the python program named sample-12.py will demonstrate class inheritance:

sample-12.py
#
# Name: sample-12.py
#

# ----- Start Definition the class Base and Derived -----

class Base:

    "This is a Base class"

    def __init__(self, m):
        print("Base.__init__(), m = ", m)
        self.m = m

    def getM(self):
        return self.m

class Derived(Base):

    "This is a Derived class"

    def __init__(self, m, n):
        print("Derived.__init__(), m = ", m,", n = ", n)
        Base.__init__(self, m)
        self.n = n

    def getN(self):
        return self.n

# -----  End Definition the class Base and Derived  -----

b = Base(10)

print("b.getM() = ", b.getM())

d = Derived(10, 20)

print("d.getM() = ", d.getM())
print("d.getN() = ", d.getN())

Execute the following command:

python sample-12.py

The following is the output:

Output (sample-12.py)

Base.__init__(), m =  10
b.getM() =  10
Derived.__init__(), m =  10 , n =  20
Base.__init__(), m =  10
d.getM() =  10
d.getN() =  20

References

Python Quick Notes :: Part - 1