Introduction to Python


INTRODUCTION

  • Objectives :
    • to code in the interpretor and explore the basics of the language
    • to write a script that we'll run in the interpretor
  • Environment
    • text editor
    • python interpretor : python, ipython

BASIC NOTIONS

Interpretor

  • python, ipython
  • interactivity / introspection
    $ ipython
    

Syntax

Variables

  • name, value, reference
    a = 12
    b = a
    id(a)
    id(b)
    

Types

  • dynamique typing (no need to declare)
    n = None        # NoneType : special type meaning... nothing
    b = True        # bool : boolean... True or False don't forget the capital letter
    
    i = 15          # int : integer
    f = 15.5        # float : decimal
    
    s = "string"    # str : string, instanciated with "" or ''
    u = u"chaîne"   # unicode : unicode string, instanciated with u"" or u''
    
    l = []          # list : list of objects (ordered)
    t = ()          # tuple : immutable list of objects
    d = {}          # dict : dictionnary of data (unique, unordered)
    
    ens = set([])   # set : set (unique, unordered)
    
  • unpacking
    a, b = 34, 56
    
  • strongly typed (no implicit type conversion)
  • casting
    str(), int(), float(), bool(), list(), tuple(), dict(), set()
    float(a)
    

Built-in : built-in functions and language's structure

  • http://docs.python.org/library/functions.html
    type()                  # returns the type of the object
    dir()                   # returns the names on the object
    help()                  # returns the help
    callable()              # tells if an object is callable, executable...
    
    bool(), int(), str()... # initialisation or casting
    getattr()
    isinstance(objet, Type) # tests the class (or type) of an object
    issubclass()
    super()
    len()
    min()
    max()
    open()
    range()
    raw_input()
    
    print
    del
    

Objects and namespaces

  • objet.attribute
  • objet.method()
  • objet.attribute.method()

Introspection

  • variable. [+ tab]
  • variable?
  • type()
  • dir()
  • help()
  • exploration of types
  • concatenation : s1 + s2
name = "Davin Baragiotta" 
firstname, lastname = name.split()
lastname.upper()
lastname.lower()
lastname.ljust(30)
name = [firstname.lower(), lastname.lower()]
username = ".".join(name)

name = "Davin Baragiotta" 
username = ".".join(name.split()).lower()

users = []
users.append(username)

davin = {'firstname':'Davin', 'lastname':'Baragiotta'}
pascal = {'firstname':'Pascal', 'lastname':'Bou Nassar'}

people = []
people.append(davin)
people.append(pascal)

statuses = [
    (1, u'New'),
    (2, u'In progress'),
    (3, u'Rejected'),
    (4, u'Selected'),
]

Containers

  • imbrication
    l = [[1,2,3],[4,'hello',6],[7,8,9]]
    d = {1611: {'lastname':'Baragiotta', 'firstname':'Davin'}, 123: {'lastname':'Bou Nassar', 'firstname':'Pascal'}}
    
  • index
    l[2], d[1611]
    
  • slicing
    l[0:2]
    

Iteration

  • while
    year = 2012
    while year <= 2015:
        print year
        year = year + 1   # year += 1
    
  • for
    for year in range(2012, 2016):
        print year
    

Comparisons and logic operators

  • false = False, 0, "", (), [], {}, None
  • and, or, not
  • < > <= >= == !=
  • x < y <= z
  • is, is not
  • in, not in

Conditionnal

  • if, elif, else
    numbers = range(6)
    if 5 in numbers:
        print 'hourra 5'
    elif 4 in numbers:
        print 'hourra 4'
    else:
        print 'pas hourra'
    

Files

  • open, manipulate, close
    f = open('text.txt')
    for line in f.readlines():
        print line,
    f.close()
    

String formatting

  • substitution : %
    for n in range(10):
        print "%d power 2 is : %d" % (n, n**2)
    
    for p in people:
        print "Hello %s %s" % (p['firstname'], p['lastname'].upper())
    

List comprehension

  • creates a list from an iterable in a one-liner
    target = 'Egypt'
    context = [line for line in f.readlines() if target in line]
    comments = [line for line in f.readlines() if line.startswith('#')]
    

Scripts

#! /usr/bin/env python
# -*- encoding: utf-8 -*-

def hello(name):
    return u"Hello %s!" % (name,)

if __name__ == '__main__':
    print u"--------------------------------------------------" 
    print u"START script" 
    print u"--------------------------------------------------" 
    name = raw_input("What is your name? ")
    print hello(name)
    print u"-----------------------------------------------" 
    print u"END script" 
    print u"-------------------------------------------------" 
  • shebang : #! /usr/bin/env python
  • encoding : # encoding: utf-8
  • if __name__ == '__main__':
  • raw_input()
  • create a project/contacts directory
  • create in this directory a Python script named form.py that :
    • asks the user its lastname, firstname and year of birth
    • salutes the user by printing its firstname plus its lastname in capital letters
  • execution ipython : run script
  • execution python :
    $ python script.py
    

Functions

  • naming convention
  • output : None by default
  • input : positional parameters, named parameters, *args, **kwargs
  • scope of variables
def age(year_birth):
    return 2012 - year_birth

def my_function(param1, param2, param3=None, param4=0, *args, **kwargs):
    """This is my function.""" 
    output = True
    return output

Import

  • import module
  • from module import name
  • from module import name as my_name
  • built-in : no need to import
  • standard library (shipped with) : import without install
    from datetime import datetime
    
    date = datetime.now()
    #year = ??
    
  • packages : importable if installed in the path
    import sys
    sys.path
    
  • in the directory project/contacts, create a Python script named lib.py
  • declare the function age in this script
  • in ipython,make sure you are in project/contacts then test the import of this function
    import lib
    my_year_birth = 1975
    lib.age(my_year_birth)
    
  • improve form.py by giving to the user its age after the salute

Modules

  • __init__.py
  • __name__ : name of the module, name of the file if imported, '__ main __' if executed (useful for tests)
  • add a __init__.py file in the project/contacts directory to convert it in a module
  • create a tests.py file at the root of the projet/ directory (to create a test suite)
  • import the age function in tests.py to test it

Data persistence

  • files
  • serialisation : import pickle
    import pickle
    
    f = open('pickles', 'w')
    pickle.dump(statuses, f)
    pickle.dump(people, f)
    f.close()
    
    exit()
    
    import pickle
    
    f = open('pickles')
    pickle.load(f)
    #objets = []
    #for obj in pickle.load(f):
    #    objets.append(obj)
    f.close()
    
  • DB : sqlite3, mysqldb, psycopg2
  • ORM : sqlalchemy

EXERCICE

Objective

To create a script feed.py in the projet/news directory that will return the
5 last news (blog posts) displayed on Montréal-Python website :
http://montrealpython.org/feed/

Approach

  1. use python-feedparser
    • Ubuntu : sudo apt-get install python-feedparser
  2. launch the interpretor and follow the example in the doc :
  3. introspect (and print the dictionnary to see its keys) at need
  4. code the script doing the desired treatment
  5. launch the script in the interpretor to confirm its correct execution
  6. serve cold

Algorithm

  • catch the RSS feed of http://montrealpython.org
  • keep the desired number of items
  • treat the selected items :
    • create a unique string with the infos of the last modified items (title, URL... and eventually date of modification)

Solution

Take time to code yourself a solution...
... then compare it with : the solution

Hint: this Python solution is only 8 lines long.

CONCLUSION

  • documentation + interactivity + introspection
  • scripts + modules
  • enjoy!