Friday, November 24, 2006

[python] Start Python

#!/usr/bin/python
import sys
import os
import __builtin__

def helloworld():
    print "Dare to Challenge http://www.pythonchallenge.com/"
    print "Hello World\n";
    print "This is system Path : "
    print sys.path #this is search Path
    sys.path.append("this/is/test/path");
    print "This is system Path after appending test path "
    print sys.path
    filename = os.environ.get('PYTHONSTARTUP')
    print filename
    if filename and os.path.isfile(filename):
        execfile(filename)
    li = []
    print "Method of list ", dir(li) # list all the method of list
    info(__builtin__, 20) # gives the list of built in function

#Factorial Function Start
def fact(n):
    if n > 1:
        return n * fact(n-1)
        else:
        return 1
def info(object, spacing=10, collapse=1):
    """Print methods and doc strings.

    Takes module, class, list, dictionary, or string."""
    # note
    methodList = [e for e in dir(object) if callable(getattr(object, e))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print "\n".join(["%s %s" %
                     (method.ljust(spacing),
                      processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList])

        
def datatypes():
    str = "This is a string."
    print str
    dict = {"server":"mpilgrim", "database":"this will be deleted"}
    print "Currnt Dictionary: ", dict # NOte that it printed in a sorted way.
    dict["server"] = "CHANGED"
    dict["uid"] = "added"
    dict["Uid"] = "case sensitive"
    dict[2] = "mixed data"
    dict["mixed"] = 123
    del dict["database"]
    print "Now Dictionary   : " , dict
    dict.clear() # To clear all the contents
    list = ["a", "b", "mpilgrim", "removethis", "example","pop"]
    print "Current List   :" , list
    print "Length of List : ", len(list)
    print "list[-1]   :", list[-1] #"li[-n] == li[len(li) - n]"
    print "Slicing    :", list[1:-1]
    print "Pop Element: ", list.pop()
    list.append("append")
    list.extend(["extend1","extend2"]) #note the arg is a list.  Concatenates
    list.insert(2,"inserthere")
    list.remove("removethis");
    list += ["Operators"]
    print "Now List   : ",list
    print "Searching extend1 (first occurence): Found at location ", list.index("extend1")
    print "Found c in list:" , "c" in list
    list = ["1","2"]
    print "List Operator  : ", list * 10
    tuple = ("son","mon","tue","wed","thu","fri","sat") # Ordered, fast, But can not be modified
    print tuple
    (a,b,c,d,e,f,g) = range(7)
    print "rnage d = ", d
    #3.6

#Calling main Functions.
helloworld()
#print fact(500)
#datatypes();
#info(list)



"""  Notes
---------- and-or Trick  ----------

>>> a = "first"
>>> b = "second"
>>> 1 and a or b
'first'
>>> 0 and a or b
'second'
---------- and-or Trick Safely ----------
>>> a = ""
>>> b = "second"
>>> (1 and [a] or [b])[0]
---------- split With No Arguments ----------
>>> s = "this    is\na\ttest"
>>> print s
this   is
a       test
>>> print s.split()
['this', 'is', 'a', 'test']
>>> print " ".join(s.split())
'this is a test'

"""

No comments: