Python – Fundamentals – How I Learned to Stop Worrying and Love the Whitespace



Python – Fundamentals – How I Learned to Stop Worrying and Love the Whitespace

0 0


python_fundamentals

Slides for Python Fundamentals

On Github gotgenes / python_fundamentals

Python

Fundamentals

or

How I Learned to Stop Worrying and Love the Whitespace

Created by Chris Lasher of 5AM Solutions, Inc.

Python is...

  • an interpreted, dynamically-typed, strongly-typed, multi-paradigm application language
  • named for Monty Python's Flying Circus
  • overseen by its creator, Guido van Rossum, a.k.a. the Benevolent Dictator For Life (BDFL)
  • basically awesome

Python looks like...

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# Copyright (c) 2011-2013 Christopher D. Lasher
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.


"""A collection of common utilities and convenient functions."""

import csv
import os.path


class SimpleTsvDialect(csv.excel_tab):
    """A simple tab-separated values dialect.


    This Dialect is similar to :class:`csv.excel_tab`, but uses
    ``'\\n'`` as the line terminator and does no special quoting.

    """
    lineterminator = '\n'
    quoting = csv.QUOTE_NONE


csv.register_dialect('simple_tsv', SimpleTsvDialect)


def make_csv_reader(csvfile, header=True, dialect=None, *args,
                    **kwargs):
    """Creates a CSV reader given a CSV file.

    :param csvfile: a file handle to a CSV file
    :param header: whether or not the file has header
    :param dialect: a :class:`csv.Dialect` instance
    :param *args: passed on to the reader
    :param **kwargs: passed on to the reader

    """
    if dialect is None:
        try:
            dialect = csv.Sniffer().sniff(csvfile.read(1024))
        except csv.Error:
            dialect = csv.excel
        csvfile.seek(0)
    if header:
        csv_reader = csv.DictReader(csvfile, dialect=dialect, *args,
                **kwargs)
    else:
        csv_reader = csv.reader(csvfile, dialect=dialect, *args,
                **kwargs)
    return csv_reader

Python is good for...

  • Rapid development
  • Modularity
  • Readable code
  • Documentation
  • Glue (interfaces with C/C++ code)
  • Web programming
  • Science!!!

Python is bad for...

  • Closed source
    • Counterpoint: awesome open source community
  • Speed
    • Counterpoint: wrap C library or use NumPy/SciPy
  • Preventing attribute access (no private/protected)
    • Counterpoint: “We're all adults here.”
    • Counterpoint: Code conventions (prefix with underscore, e.g., _private_var)

Python is an interpreted language

  • Source code files processed at runtime by interpreter
  • Interactive Intepreter (REPL)

Python Interpreter

  • Source code organized as individual scripts, modules, packages, or entire applications
  • Python interpreter invoked on a script or entry module
  • Multiple interpreter implementations
    • CPython interpreter implementation usually what people mean by “Python”
    • Jython (implemented on JVM)
    • IronPython (implemented on .Net)
    • PyPy (Python interpreter implemented in Python)

Interactive Interpreters (REPL)

Presentation code conventions

Python script/module

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

a = 1
b = 2
c = a + b
print(c)

Interactive Interpreter

>>> a = 1
>>> b = 2
>>> a + b
3

Mega-bonus "executables"

Brought to you by Online Python Tutor

Everything is an object

  • Every entity is a first-class entity
  • Objects have a specific “type”
  • Variables are just references to objects

Variables are just named references

Reassigning a variable affects only that one

Python is dynamically typed

Python is strongly typed

>>> "The value is " + 2    # gives "The value is 2" ???
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
          </module></stdin>
>>> "The value is " + str(2)
'The value is 2'
>>> "The value is {}".format(2)   # The "Pythonic" way
'The value is 2'

Python types fall into two categories

  • immutable (essentially all basic types)
  • mutable (essentially all containers)

Immutable types

Basic Immutable Types

  • None (Python's null)
  • Numeric
    • Integer: -1, 9001, etc.
    • Float: 3.1459
    • Complex: 44+2j
  • Boolean (technically subclass of integer): True or False
  • Strings
  • Tuples

Immutable types are immutable!

Python strings come in two flavors

  • Unicode strings
  • Byte strings

Unicode Strings

  • Default in Python 3
  • Handle crazy characters just fine
    msg = 'Wi nøt trei a høliday in Sweden this yër?'
  • In Python 2, prepend a u,
    msg = u"See the løveli lakes"

Byte Strings

  • default in Python 2
  • only handle 256-bit encodings (think ASCII, ISO-8859-1); explicitly encode high-level bytes
  • in Python 3 used for working directly with bytes
  • in Python 3, create by prepending a b
    msg = b'See the l\xc3\xb8veli lakes'

Quote Types

  • Either single quote ' or double quote " may be used; functionally equivalent
  • Triple-quoted strings (''' or """) preserve whitespace:
    >>> s = '''A triple-quoted
      ... string can
      ...     preserve
      ...         whitespace
      ... '''
      >>> s
      'A triple-quoted\nstring can\n    preserve\n        whitespace\n'

Tuples are ordered collections

  • Tuples are created using parentheses:
    ('a', 'b', 42)
  • Tuples can contain any other object:
    ((1, 2),)   # single-element tuple containing another
  • Objects do not have to be of the same type

Indexing

>>> a = (1, 2, (3, 4))
>>> a[0]   # access the first element
1
>>> a[-1]  # access the last element
(3, 4)
>>> a[-1][0]  # access the first element of the last element
3

Slicing

  • Access multiple elements simultaneously by slicing
  • Slicing syntax
    variable[start_index:stop_index:step_size]
  • Any of start_index, stop_index, and step_size may be omitted
  • Interval is zero-based, half-open; read a slice as "going from start_index up to, but not including stop_index
>>> a = (1, 2, 3)
>>> a[1:3]
(2, 3)
>>> a[1:]
(2, 3)
>>> a[:2]
(1, 2)
>>> a[::2]
(1, 3)

Iterable Types

  • Lists
  • Dictionaries
  • Sets

Lists

  • Mutable collections of other objects
  • vs. tuples: When in doubt, use lists
  • Indexing and slicing work as tuples
>>> a = [81, 82, 83]
>>> a[0]
81
>>> a[1]
82
>>> a[:2]
[81, 82]
Can reassign to lists
>>> a
[81, 82, 83]
>>> a[0] = 'spam'
>>> a
['spam', 82, 83]

Mutable, mutable lists

>>> a
['spam', 82, 83]
>>> a.index('spam')
0
>>> del a[0]
>>> a
[82, 83]
>>> a.remove(83)
>>> a
[82]
>>> elem = a.pop()
>>> elem
82
>>> a
[]
>>> a.append(elem)
>>> a
[82]
>>> a.insert(0, 81)
>>> a
[81, 82]
>>> a.extend([83, 84, 85])
>>> a
[81, 82, 83, 84, 85]
>>> a[1:1] = ['happy', 'joy']
>>> a
[81, 'happy', 'joy', 82, 83, 84, 85]

Altering mutable objects may cause side-effects

Truthiness

Flow control

Functions

Classes

Importing other modules

Packaging