Learn 90% of Python in 90 Minutes

212,008 views

Published on

The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.

Published in: Technology, Education
12 Comments
653 Likes
Statistics
Notes
No Downloads
Views
Total views
212,008
On SlideShare
0
From Embeds
0
Number of Embeds
8,256
Actions
Shares
0
Downloads
8,011
Comments
12
Likes
653
Embeds 0
No embeds

No notes for slide

Learn 90% of Python in 90 Minutes

  1. 1. 90% of Python in 90 Minutes @__mharrison__ Copyright 2013
  2. 2. About Me ● ● ● 12+ years Python Worked in Data Analysis, HA, Search, Open Source, BI, and Storage Author of multiple Python Books
  3. 3. Goal ● Read Python ● Write Python
  4. 4. Book
  5. 5. Book Treading on Python Volume 1 covers this talk in much more detail.
  6. 6. Begin
  7. 7. Disclaimer ● Assume some programming experience ● Not covering all api's, just syntax
  8. 8. Warning ● Starting from ground zero ● Hands-on at end
  9. 9. Three Python'isms to Remember ● dir ● help ● colon/indent shuffle
  10. 10. Why Python? Python is a powerful, multi-paradigm, interpreted language popular with start-ups and large Co’s
  11. 11. Python 2 or 3? For beginners there is no real difference between Python 2 & 3. The basics are the same (except for print)
  12. 12. Hello World
  13. 13. hello world print "hello world"
  14. 14. from interpreter $ python >>> print "hello world" hello world
  15. 15. REPL Read, Eval, Print, Loop
  16. 16. REPL $ python >>> 2 + 2 4 >>> # # # read, eval print repeat (loop)
  17. 17. REPL (2) Many developers keep a REPL handy during programming
  18. 18. From script Make file hello.py with print "hello world" Run with: python hello.py
  19. 19. (unix) script Make file hello with #!/usr/bin/env python print "hello world" Run with: chmod +x hello ./hello
  20. 20. Python 3 hello world print is no longer a statement, but a function print("hello world")
  21. 21. Objects
  22. 22. Objects Everything in Python is an object that has: ● an identity (id) ● a value (mutable or immutable)
  23. 23. id >>> a = 4 >>> id(a) 6406896
  24. 24. Value ● ● Mutable:When you alter the item, the id is still the same. Dictionary, List Immutable:String, Integer, Tuple
  25. 25. Mutable >>> b = [] >>> id(b) 140675605442000 >>> b.append(3) >>> b [3] >>> id(b) 140675605442000 # SAME!
  26. 26. Immutable >>> a = 4 >>> id(a) 6406896 >>> a = a + 1 >>> id(a) 6406872 # DIFFERENT!
  27. 27. Variables a b c a = = = = 4 # Integer 5.6 # Float "hello" # String "4" # rebound to String
  28. 28. Naming ● lowercase ● underscore_between_words ● don't start with numbers See PEP 8
  29. 29. PEP Python Enhancement Proposal (similar to JSR in Java)
  30. 30. Math
  31. 31. Math +, -, *, /, ** (power), % (modulo)
  32. 32. Careful with integer division >>> 3/4 0 >>> 3/4. 0.75 (In Python 3 // is integer division operator)
  33. 33. What happens when you raise 10 to the 100th?
  34. 34. Long >>> 10**100 10000000000000000000000000000000 00000000000000000000000000000000 00000000000000000000000000000000 00000L
  35. 35. Long (2) >>> import sys >>> sys.maxint 9223372036854775807 >>> sys.maxint + 1 9223372036854775808L
  36. 36. Strings
  37. 37. Strings name = 'matt' with_quote = "I ain't gonna" longer = """This string has multiple lines in it"""
  38. 38. How do I print? He said, “I’m sorry”
  39. 39. String escaping Escape with >>> print 'He said, "I'm sorry"' He said, "I'm sorry" >>> print '''He said, "I'm sorry"''' He said, "I'm sorry" >>> print """He said, "I'm sorry"""" He said, "I'm sorry"
  40. 40. String escaping (2) Escape Sequence Output Backslash ' Single quote " Double quote b ASCII Backspace n Newline t Tab u12af Unicode 16 bit U12af89bc Unicode 32 bit o84 Octal character xFF Hex character
  41. 41. String formatting c-like >>> "%s %s" %('hello', 'world') 'hello world' PEP 3101 style >>> "{0} {1}".format('hello', 'world') 'hello world'
  42. 42. Methods & dir
  43. 43. dir Lists attributes and methods: >>> dir("a string") ['__add__', '__class__', ... 'startswith', 'swapcase', 'title', 'translate', 'upper', 'strip', 'zfill']
  44. 44. Whats with all the '__blah__'?
  45. 45. dunder methods dunder (double under) or "special/magic" methods determine what will happen when + (__add__) or / (__div__) is called.
  46. 46. help >>> help("a string".startswith) Help on built-in function startswith: startswith(...) S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
  47. 47. String methods ● s.endswith(sub) Returns True if endswith sub ● s.find(sub) Returns index of sub or -1 ● s.format(*args) Places args in string
  48. 48. String methods (2) ● s.index(sub) Returns index of sub or exception ● s.join(list) Returns list items separated by string ● s.strip() Removes whitespace from start/end
  49. 49. Comments
  50. 50. comments Comments follow a #
  51. 51. comments No multi-line comments
  52. 52. More Types
  53. 53. None Pythonic way of saying NULL. Evaluates to False. c = None
  54. 54. booleans a = True b = False
  55. 55. sequences ● lists ● tuples ● sets
  56. 56. lists Hold sequences. How would we find out the attributes & methods of a list?
  57. 57. lists >>> dir([]) ['__add__', '__class__', '__contains__',... '__iter__',... '__len__',... , 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
  58. 58. lists >>> >>> >>> >>> >>> >>> [1, a = [] a.append(4) a.append('hello') a.append(1) a.sort() # in place print a 4, 'hello']
  59. 59. lists How would we find out documentation for a method?
  60. 60. lists help function: >>> help([].append) Help on built-in function append: append(...) L.append(object) -- append object to end
  61. 61. List methods ● l.append(x) Insert x at end of list ● l.extend(l2) Add l2 items to list ● l.sort() In place sort
  62. 62. List methods (2) ● l.reverse() Reverse list in place ● l.remove(item) Remove first item found ● l.pop() Remove/return item at end of list
  63. 63. Dictionaries
  64. 64. dictionaries Also called hashmap or associative array elsewhere >>> >>> >>> >>> >>> 10 age = {} age['george'] = 10 age['fred'] = 12 age['henry'] = 10 print age['george']
  65. 65. dictionaries (2) Find out if 'matt' in age >>> 'matt' in age False
  66. 66. in statement Uses __contains__ dunder method to determine membership. (Or __iter__ as fallback)
  67. 67. .get >>> print age['charles'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'charles' >>> print age.get('charles', 'Not found') Not found
  68. 68. deleting keys Removing 'charles' from age >>> del age['charles']
  69. 69. deleting keys del not in dir. .pop is an alternative
  70. 70. Functions
  71. 71. functions def add_2(num): """ return 2 more than num """ return num + 2 five = add_2(3)
  72. 72. functions (2) ● def ● function name ● (parameters) ● : + indent ● optional documentation ● body ● return
  73. 73. whitespace Instead of { use a : and indent consistently (4 spaces)
  74. 74. whitespace (2) invoke python -tt to error out during inconsistent tab/space usage in a file
  75. 75. default (named) parameters def add_n(num, n=3): """default to adding 3""" return num + n five = add_n(2) ten = add_n(15, -5)
  76. 76. __doc__ Functions have docstrings. Accessible via .__doc__ or help
  77. 77. __doc__ >>> def echo(txt): ... "echo back txt" ... return txt >>> help(echo) Help on function echo in module __main__: <BLANKLINE> echo(txt) echo back txt <BLANKLINE>
  78. 78. naming ● lowercase ● underscore_between_words ● don't start with numbers ● verb See PEP 8
  79. 79. Conditionals
  80. 80. conditionals if grade > 90: print "A" elif grade > 80: print "B" elif grade > 70: print "C" else: print "D"
  81. 81. Remember the colon/whitespace!
  82. 82. Booleans a = True b = False
  83. 83. Comparison Operators Supports (>, >=, <, <=, ==, !=) >>> 5 > 9 False >>> 'matt' != 'fred' True >>> isinstance('matt', basestring) True
  84. 84. Boolean Operators and, or, not (for logical), &, |, and ^ (for bitwise) >>> x = 5 >>> x < -4 or x > 4 True
  85. 85. Boolean note Parens are only required for precedence if (x > 10): print "Big" same as if x > 10: print "Big"
  86. 86. Chained comparisons if 3 < x < 5: print "Four!" Same as if x > 3 and x < 5: print "Four!"
  87. 87. Iteration
  88. 88. iteration for number in [1,2,3,4,5,6]: print number for number in range(1, 7): print number
  89. 89. range note Python tends to follow half-open interval ([start,end)) with range and slices. ● end - start = length ● easy to concat ranges w/o overlap
  90. 90. iteration (2) Java/C-esque style of object in array access (BAD): animals = ["cat", "dog", "bird"] for index in range(len(animals)): print index, animals[index]
  91. 91. iteration (3) If you need indices, use enumerate animals = ["cat", "dog", "bird"] for index, value in enumerate(animals): print index, value
  92. 92. iteration (4) Can break out of nearest loop for item in sequence: # process until first negative if item < 0: break # process item
  93. 93. iteration (5) Can continue to skip over items for item in sequence: if item < 0: continue # process all positive items
  94. 94. iteration (6) Can loop over lists, strings, iterators, dictionaries... sequence like things: my_dict = { "name": "matt", "cash": 5.45} for key in my_dict.keys(): # process key for value in my_dict.values(): # process value for key, value in my_dict.items(): # process items
  95. 95. pass pass is a null operation for i in # do pass range(10): nothing 10 times
  96. 96. Hint Don't modify list or dictionary contents while looping over them
  97. 97. Slicing
  98. 98. Slicing Sequences (lists, tuples, strings, etc) can be sliced to pull out a single item my_pets = ["dog", "cat", "bird"] favorite = my_pets[0] bird = my_pets[-1]
  99. 99. Negative Indexing Proper way to think of [negative indexing] is to reinterpret a[-X] as a[len(a)-X] @gvanrossum
  100. 100. Slicing (2) Slices can take an end index, to pull out a list of items my_pets = ["dog", "cat", "bird"] # a list cat_and_dog = my_pets[0:2] cat_and_dog2 = my_pets[:2] cat_and_bird = my_pets[1:3] cat_and_bird2 = my_pets[1:]
  101. 101. Slicing (3) Slices can take a stride my_pets = ["dog", "cat", "bird"] # a list dog_and_bird = [0:3:2] zero_three_etc = range(0,10) [::3]
  102. 102. Slicing (4) Just to beat it in veg = "tomatoe" correct = veg[:-1] tmte = veg[::2] eotamot = veg[::-1]
  103. 103. File IO
  104. 104. File Input Open a file to read from it (old style): fin = open("foo.txt") for line in fin: # manipulate line fin.close()
  105. 105. File Output Open a file using 'w' to write to a file: fout = open("bar.txt", "w") fout.write("hello world") fout.close()
  106. 106. Always remember to close your files!
  107. 107. closing with with implicit close (new 2.5+ style) with open('bar.txt') as fin: for line in fin: # process line
  108. 108. Classes
  109. 109. Classes class Animal(object): def __init__(self, name): self.name = name def talk(self): print "Generic Animal Sound" animal = Animal("thing") animal.talk()
  110. 110. Classes (2) notes: ● object (base class) (fixed in 3.X) ● dunder init (constructor) ● all methods take self as first parameter
  111. 111. Classes(2) Subclassing class Cat(Animal): def talk(self): print '%s says, "Meow!"' % (self.name) cat = Cat("Groucho") cat.talk() # invoke method
  112. 112. Classes(3) class Cheetah(Cat): """classes can have docstrings""" def talk(self): print "Growl"
  113. 113. naming ● CamelCase ● don't start with numbers ● Nouns
  114. 114. Debugging
  115. 115. Poor mans print works a lot of the time
  116. 116. Remember Clean up print statements. If you really need them, use logging or write to sys.stdout
  117. 117. pdb import pdb; pdb.set_trace()
  118. 118. pdb commands ● h - help ● s - step into ● n - next ● c - continue ● w - where am I (in stack)? ● l - list code around me
  119. 119. That's all Questions? Tweet me For more details see Treading on Python Volume 1 @__mharrison__ http://hairysun.com

×