Python
Exercises at -Python Exercise 1Python Exercise 2Python Exercise 3
----> hello.py import re def foo(): print("Hello Amar Sharma") if __name__ == "__main__": foo()
TRY FROM REPL
Strings examples
>>> name1 = "John" >>> name2 = "Doe" >>> "My name is %s " % name1 'My name is John ' >>> name1 + " " + name2 'John Doe' >>> if "J" in name1: print("Yes, J's there") Yes, J's there
Strings examples
>>> for i in name1: print(i) J o h n >>>name1.replace("h","a") 'Joan' >>> name1 'John'
Strings examples
>>>name1.find("hn") 2 >>> list(name1) ['J', 'o', 'h', 'n'] >>> name1*4 'JohnJohnJohnJohn' >>> foo = "Python:Perl:Ruby:TCL:Shell" >>> foo.split(":") ['Python', 'Perl', 'Ruby', 'TCL','Shell']
List examples
>>> foo = ["J","o","h","n"]
>>> foo
['J', 'o', 'h', 'n']
>>> foo.append(" ")
>>> foo
['J', 'o', 'h', 'n', ' ']
>>> foo.extend(["D","o","e"])
>>> foo
['J', 'o', 'h', 'n', ' ', 'D', 'o', 'e']
>>> "".join(foo)
'John Doe'
>>> " ".join(foo)
'J o h n D o e'
>>> foo.reverse()
>>> foo
['e', 'o', 'D', ' ', 'n', 'h', 'o', 'J']
>>> foo = ["J","o","h","n"]
>>> for i in foo:
print(foo.index(i),i)
0 J
1 o
2 h
3 n
>>> foo
['J', 'o', 'h', 'n']
>>> foo[2]
'h'
>>> foo[2]="a"
>>> foo
['J', 'o', 'a', 'n']
>>> foo.sort()
>>> foo
['J', 'a', 'n', 'o']
>>> foo.pop()
'o'
>>> foo.pop()
'n'
>>> foo.pop()
'a'
>>> foo.pop()
'J'
>>> foo
[]
>>> foo = "This is the last time I'm going to say this".split()
>>> foo
['This', 'is', 'the', 'last', 'time', "I'm", 'going', 'to', 'say', 'this']
>>> foo[2]
'the'
>>> foo[2:6]
['the', 'last', 'time', "I'm"]
>>> foo[-2]
'say'
>>> foo[:-2]
['This', 'is', 'the', 'last', 'time', "I'm", 'going', 'to']
>>> foo[4:]
['time', "I'm", 'going', 'to', 'say', 'this']
>>>
Dictionary examples
>>> os = { "Microsoft" : "Windows", "Sun" : "Solaris", "Belllabs" : "Plan 9", "SGI" : "Irix"} >>> >>> os {'Bell labs': 'Plan 9', 'Sun': 'Solaris', 'SGI': 'Irix', 'Microsoft': 'Windows'} for i in os.keys(): print(i,os[i]) Bell labs Plan 9 Sun Solaris SGI Irix Microsoft Windows >>> >>> os.has_key("Apple") False >>> "Apple" in os False >>> "Sun" in os True >>> os.values() ['Plan 9', 'Solaris', 'Irix', 'Windows'] >>> os.keys() ['Bell labs', 'Sun', 'SGI', 'Microsoft'] >>> os2 = {"FSF": "Gnu/Linux","Apple" : "OSX"} >>> os2 {'Apple': 'OSX', 'FSF': 'Gnu/Linux'} >>> os.update(os2) >>> for i in os.keys(): #print(i,":",end='') print(i,":"),Bell labs : SGI : Apple : FSF : Sun : Microsoft : >>>
Tuples
>>> tuple("Python") ('P', 'y', 't', 'h', 'o', 'n') >>> foo = (1,2,3) >>> foo[1] = 7 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> foo = (1,) >>> type(foo) <type 'tuple'> >>>
Files
>>> foo = open("/home/mohan/ip.php") >>> foo.read(20) '<?php\necho $_SERVER[' >>> foo.readline() "'REMOTE_ADDR'];\n" >>> foo.readline() '\n' >>> foo.readline() '$url = json_decode(file_get_contents("http://api.ipinfodb.com/v3/ip-city/? key=<your_api_key>&ip=".$_SERVER[\'REMOTE_ADDR\']."&format=json"));\n' >>> x=foo.readlines() >>> len(x) 23 >>> x[4] 'echo "<table border=\'1\' width=\'50%\' align=\'center\'><tr><td>COUNTRY:</td><td>";\n' >>> foo.close() >>> foo.read() Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file >>>
Idea of python objects
- >>> foo = “Wozniak”
>>> bar = foo >>> id(foo) 139807526833968 >>> id(bar) 139807526833968 >>> baz = "Wozniak" >>> id(baz) 139807526833968 >>> >>> foo = range(1,100) >>> bar = range(1,100) >>> id(foo) 139807526796536 >>> id(bar) 139807526796320 >>> foo is bar False >>> foo == bar True >>>
Assignments
>>> foo = ("Wozniak","Apple","Designer") >>> name,company,position = foo >>> name 'Wozniak' >>> position 'Designer' >>> foo,bar = 1,2 >>> foo,bar = bar,foo >>> foo 2 >>> bar 1 >>>
- Multiple targets
>>> a=b=1 >>> a 1 >>> b 1 >>>
- Augmented assignments
>>> foo=1 >>> foo+=1 >>> foo 2 >>>
Conditional Branching statements
- If statements
>>> foo = 11 >>> if foo < 9: print("Less than nine") elif foo > 10: print("Greater than 10") else: print("Between 9 and 10") Greater than 10
- Multiway branching with dictionaries
>>> choice = "eggs" >>> print ({"spam" : 10,"eggs" : 20,"veg" : 15}[choice]) 20 >>>
Indefinite iteration
>>> while 1: x = next() if not x: break print(x)
Definite iteration
>>> for i in range(1,10): #print (i,":",end='') print(i,":"),1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 :
Zip Function
>>> l1 = [1,3,5,7,9] >>> l2 = [2,4,6,8,10] >>> for (x,y) in zip(l1,l2): #print ("(%d,%d) : " % (x,y),end='') print ("(%d,%d) : " % (x,y)),(1,2) : (3,4) : (5,6) : (7,8) : (9,10) : >>>
Example Function
>>> def thrice(arg):return arg*3 >>> thrice(4) 12 >>> thrice([1,2,3]) [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> thrice("Ni!") 'Ni!Ni!Ni!' >>>
Functions
>>> foo = thrice >>> foo(4) 12
Ref or Value ?
>>> bar = [1,2,3,4,5] >>> foo(bar) >>> bar [1, 2, 1, 4, 5] >>> bar = [1,2,3,4,5] >>> foo(bar[:]) #Passing a copy >>> bar [1, 2, 3, 4, 5] >>>
- Arguments by name
>>> def fn(name,company,designation): print("%s works at %s as an %s" % (name,company,designation)) >>> fn("Noufal","Synopsys","Engineer") Noufal works at Synopsys as an Engineer >>> fn(company = "Synopsys",name = "Noufal",designation="Engineer") Noufal works at Synopsys as an Engineer >>>
-
Default arguments
>>> def fn(name,age=25): print("%s is %d years old" % (name,age)) >>> fn("John") John is 25 years old >>> fn("John",30) John is 30 years old >>>
- Variable argument lengths by position
>>> def fn(*foo): for i in foo: #print(i,end='') print(i), >>> fn(1,2,3,4,5,6,7) 1 2 3 4 5 6 7 >>>
- Variable argument lengths by keyword
>>> def fn(**foo): for i in foo.keys(): print(i,":",foo[i]) >>> fn(name="John",age="50") age : 50 name : John >>>
Modules
>>> import display >>> display.fn("John",40) John is 40 years old >>> from display import * >>> fn("John",40) John is 40 years old >>> from display import fn >>> fn("John",40) John is 40 years old
- Module concepts
>>> mod = __import__("display") >>> mod.fn("John",50) John is 50 years old
- Some standard modules
>>> import os >>> foo = os.popen("/bin/ls") >>> foo <open file '/bin/ls', mode 'r' at 0x127860> >>> op = foo.read() >>> op '#.bbdb#\n#.newsrc-dribble#\nMail\nNews\nStarOffice52\naudio ' >>> files = op.split() >>> for i in files: print(i) #.bbdb# #.newsrc-dribble# Mail News
>>> import sre
>>> numerical = sre.compile(“[0-9]+”)
>>> sstring = “Apple PowerBook for just 66000”
>>> foo = numerical.search(sstring)
>>> foo
<_sre.SRE_Match object at 0x1a16e8>
>>> foo.group()
‘66000‘
>>>
>>> import pickle >>> spam = {"Wall" : "Perl", "Guido" : "Python", "Matsumoto" : "Ruby"} >>> spam.keys() ['Wall', 'Matsumoto', 'Guido'] >>> foo = open("/u/noufal/ldict.pkl","w") >>> pickle.dump(spam,foo) >>> foo.close() >>> del(spam) >>> foo = open("/u/noufal/ldict.pkl","r") >>> ham = pickle.load(foo) >>> ham {'Wall': 'Perl', 'Matsumoto': 'Ruby', 'Guido': 'Python'}
Classes and OOP
- Classes behaviour
>>> class FirstClass: def setdata(self,value): self.data = value def display(self): print(self.data) >>> x = FirstClass() >>> y = FirstClass() >>> x.setdata("Eric Idle") >>> x.display() Eric Idle >>> dir(x) ['__doc__', '__module__', 'data', 'display', 'setdata'] >>>
- Inheritance
>>> class SecondClass(FirstClass): def display(self): print("Current value is %s" % str(self.data)) >>> x = SecondClass() >>> x.setdata("King Arthur") >>> x.display() Current value is King Arthur
>>> class ThirdClass(SecondClass): def __init__(self,value): self.data = value def __add__(self,other): return ThirdClass(self.data + other) >>> a = ThirdClass("abc") >>> a.display() Current value is abc >>> b = a + "123" >>> b.display() Current value is abc123 >>>
- Classes odds and ends
>>> getattr(b,"data") 'abc123' >>> setattr(b,"data","xzy") >>> b.data 'xzy' >>> b.display() Current value is xzy
- Exceptions
>>> foo = [1,2,3,4,5] >>> foo[10] Traceback (most recent call last): File "<stdin>", line 1, in ? IndexError: list index out of range >>> try: foo[10] except IndexError: print("Index too large.") Index too large.
- Raising your own exceptions
>>> foo = "FunError" >>> raise foo Traceback (most recent call last): File "<stdin>", line 1, in ? FunError >>> raise foo,"This is what you get for erroring out" Traceback (most recent call last): File "<stdin>", line 1, in ? FunError: This is what you get for erroring out
- Documenting code
>>> def fn(name,age=30): "Displays persons name and age. Age defaults to 30." print("%s is %d years old" % (name,age)) >>> fn("John") John is 30 years old >>> print fn.__doc__ Displays persons name and age. Age defaults to 30.
- Functional programming primitives
>>> foo = lambda x:x*3 >>> foo(2) 6 >>> apply (lambda x:x*100,(2,)) 200 >>> foo = [1,2,3,4,5,6,7] >>> map(lambda x:x*2,foo) [2, 4, 6, 8, 10, 12, 14]
- Functional programming continued
>>> filter (lambda x:x%2==0,range(20)) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] reduce: Apply function on sequence elements pairwise >>> reduce(lambda x,y:x+y,range(10)) 45 >>> foo = 0 >>> for i in range(10): foo += i >>> print(foo) 45 >>> def create_incrementer(inc): return lambda x:x+inc >>> inc3=create_incrementer(3) >>> inc3(10) 13
- List comprehensions
>>> [x*2 for x in range(1,10)] [2, 4, 6, 8, 10, 12, 14, 16, 18] >>> [x**2 for x in range(1,10) if x%2 == 0] [4, 16, 36, 64] >>> [(x,x**2) for x in range(1,10) if x%2 == 0] [(2, 4), (4, 16), (6, 36), (8, 64)]
- Generator functions
>>> def gensq(n): for i in range(n): yield i ** 2 >>> for i in gensq(5): #print(i,":",end='') print(i), 0 : 1 : 4 : 9 : 16 : >>> x = gensq(10) >>> x <generator object at 0x191da0> >>> x.next() 0 >>> x.next() 1 >>> x.next() 4
- Useful development stuff
>>> import rlcompleter, readline >>> readline.parse_and_bind('tab: complete') >>> foo = "hello" >>> foo.<TAB><TAB> foo.__add__ foo.__lt__ foo.encode foo.replace foo.__class__ foo.__mod__ foo.endswith foo.rfind foo.__contains__ foo.__mul__ foo.expandtabs foo.rindex foo.__delattr__ foo.__ne__ foo.find foo.rjust foo.__doc__ foo.__new__ foo.index foo.rstrip foo.__eq__ foo.__reduce__ foo.isalnum foo.split foo.__ge__ foo.__reduce_ex__ foo.isalpha foo.splitlines foo.__getattribute__ foo.__repr__ foo.isdigit foo.startswith foo.__getitem__ foo.__rmod__ foo.islower foo.strip foo.__getnewargs__ foo.__rmul__ foo.isspace foo.swapcase foo.__getslice__ foo.__setattr__ foo.istitle foo.title foo.__gt__ foo.__str__ foo.isupper foo.translat foo.__hash__ foo.capitalize foo.join foo.upper foo.__init__ foo.center foo.ljust foo.zfill foo.__le__ foo.count foo.lower foo.__len__ foo.decode foo.lstrip
- Python DataBase Example
#!/usr/bin/python import MySQLdb #Open database connection db = MySQLdb.connect("","","","information_schema" ) #prepare a cursor object using cursor() method cursor = db.cursor() #execute SQL query using execute() method. cursor.execute("SELECT VERSION()") #Fetch a single row using fetchone() method. data = cursor.fetchone() print "Database version : %s " % data #disconnect from server db.close()
- python sample program
import MySQLdb # Open database connection db = MySQLdb.connect("","","","information_schema" ) # prepare a cursor object using cursor() method cursor = db.cursor() sql = "SELECT * FROM TABLES " try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: print row except: print "Error: unable to fecth data" # disconnect from server db.close()