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

Introduction to Python

Introduction to Python

The slides of my brown bag session that briefly introduced the Python programming language! ^__^

Gianluca Costa

March 31, 2014
Tweet

More Decks by Gianluca Costa

Other Decks in Programming

Transcript

  1. Gianluca Costa
    Introduction to Python

    View Slide

  2. Main traits
    Interpreted
    Cross-technology
    Extensible
    Elegant
    VHLL

    View Slide

  3. Timeline
    1991 2000 2008
    Python 1.0 Python 2 Python 3
    2014
    Python 3.4
    Python 2.7

    View Slide

  4. The execution model
    x = 10
    print(x)
    Myscript.py The interpreter
    executes
    lines of code
    following
    the flow

    View Slide

  5. Running Python scripts

    python <br/>●<br/>On Windows: shell associations<br/>●<br/>On Linux: traditional #!<br/>

    View Slide

  6. Trying out Python
    Python's interpreter is interactive, too!

    View Slide

  7. Variables

    x = 10

    Later, you can write:
    x = “Hello”

    View Slide

  8. Names are remote controls
    10
    Hello
    x
    x = 10
    x = “Hello”

    View Slide

  9. Assignment
    The key to Python's naming is the
    assignment operator
    X = 10
    1)Expression evaluation
    2)Name creation & binding

    View Slide

  10. Basic data types

    bool: True, False

    str: “Cip”, 'Cip', r“\d+”, “““Multiline string”””

    unicode: u“Ciop”, u'Ciop', ur“\d+”,
    u“““Multiline”””

    int: 2 ** 90

    float: 5.3

    complex: 8 + 7j

    View Slide

  11. None

    X = None

    View Slide

  12. Inspecting a Python object

    type(obj)

    dir(obj)

    isinstance(obj, )

    obj is None

    obj is not None

    View Slide

  13. Strings: a warning

    In Python 2, str and unicode

    In Python 3, str and bytes

    View Slide

  14. Collections

    Arrays do not exist in Python (^__^!)

    list: [], [90, 100, 474, “Yogi”]

    tuple: (), (2,), (4.3, 12.1)

    dict: {}, {“Alpha”: 90, “Beta”: 2, 15: 20}

    set: set(), {1, 2, 3}

    View Slide

  15. Flow control

    if / elif / else

    while

    try / except / finally

    raise

    with

    for

    yield

    pass

    View Slide

  16. For in Python

    No C-style for

    Python only uses iterations on collections:
    – for i in range(10):
    print(i)

    View Slide

  17. List comprehension

    topStudents = [
    student
    for student in students
    if student.average >= 85
    ]

    coordinates = [
    (x + 5, y - 2)
    for x in range(1, 11)
    for y in range(1, 6)
    ]
    coordinates = [ ]
    for x in range(1, 11):
    for y in range(1, 6):
    coordinates.append(
    (x + 5, y – 2)
    )

    View Slide

  18. Exceptions
    try:
    raise MyException(“Epic!”)
    except (ExcType1, ExcType2) as ex:
    pass
    except ExcType3:
    pass
    except:
    pass
    finally:
    pass

    View Slide

  19. The WITH statement
    with open(“readme.txt”, “r”) as myFile:
    for line in myFile:
    #Process line here
    print(line)

    View Slide

  20. Functions

    def f(x, y):
    return x + y

    A new function object is created and the
    name “f” gets bound to it.

    View Slide

  21. Functions as objects

    def f(x, y):
    return x + y

    h = f

    h(90, 100)

    View Slide

  22. No overloading in Python

    In Python, def creates a function object
    and binds a name to it!

    Cannot do overloading!!! X___X!

    View Slide

  23. Parameters VS Argument

    Parameter = variable in a function
    signature. It's a placeholder for the actual
    value

    Argument = actual value passed when
    invoking the function

    View Slide

  24. Function parameters

    Standard parameters: f(x, y)

    Default values: f(x, y, z = 90)

    Arbitrary sequence: f(*args)

    Keyword params: f(**kwargs)

    They can all be introduced, in this order:
    f(x, y, z = 90, *args, **kwargs)

    View Slide

  25. Function arguments

    Given a function f(x, y)...

    ...pass by position: f(9, 10)

    ...pass by name: f(y = 10, x = 9)

    ...unpack a list of arguments:
    – myParamsSequence = [9, 10]
    – f(*myParamsSequence)

    ...pass a map of arguments:
    – myParamsMap = { “x”: 9, “y”: 10” }
    – f(**myParamsMap)

    View Slide

  26. Lambdas

    myFunction = lambda x, y: x + y

    myFunction(90, 100)

    View Slide

  27. Classes

    class Panda(object):
    pass #can be used for classes, too

    In Python 3, you can just write:
    class Panda:
    pass

    View Slide

  28. Creating methods

    class Panda(object):
    def sayHello(self):
    print(“Hello! ^__^!”)

    self is the first parameter of instance
    methods, and it's passed as an implicit
    argument! It refers to the current instance,
    just like this in Java/C#.

    View Slide

  29. No overloading for methods

    Methods are bound functions

    Methods do not support overloading

    View Slide

  30. Fields and constructor

    class Panda(object):
    def __init__(self, name):
    self._name = name
    self._picnicChests = 0
    def addPicnicChest(self, picnicChest):
    self._picnicChests += 1
    def getName(self):
    return self._name

    View Slide

  31. No access control in Python
    If a member of an object should not be
    used by other objects, just prepend “_” to
    its name.
    For example:

    self._privateField = 0

    def _privateMethod(self):
    pass

    View Slide

  32. Instantiating an object

    yogi = Panda(“Yogi”)

    print(yogi.name)

    yogi.addPicnicChest(myPicnicChest)

    View Slide

  33. Class fields

    class Panda(object):
    _population = 0
    def __init__(self):
    Panda._population += 1

    print(Panda._population)
    print(yogi._population)

    View Slide

  34. Class fields - Caveat

    yogi = Panda(“Yogi”)

    print(yogi._population)

    yogi._population = 10

    print(Panda._population) #Output == ?

    View Slide

  35. Object's name resolution
    3. Super namespaces
    2. Class namespace
    1. Object namespace
    … = obj.name

    View Slide

  36. Multiple inheritance

    Python does not define explicit interfaces...

    ...but it supports multiple inheritance!

    class Panda(Bear, VeryCuteAnimal):
    pass

    View Slide

  37. Diamond resolution
    Just too difficult to learn! ^__^''''

    View Slide

  38. Explicit method resolution

    Given an object instance, how to call the
    method of a specific superclass?
    – Super1.f(obj, )
    – Super2.f(obj, )

    View Slide

  39. Overriding methods

    Python supports overriding!

    But how to call the version provided by the
    superclass?

    View Slide

  40. super()

    super(CurrentClassName, self).f()

    In Python 3:
    super().f()

    Not mandatory (you can use explicit
    method resolution instead)

    View Slide

  41. Static methods

    class Panda(object):
    @staticmethod
    def myStaticMethod(x, y):
    return x+y

    Static methods can be called via the class
    or via any instance

    View Slide

  42. Class methods

    class Bear(object):
    @classmethod
    def f(cls, x, y):
    return x + y

    They can be called via class or instance

    View Slide

  43. Operator overloading

    To overload “+”
    – def __add__(self, other):
    return ...

    There are several operators available

    View Slide

  44. String representations (v. 2.x)

    __repr__(self)

    __str__(self)

    __unicode__(self)

    View Slide

  45. String representations (v. 3.x)

    __repr__(self)

    __bytes__(self)

    __str__(self)

    View Slide

  46. Equality and hashcode

    __eq__(self, other) and __neq__(self,
    other). Both should be implemented.

    __hash__(self) returns the hash code

    View Slide

  47. Comparisons

    Binary operators: __gt__, __gte__, __lt__,
    __lte__

    Alternatively, __cmp__ behaves just like
    Java's compareTo()

    View Slide

  48. Modules

    Python files are modules...

    ...but not all modules are files! ^__^!

    PYTHONPATH

    View Slide

  49. Importing a module

    import re

    from re import compile

    from re import * (good just while learning)

    View Slide

  50. Module caching and reloading

    Importing a module executes it only the first
    time

    The module cache is sys.modules

    reload() reloads a module

    .pyc files to optimize loading in future
    sessions

    View Slide

  51. Packages

    Python supports packages!

    Directory structure

    __init__.py

    Within a package, use relative import!

    View Slide

  52. Further execution options

    Py2exe for Windows

    PyInstaller for Windows & Unix

    Jython

    IronPython

    Boo

    View Slide