Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Intro to Python

Intro to Python

An introduction to the programming language Python. This talk was written for a hackday centred around Django, and given to a group of software developers who were experienced in PHP but had minimal knowledge of Python.

Rae Knowler

February 10, 2015
Tweet

More Decks by Rae Knowler

Other Decks in Programming

Transcript

  1. What is Python? • Open source general-purpose language. • Object

    Oriented, Procedural, Functional • Easy to interface with C/ObjC/Java/Fortran • Easy-ish to interface with C++ (via SWIG) • Great interactive environment (http://tdc-www.harvard.edu/Python.pdf) 2
  2. What can you use Python for? • Web development --

    e.g with Django or Pylons • Scraping • Scripting • Scientific programming • Even games 3
  3. Whitespace def counter(x): if x > 10: print "x is

    already > 10!" else: print x 8
  4. No variable declarations >>> x = 3 >>> type(x) <type

    'int'> >>> y = "fish" >>> type(y) <type 'str'> 9
  5. If if name == "Freda": greeting = "Hi Freda!" elif

    name == "Bobby": greeting = "Go away, Bobby!" else: greeting = "Welcome, " + name 11
  6. While n = 1 t = 1 while n <

    5: print 'The %s. triangle number is %s' % (n, t) n += 1 t += n 12
  7. While Output: The 1. triangle number is 1 The 2.

    triangle number is 3 The 3. triangle number is 6 The 4. triangle number is 10 13
  8. For Output: Don't forget to buy bread Don't forget to

    buy apples Don't forget to buy jam 15
  9. Try try: self.add_friend(user) log.debug('Added friend!') except Error as e: log.debug('Failed

    to add friend: %s' % e.value) finally: log.debug('We tried to add a friend.') 16
  10. Bool False: False, 0, None, empty sequences or maps True:

    True, 1, non-empty sequences ... Cast to bool: bool([x]) 18
  11. Int >>> x = 3 >>> x = int(3) >>>

    x = int(3.3) >>> x 3 >>> 5 / 3 1 >>> 5.0 / 3 1.6666666666666667 19
  12. Strongly typed... >>> 1 + '2 fish' Traceback (most recent

    call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' 21
  13. ...but still dynamic >>> x = 1 >>> x =

    'flower' >>> x 'flower' 22
  14. List >>> numbers = [1, 2, 3] >>> numbers +

    [4] [1, 2, 3, 4] >>> numbers * 2 [1, 2, 3, 1, 2, 3] >>> numbers[0] = 5 >>> numbers [5, 2, 3] 24
  15. Tuple >>> animals = ('bee', 'bear') >>> animals * 2

    ('bee', 'bear', 'bee', 'bear') >>> animals[0] 'bee' >>> animals[0] = 'cat' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment 25
  16. String >>> flower1 = "tulep" >>> flower2 = "daffodil" >>>flowers

    = ", ".join([flower1, flower2]) >>>flowers 'tulep, daffodil' 26
  17. String >>>flowers 'tulep, daffodil' >>> flowers[3] = "i" Traceback (most

    recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment 27
  18. Looping over sequences >>> flower = "tulip" >>> for letter

    in flower: ... print letter ... t u l i p 28
  19. Slicing >>> flower = "tulip" >>> flower[1:4] 'uli' >>> flower1[1:4:2]

    'ui' >>> flower1[::2] 'tlp' >>> flower1[::-1] 'pilut' 29
  20. Dictionaries >>> books = {} >>> books["War and Peace"] =

    2 >>> books["Jane Eyre"] = 3 >>> books {'Jane Eyre': 3, 'War and Peace': 2} 31
  21. Keys >>> books.keys() ['Jane Eyre', 'War and Peace'] >>> for

    key in books: ... print key ... Jane Eyre War and Peace >>> "Love and Rockets" in books False 33
  22. iteritems() >>> for title, count in books.iteritems(): ... print title,

    count ... Jane Eyre 3 War and Peace 1 iteritems() creates a generator of key, value pairs 34
  23. List comprehensions >>> numbers = list(range(10)) >>> odds = []

    >>> for n in numbers: ... if n % 2 == 1: ... odds.append(n) ... >>> odds [1, 3, 5, 7, 9] 36
  24. List comprehensions [expression for item in list if conditional] >>>

    odds = [n for n in numbers if n % 2 == 1] >>> odds [1, 3, 5, 7, 9] 37
  25. List comprehensions [expression for item in list if conditional] >>>

    squares = [n * n for n in numbers] >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 38
  26. Dict comprehensions {key:value for item in list if conditional} >>>{n:

    n * n for n in numbers if n % 2 == 1} {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} Python 3.x only 39
  27. Functions def is_prime(n): m = 2 while m * m

    < n: if n % m == 0: return False m += 1 return True 41
  28. Optional arguments >>> def greet(name, time="day"): ... print "Good "

    + time + ", " + name ... >>> greet("Freda") Good day, Freda >>> greet("Bobby", "morning") Good morning, Bobby >>> greet(name="Jenny", time="evening") Good evening, Jenny 42
  29. *args and **kwargs >>> def what_are_flowers(f1, f2, f3): ... print

    "The flowers are %s, %s and %s." % (f1, f2, f3) ... >>> what_are_flowers("lily", "rose", "tulip") The flowers are lily, rose and tulip. 43
  30. *args and **kwargs The flowers are lily, rose and tulip

    >>> def what_are_flowers(*args): ... print "The flowers are " + ", ".join(args) ... >>> what_are_flowers("rose", "iris") The flowers are rose, iris >>> what_are_flowers("rose", "iris", "pansy") The flowers are rose, iris, pansy 44
  31. *args and **kwargs >>> flowers = {"poppy": 3, "rose": 2}

    >>> def what_are_flowers(**kwargs): ... for k, v in kwargs: ... print v + " flowers are " + k ... >>> what_are_flowers(**flowers) 3 flowers are poppy 2 flowers are rose 45
  32. *args and **kwargs >>> def inventory(bag, *args, **kwargs): ... print

    "bag: " + bag ... if args: ... print [a for a in args] ... if kwargs: ... print [k, v for k, v in kwargs. iteritems()] 46
  33. *args and **kwargs >>> inventory("sack", "apple", "cat", pencils=2, candles=3) bag:

    sack ['apple', 'cat'] {'pencils': 2, 'candles': 3} 47
  34. Splatting >>> a, b, c = (1, 2, 3) >>>

    a, b, c (1, 2, 3) >>> d, e, f = [1, 2, 3] >>> d, e, f (1, 2, 3) >>> g, h, i = '123' >>> g, h, i ('1', '2', '3') 48
  35. Module search path 1. Built-in modules 2. The current directory

    3. PYTHONPATH 4. Installation-dependent default 55
  36. What does virtualenv do? "A tool to create isolated Python

    environments" (https://virtualenv.pypa.io/en/latest/) 63
  37. How to use virtualenv? $ sudo pip install virtualenv $

    virtualenv venv $ cd venv $ ls bin include lib local $ source bin/activate (venv) $ 64
  38. Useful links The Python docs: https://docs.python.org/3/ Django: https://www.djangoproject.com/ IPython interactive

    shells: http://ipython.org/ Introduction to Python (Harvard): http://tdc- www.harvard.edu/Python.pdf 69