Programming with Python - Week 2

778 views
712 views

Published on

Lecture notes on Programming with Python.

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
778
On SlideShare
0
From Embeds
0
Number of Embeds
14
Actions
Shares
0
Downloads
17
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Programming with Python - Week 2

    1. 1. Programming withPython Week 2Dept. of Electrical Engineering and Computer ScienceAcademic Year 2010-2011
    2. 2. Week 1 - Highlights• In Python, everything is an object.• In Python, you never explicitly specify the datatype of anything.• Based on what value you assign, Python keeps track of the datatype internally.
    3. 3. Week 1 - Highlights• just indent and get on with your life.• indentation is a language requirement. not a matter of style.• Python uses carriage return to separate statements.• Python uses a colon and indentation to separate code blocks. : ...
    4. 4. Mannerism: Dropbox usage• Use Shared Dropbox folder more responsibly.• Think of your friends.• Think before you act.
    5. 5. Week 2
    6. 6. 3.1 IntroducingDictionaries• Dictionary is a built-in datatype of Python.• It defines a one-to-one relationship between keys and values.• One-to-one relationship? Let’s see with a useful example.
    7. 7. One-to-one relationship?• http://maps.google.com/maps/place? cid=12784366278796637370&q=Wells+Fargo+Bank +near+Union+Street,+SF,+CA,+United +States&hl=en&dtab=0&sll=37.798984,-122.421915&ssp n=0.006295,0.03601&ie=UTF8&ll=37.817446,-122.4536 13&spn=0,0&z=14 Relationship: shortened to by• http://bit.ly/f2bSMH
    8. 8. Takeaway I: Its much easier to includeKey --> Value the shorter link in an email or Twitter post without it breaking or taking up space. Takeaway II: bit.ly works by issuing a "301 redirect". When you shorten a link with bit.ly, you are redirecting a click from bit.ly to the destination URL. A 301 redirect is the most efficient and search engine-friendly method for webpage redirection.
    9. 9. 3.1.1 Defining Dictionaries• >>> d = {“bruce”: “lee”, “mortal”: “kombat”} } {• >>> d {bruce: lee, mortal: kombat}• >>> d["bruce"] lee
    10. 10. Rules, rules, rules• You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.• You can add new key-value pairs at any time. This syntax is identical to modifying existing values.• Be careful: you may be adding new values but are actually just modifying the same value over and over because your key isnt changing the way you think it is.• Dictionaries are unordered.• Dictionary keys are case-sensitive.
    11. 11. 3.1.2 Modifying dictionaries& case-sensitivity K• >>> d = {}• >>> d = {“key” : “value”}• >>> d k {key: value}• >>> d[“Key”] = “Value”• >>> d {Key: Value, key: value}
    12. 12. Shepherd’ssalad of datatypes• >>> d={"bruce":"lee","mortal":"kombat"}• >>> d["air force"] = 1• >>> d {bruce: lee, air force: 1, mortal: kombat}• >>> d[2]="two"• >>> d {bruce: lee, 2: two, air force: 1, mortal: kombat}
    13. 13. Dictionaries• Dictionaries are NOT just for strings.• Dictionary values can be any datatype. Within a single dictionary, you can have values of different datatypes.• Dictionary keys are more restricted: strings and integers are mostly used (note: there are some others too).
    14. 14. 3.1.3 Deleting Itemsfrom Dictionaries• >>> d {bruce: lee, 2: two, air force: 1, mortal: kombat}• >>> del d[2]• >>> d {bruce: lee, air force: 1, mortal: kombat}• >>> d.clear()• >>> d {}
    15. 15. 3.2 Introducing Lists• Shopping cart is a list.
    16. 16. Grocery list is a list.
    17. 17. Things to do is a list.
    18. 18. 3.2.1 Defining Lists• >>> li=["armani watch","hunting with the moon","amazon kindle","iphone 4"]• >>> li [armani watch, hunting with the moon, amazon kindle, iphone 4]• >>> li[0] armani watch• >>> li[3] iphone 4
    19. 19. Lists are , , ,]• ordered. [• enclosed in square brackets.• having their first element start at index 0.
    20. 20. Two way access• Forward: li[0] li[3] li = ["armani watch","hunting with the moon","amazon kindle","iphone 4"]• Backward: li[-1] li[-4]
    21. 21. Slicing a list :3 ]• Reading the list from left to right: [ 1 i. the first slice index specifies the first element you want, ii. the second slice index specifies the first element you dont want, iii. the return value is everything in between.
    22. 22. Slicing at work• >>> li [armani watch, hunting with the moon, amazon kindle, iphone 4]• >>> li[1:3] [hunting with the moon, amazon kindle]• >>> li[0:0] Ask in class...
    23. 23. Assuming list length is n• li[:3] is the same as li[0:3].• li[3:] is the same as li[3:n], where n is the length of the list.• li[:n] will always return the first n elements.• li[:] is shorthand for making a complete copy of a list: all elements of the original list are included. But this is not the same as the original li list; it is a new list that has the same elements.
    24. 24. 3.2.1 Adding elements toLists• >>> li [armani watch, hunting with the moon, amazon kindle, iphone 4]• >>> li.append("ipad 32gb wifi+3g")• >>> li [armani watch, hunting with the moon, amazon kindle, iphone 4, ipad 32gb wifi+3g]
    25. 25. 3.2.1 Adding elements toLists• >>> li [armani watch, hunting with the moon, amazon kindle, iphone 4, ipad 32gb wifi+3g]• >>> li.insert(1,”macbook pro”)• >>> li [armani watch, macbook pro, hunting with the moon, amazon kindle, iphone 4, ipad 32gb wifi+3g]
    26. 26. 3.2.1 Adding elements toLists• >>> li [armani watch, macbook pro, hunting with the moon, amazon kindle, iphone 4, ipad 32gb wifi+3g]• >>> li.extend(["zoolander dvd","v for vendetta dvd","gladiator dvd"])• >>> li [armani watch, macbook pro, hunting with the moon, amazon kindle, iphone 4, ipad 32gb wifi+3g, zoolander dvd, v for vendetta dvd, gladiator dvd]
    27. 27. Difference between extendand append• >>> li=["a","b","c"] • >>> del li[3]• >>> li • >>> li [a, b, c] [a, b, c]• >>> li.append • >>> li.extend(["d","e"])• >>> li.append(["d","e"]) • >>>b, c, d, e] [a, li• >>> li [a, b, c, [d, e]]
    28. 28. 3.2.3 Searching a List• >>> li • >>> “c” in li [a, b, c, d, e] True• >>> li • >>> “f” in li [a, b, c, d, e] False• >>> li.index("a") • >>> li.index(“g”) call last): 0 Traceback (most recent File "<pyshell#47>", line 1, in• >>> li.index("e") <module> li.index("g") 4 ValueError: list.index(x): x not in list• >>> “c” in li
    29. 29. 3.2.4 Deleting List elements• >>> li [a, b, c, d, e]• >>> li.remove("a")• >>> li [b, c, d, e]• >>> li.remove("f") Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> li.remove("f") ValueError: list.remove(x): x not in list• >>> li.pop() e
    30. 30. 3.2.5 Using List operators• >>> li [b, c, d]• >>> li = ["a"] + li• >>> li [a, b, c, d]• >>> li += ["e","f"]• >>> li [a, b, c, d, e, f]
    31. 31. 3.2.5 Using List operators extend• >>> li [b, c, d] ext fas larg ter is end• >>> li = ["a"] + li an e li for• >>> li sts in- . it [a, b, c, d] op pla is• >>> li += ["e","f"] era ce• >>> li tio [a, b, c, d, e, f] n.
    32. 32. 3.3 Introducing Tuples ,)• A tuple is an immutable list. , ,• A tuple cannot be changed once it is created. (
    33. 33. Tuples have no methodsimmutable
    34. 34. Tuples are good for?• Tuples are faster than lists.• Working with read-only data makes your code safer. Implicit write-protection.• Note that tuples can be converted into lists and vice- versa.
    35. 35. 3.4 Declaring Variables• Python has local and global variables like most other languages, but it has no explicit variable declarations.• Variables spring into existence by being assigned a value, and they are automatically destroyed when they go out of scope.• Python will not allow you to reference a variable that has never been assigned a value; trying to do so will raise an exception.
    36. 36. VARIABLES VALUE = 1 ASSIGNMENT
    37. 37. 3.4.2 Assigningmultiple values at once• >>> tuple_t = (eecs,211)• >>> (dept,course_code)=tuple_t• >>> dept eecs• >>> course_code 211
    38. 38. Tuples are good for?• Tuples are used in multi-variable assignment.
    39. 39. 3.5 Formatting Strings• >>> m = “mortal”• >>> k = “kombat”• >>> “%s %s” % (m,k) mortal kombat• note the usage of tuples here as well. %
    40. 40. String formatting vs.String concatenation• >>> li [a, b, c, d, e, f]• >>> len(li) 6 %d• >>> print "The length of the list is: %d" % (len(li),) The length of the list is: 6
    41. 41. String concatenation +• >>> print "The length of the list is: " + (len(li)) Traceback (most recent call last): File "<pyshell#74>", line 1, in <module> print "The length of the list is: " + (len(li)) TypeError: cannot concatenate str and int objects• >>> print “mortal” + “ kombat” mortal kombat• string concatenation works only when everything is already a string.
    42. 42. Formatting numbers %f• >>> print "Todays stock price: %f" % 50.4625 Todays stock price: 50.462500• >>> print "Todays stock price: %.2f" % 50.4625 Todays stock price: 50.46• >>> print "Change since yesterday: %+.2f" % 1.5 Change since yesterday: +1.50
    43. 43. 3.6 Mapping Lists• One of the most powerful features of Python is the list comprehension, which provides a compact way of mapping a list into another list by applying a function to each of the elements of the list.• >>> l_numbers = [1,2,3,4]• >>> [element*2 for element in l_numbers] [2, 4, 6, 8]
    44. 44. List comprehensionstep by step• >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}• >>> params.items() [(pwd, secret), (database, master), (uid, sa), (server, mpilgrim)]• >>> [k for k, v in params.items()]• [pwd, database, uid, server] >>> [v for k, v in params.items()] tuples [secret, master, sa, mpilgrim]• >>> ["%s=%s" % (k, v) for k, v in params.items()] [pwd=secret, database=master, uid=sa, server=mpilgrim]
    45. 45. 3.7 Joining Lists andSplitting Strings• To join any list of strings into a single string, use the join method of a string object.• >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()]) pwd=secret;database=master;uid=sa;server=mpilgrim• join works only on lists of strings; it does not do any type coercion. Joining a list that has one or more non- string elements will raise an exception.
    46. 46. 3.7 Joining Lists andSplitting Strings• >>> li = ";".join(["%s=%s" % (k, v) for k, v in params.items()])• >>> li pwd=secret;database=master;uid=sa;server=mpilgrim• >>> li.split(";") [pwd=secret, database=master, uid=sa, server=mpilgrim]• Ask in class.. what do you notice?
    47. 47. Remember Your FirstPython Program odbchelper.py
    48. 48. Dr. Ahmet Bulut took this picture in NYC during when he wasinterning at IBM T.J.Watson Research Center in August 2004.

    ×