Introducing Python
by Example

Enrico Franchi
efranchi@ce.unipr.it


                       1
Outline                                       2

 Very (very )* short introduction to Python
 Some small examples
 Evolutionary game
Parlando del
futuro...                               3
We will perhaps eventually be
writing only small modules that are
identified by name as they are
used to build larger ones, so that
devices like indentation, rather than
delimiters, might become feasible
for expressing local structure in the
source language.

Donald E. Knuth, Structured
Programming with go to
Statements, 1974
Introduzione                                                 4

 Python è concepito da Guido van Rossum alla fine
 degli anni ‘80 per Amoeba
 Pubblico 1991, stabile 1994.
 Linguaggio di alto livello ed orientato agli oggetti.
 Utilizzato per programmazione di sistema e di rete, e
 calcolo scientifico, applicazioni desktop, integrazione di
 videogiochi, MMORPG backend, ...
 Si impone in ambito web/enterprise, con soluzioni
 come Zope/Plone, Django,Twisted, GAE, OpenERP.
5



READABILITY
  COUNTS
        Zen of Python
Oggetti in Python                              6

 In Python tutto è un oggetto:
   Un numero, una stringa sono oggetti
   Gli oggetti sono oggetti (ehm...)
   Una funzione è un oggetto
   Una classe è un oggetto
 Gli oggetti sono cittadini di prima classe,
 possiamo manipolarli riccamente e
 comodamente (introspezione, etc.)
 Possiamo fare, in definitiva, tutto
Tipizzazione in Python                                       7

 Python è un linguaggio ad oggetti a tipizzazione
 dinamica e forte
   Tipizzazione forte:
     Gli errori di tipo sono sempre generati. Es. Stringhe
     non diventano interi e viceversa
     Ogni oggetto ha una classe, questa non cambia
   Tipizzazione dinamica
     Gli errori di tipo sono generati a runtime
     Duck typing
Hello, world!                  8




 print	
  “Hello,	
  world!”
Dettagli implementativi                                    9

                                $ cat hello.py
 Tipicamente Python viene
                                #!/usr/bin/python
 compilato a byte-code e
 questo viene interpretato da   print "Hello, world!"
 una macchina virtuale (come
                                $ python hello.py
 Java)                          Hello, world!
 Diversamente da Java la        $ chmod 755 hello.py
                                $ ./hello.py
 compilazione è trasparente     Hello, world!
 per l’utente                   $ python
                                Python 2.5.1 (...)
 Possiamo anche usare           ...
 l’interprete interattivo       >>> print "Hello, world"
                                Hello, world
Interprete interattivo                                              10

 L’interprete interattivo ufficiale ha
                                        >>> import os
 come prompt >>>                        >>> print “foo”
                                        foo
 Scriviamo comandi (statements)         >>> os.getcwd()
                                        “/Users/enric/pycourse”
 che vengono byte-compilati ed          >>> import sys
 eseguiti                               >>> sys.stdout.write(“ciaon”)
                                        ciao
 Se il comando valuta in un             >>> def f(a):
                                        ...      sys.stdout.write(a)
 espressione (es. un expression         ...      return a
                                        ...
 statement), l’espressione viene        >>> f(“ciaon”)
 stampata                               ciao
                                        “ciaon”
Esempio 01:
System Scripting                                  11




     import os
     import shutil

     for fname in os.listdir(os.getcwd()):
         if fname.endswith(('pyc', 'pyo')):
             os.remove(fname)
         elif fname.endswith('py'):
             shutil.copy(fname, fname + '.bak')
Esempio 2:
“semplice wget” (GvR)                         12


      import sys
      import urllib
      import os


      def hook(*a):
          print '%s: %s' % (fn, a)

      for url in sys.argv[1:]:
          fn = os.path.basename(url)
          print url, "->", fn
          urllib.urlretrieve(url, fn, hook)
Evolution!                              13




             https://github.com/rik0/isle
Animals                                                             14

                         Animal                      Dir    Gene
 0   1   2
             + x : int
             + y : int                                0      1
 7   M   3                                            1      1
             + energy : int
             + dir : int                              2      10
 6   5   4                                            3      1
             + genes : int[8]
             + move() : void                          4      1
             + turn() : void                          5      1
             + eat(plants : cell[0..]) : void         6      1
             + reproduce() : Animal[0..1]             7      1




                                         https://github.com/rik0/isle
UI
https://github.com/rik0/isle        15

Pycrashcourse4.0 pdfjam

  • 1.
    Introducing Python by Example EnricoFranchi efranchi@ce.unipr.it 1
  • 2.
    Outline 2 Very (very )* short introduction to Python Some small examples Evolutionary game
  • 3.
    Parlando del futuro... 3 We will perhaps eventually be writing only small modules that are identified by name as they are used to build larger ones, so that devices like indentation, rather than delimiters, might become feasible for expressing local structure in the source language. Donald E. Knuth, Structured Programming with go to Statements, 1974
  • 4.
    Introduzione 4 Python è concepito da Guido van Rossum alla fine degli anni ‘80 per Amoeba Pubblico 1991, stabile 1994. Linguaggio di alto livello ed orientato agli oggetti. Utilizzato per programmazione di sistema e di rete, e calcolo scientifico, applicazioni desktop, integrazione di videogiochi, MMORPG backend, ... Si impone in ambito web/enterprise, con soluzioni come Zope/Plone, Django,Twisted, GAE, OpenERP.
  • 5.
    5 READABILITY COUNTS Zen of Python
  • 6.
    Oggetti in Python 6 In Python tutto è un oggetto: Un numero, una stringa sono oggetti Gli oggetti sono oggetti (ehm...) Una funzione è un oggetto Una classe è un oggetto Gli oggetti sono cittadini di prima classe, possiamo manipolarli riccamente e comodamente (introspezione, etc.) Possiamo fare, in definitiva, tutto
  • 7.
    Tipizzazione in Python 7 Python è un linguaggio ad oggetti a tipizzazione dinamica e forte Tipizzazione forte: Gli errori di tipo sono sempre generati. Es. Stringhe non diventano interi e viceversa Ogni oggetto ha una classe, questa non cambia Tipizzazione dinamica Gli errori di tipo sono generati a runtime Duck typing
  • 8.
    Hello, world! 8 print  “Hello,  world!”
  • 9.
    Dettagli implementativi 9 $ cat hello.py Tipicamente Python viene #!/usr/bin/python compilato a byte-code e questo viene interpretato da print "Hello, world!" una macchina virtuale (come $ python hello.py Java) Hello, world! Diversamente da Java la $ chmod 755 hello.py $ ./hello.py compilazione è trasparente Hello, world! per l’utente $ python Python 2.5.1 (...) Possiamo anche usare ... l’interprete interattivo >>> print "Hello, world" Hello, world
  • 10.
    Interprete interattivo 10 L’interprete interattivo ufficiale ha >>> import os come prompt >>> >>> print “foo” foo Scriviamo comandi (statements) >>> os.getcwd() “/Users/enric/pycourse” che vengono byte-compilati ed >>> import sys eseguiti >>> sys.stdout.write(“ciaon”) ciao Se il comando valuta in un >>> def f(a): ... sys.stdout.write(a) espressione (es. un expression ... return a ... statement), l’espressione viene >>> f(“ciaon”) stampata ciao “ciaon”
  • 11.
    Esempio 01: System Scripting 11 import os import shutil for fname in os.listdir(os.getcwd()): if fname.endswith(('pyc', 'pyo')): os.remove(fname) elif fname.endswith('py'): shutil.copy(fname, fname + '.bak')
  • 12.
    Esempio 2: “semplice wget”(GvR) 12 import sys import urllib import os def hook(*a): print '%s: %s' % (fn, a) for url in sys.argv[1:]: fn = os.path.basename(url) print url, "->", fn urllib.urlretrieve(url, fn, hook)
  • 13.
    Evolution! 13 https://github.com/rik0/isle
  • 14.
    Animals 14 Animal Dir Gene 0 1 2 + x : int + y : int 0 1 7 M 3 1 1 + energy : int + dir : int 2 10 6 5 4 3 1 + genes : int[8] + move() : void 4 1 + turn() : void 5 1 + eat(plants : cell[0..]) : void 6 1 + reproduce() : Animal[0..1] 7 1 https://github.com/rik0/isle
  • 15.