SlideShare ist ein Scribd-Unternehmen logo
1 von 70
Downloaden Sie, um offline zu lesen
Crashkurs
Crashkurs


<reloaded>
Strukturierung durch Einrückung

def berechne_fakultaet(num): {
    if num == 0: {
        return 1
    }
    result = num * berechne_fakultaet(num - 1)
    return result
}




Python kennt keine Klammern für { Codeblöcke }




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            3
Strukturierung durch Einrückung

def berechne_fakultaet(num):
    if num == 0:
        return 1

      result = num * berechne_fakultaet(num - 1)
      return result




Whitespaces am Zeilenanfang sind syntaktisch relevant
1 Tabulator entspricht 8 Leerzeichen




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            4
Strukturierung durch Einrückung

def berechne_fakultaet(num):
....if num == 0:
........return 1
........
....result = num * berechne_fakultaet(num - 1)
....return result
....




Konvention:
Einrücktiefe pro Block: 4 Leerzeichen
Verwende nur Leerzeichen, keine Tabulatoren!




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            5
Interaktiver Interpreter

MacPro:~ klaus$ python
Python 2.7 (r27:82500, Jul 26 2010, 10:14:29)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>>    def berechne_fakultaet(num):
...        if num == 0:
...            return 1
...        result = num * berechne_fakultaet(num - 1)
...        return result
...
>>>    berechne_fakultaet(2)
2
>>>    berechne_fakultaet(3)
6
>>>    berechne_fakultaet(6)
720




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            6
Welche Version wählen?


Python 2 oder Python 3?

                               (         )

• geringe Differenzen: viele Backports von Python 3 nach Python 2.7
• 2to3-Tool: z.B.: „print n“            „print(n)“
• Problem: externe Libraries




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            7
Objektorientierung


Python kennt nur Objekte:

                      type

• Alle Datenobjekte sind vom Typ type
• Alle Funktionen und Klassen sind vom Typ type
• Objekte vom Typ type sind „callable“




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            8
Datenobjekte


                 Type                                       Beispiel         variabel

               Integer                                           42         immutable

                 Float                                         42.0         immutable

                String                                     „python“         immutable

                  List                           [42, „python“, 42.0]        mutable

                Tuple                            (42, „python“, 42.0)       immutable

            Dictionary                            {„one“: 1, 2: „two“}       mutable




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                        9
Listen

>>> liste_1 = [1, 2, 3, 4]




•Instanziierung eines Listen-Objekts durch: [ ]




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            10
Listen

>>> liste_1 = [1, 2, 3, 4]
>>> liste_1[0]
1




•Instanziierung eines Listen-Objekts durch: [ ]
•Listen-Index ist 0-basiert.



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            11
Listen

>>> liste_1 = [1, 2, 3, 4]
>>> liste_1[0]
1

>>> liste_1[-1]
4




•Instanziierung eines Listen-Objekts durch: [ ]
•Listen-Index ist 0-basiert.
•Index-Zugriff „von hinten“ möglich: [-1]

Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            12
Listen

>>> liste_1 = range(10)
>>> liste_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> liste_1[-1]
9




•Instanziierung eines Listen-Objekts durch: [ ]
•Listen-Index ist 0-basiert.
•Index-Zugriff „von hinten“ möglich: [-1]

Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            13
Listen

>>> liste_1 = range(10)
>>> liste_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> liste_1[-1]
9
>>> liste_1[-2]
8




•Index-Zugriff „von hinten“ möglich: [-2]




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            14
Listen

>>> liste_1 = range(10)
>>> liste_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> liste_1[1:3]
[1, 2]




•Listen bieten Slicing: [p, q[




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            15
Listen

>>> liste_1 = range(10)
>>> liste_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> liste_1[1:3]
[1, 2]

>>> liste_1[:3]
[0, 1, 2]




•Listen bieten Slicing: [p, q[
•Default: [:n] entspricht [0:n]



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            16
Listen

>>> liste_1 = range(10)
>>> liste_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> liste_1[1:3]
[1, 2]

>>> liste_1[:3]
[0, 1, 2]

>>> liste_1[3:]
[3, 4, 5, 6, 7, 8, 9]




•Listen bieten Slicing: [p, q[
•Default: [:n] entspricht [0:n]
•Default: [m:] entspricht [m:0]

Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            17
Listen

>>> liste_1 = range(10)
>>> liste_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> liste_1[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]




•Default: [:] entspricht [0:0] (Kopie)




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            18
Listen

>>> liste_1 = range(10)
>>> liste_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> liste_1[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> liste_1[::3]
[0, 3, 6, 9]




•Default: [:] entspricht [0:0] (Kopie)
•Slicing mit Intervall möglich: [m:n:i]



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            19
Listen

>>> liste_2 = [4, "five", berechne_fakultaet, liste_1]




•Listen können beliebige Objekte enthalten




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            20
Listen

>>> liste_2 = [4, "five", berechne_fakultaet, liste_1]
>>> liste_2
[4, 'five', <function berechne_fakultaet at 0x1004846e0>, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]


>>> liste_2[-1][-1]
9




•Listen können beliebige Objekte enthalten
•Aufbau komplexer Datenstrukturen möglich



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                        21
Listen

>>> liste_2 = [4, "five", berechne_fakultaet, liste_1]
>>> liste_2
[4, 'five', <function berechne_fakultaet at 0x1004846e0>, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]


>>> liste_2[-1][-1]
9

>>> liste_2[2](6)
720




•Listen können beliebige Objekte enthalten
•Aufbau komplexer Datenstrukturen möglich
•Funktionsaufrufe aus Listen möglich

Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                        22
Zeichenketten

>>> text = 'Dies ist ein String'
>>> text[0]
'D'
>>> text[-1]
'g'
>>> text[-6:]
'String'
>>> text.split()[-1]
'String'




•Zeichenketten sind Sequenzen
•Zeichenketten sind Objekte mit Methoden



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            23
Dictionaries

>>> dict_1 = {"one": 1, "two": 2}




•Dictionary: key-value-storage




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            24
Dictionaries

>>> dict_1 = {"one": 1, "two": 2}
>>> dict_1
{'two': 2, 'one': 1}




•Dictionary: key-value-storage
•Inhalte unsortiert



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            25
Dictionaries

>>> dict_1 = {"one": 1, "two": 2}
>>> dict_1
{'two': 2, 'one': 1}

>>> dict_1["two"]
2




•Dictionary: key-value-storage
•Inhalte unsortiert
•Zugriff per „key“

Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            26
Dictionaries

>>> dict_1 = {"one": 1, "two": 2}
>>> dict_1
{'two': 2, 'one': 1}

>>> dict_1["liste_2"] = liste_2
>>> dict_1
{'liste_2': [4, 'five', <function berechne_fakultaet at 0x1004846e0>, [0, 1, 2,
3, 4, 5, 6, 7, 8, 9]], 'two': 2, 'one': 1}




•Dictionary: key-value-storage
•Inhalte unsortiert
•Zugriff per „key“
•Beliebige Objekte als „value“
Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                  27
Dictionaries

>>> dict_1 = {"one": 1, "two": 2}
>>> dict_1["liste_2"] = liste_2
>>> dict_1
{'liste_2': [4, 'five', <function berechne_fakultaet at 0x1004846e0>, [0, 1, 2,
3, 4, 5, 6, 7, 8, 9]], 'two': 2, 'one': 1}

>>> dict_1["two"]
2
>>> dict_1["liste_2"][-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> dict_1["liste_2"][2](6)
720



•Dictionary: key-value-storage
•Inhalte unsortiert
•Zugriff per „key“
•Beliebige Objekte als „value“
Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                  28
Label


Referenzierung immutabler Datenobjekte:

>>> a = b = 42                                                              Label   Objekt
>>> a, b
(42, 42)
>>>                                                                           a       42

                                                                              b




•Daten sind Objekte
•„Variable“ sind Referenzen (Label) auf diese Objekte



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                             29
Label


Referenzierung immutabler Datenobjekte:

>>> a = b = 42                                                              Label   Objekt
>>> a, b
(42, 42)
>>> b = 4                                                                     a       42
>>> a, b
(42, 4)
>>>                                                                           b       4




•Daten sind Objekte
•„Variable“ sind Referenzen (Label) auf diese Objekte



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                             30
Label


Referenzierung mutabler Datenobjekte:

>>> l1 = ['one']                                                            Label       Objekt



                                                                             l1     ['one']




•Daten sind Objekte
•„Variable“ sind Referenzen (Label) auf diese Objekte



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                                 31
Label


Referenzierung mutabler Datenobjekte:

>>> l1 = ['one']                                                            Label       Objekt
>>> l2 = l1

                                                                             l1     ['one']


                                                                             l2




•Daten sind Objekte
•„Variable“ sind Referenzen (Label) auf diese Objekte



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                                 32
Label


Referenzierung mutabler Datenobjekte:

>>> l1 = ['one']                                                            Label           Objekt
>>> l2 = l1
>>> l2.append('two')
                                                                             l1        ['one']


                                                                             l2
                                                                                            .append('two')



                                                                                    ['one', 'two']

•Daten sind Objekte
•„Variable“ sind Referenzen (Label) auf diese Objekte



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                                     33
Label


Referenzierung mutabler Datenobjekte:

>>> l1 = ['one']                                                            Label           Objekt
>>> l2 = l1
>>> l2.append('two')
>>> l1                                                                       l1        ['one']
['one', 'two']

                                                                             l2
                                                                                            .append('two')



                                                                                    ['one', 'two']

•Daten sind Objekte
•„Variable“ sind Referenzen (Label) auf diese Objekte



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                                     34
Datenobjekte: boolscher Kontext


           Datenobjekt                                boolscher Wert        Singleton
                  True                                         True            ja
                  False                                        False           ja
                 None                                          False           ja
                     0                                         False
                   0.0                                         False
                     1                                         True
                    []                                         False
                    {}                                         False
                    ""                                         False
                    ""                                         True




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                        35
Datenobjekte: boolscher Kontext


Vorsicht vor Fließkommazahlen:


>>> p = 3 * 2.7 / 3 - 2.7
>>> p
4.440892098500626e-16
>>> if p:
...    print True
... else:
...    print False
...
True




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            36
Kontrollanweisungen

# if-then-else in Python:                                                   # Auswahl Vergleichsoperatoren:
>>> a = 1                                                                   >>> a = 1
>>> if a == 42:                                                             >>> b = 42
...     print "Das ist die Antwort"                                         >>> a != b
... elif a == 41:                                                           True
...     print "knapp daneben"                                               >>> a < b
... elif a == 43:                                                           True
...     print "auch daneben"                                                >>> c = 43
... else:                                                                   >>> a < b < c
...     print "leider ganz falsch"                                          True
...
leider ganz falsch




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                                              37
Schleifen

„for“ für Iterationen über gegebene Sequenzen

>>> for n in range(20):                          # iteriert über n von [0, 20[
...     if not n % 3:
...             continue                         # erzwingt nächsten Schleifendurchlauf
...     if n > 10:
...             break                            # erzwingt Schleifenabbruch
...     print n
...
1
2
4
5
7
8
10
>>>




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                          38
Schleifen

„while“ für Schleifen mit programmatischen Abbruch

>>> import random
>>> run = True
>>> while run:
...     r = random.random()
...     run = r < 0.8
...     print r
...
0.783283639782
0.282615658576
0.821162495507
>>>




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            39
Funktionen


Erhalten Argumente und liefern Ergebnisse

def berechne_fakultaet(num):
    if num == 0:
        return 1
    result = num * berechne_fakultaet(num - 1)
    return result



Allgemein:

def <name>(arg1, arg2, ... argN):
    <statements>
    return <value>




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            40
Funktionen


Argumente: Abgleich von links nach rechts


>>> def booktitle(title, author):
... 	 # title, author: required parameters
... 	 print "Author: %snTitle: %s" % (author, title)
...

>>> booktitle('Solaris', 'Lem')
Author: Lem
Title: Solaris




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            41
Funktionen


Argumente: Abgleich von links nach rechts


>>> def booktitle(title, author):
... 	 # title, author: required parameters
... 	 print "Author: %snTitle: %s" % (author, title)
...

>>> booktitle('Solaris', 'Lem')
Author: Lem
Title: Solaris

>>> booktitle('Der Hobbit')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: booktitle() takes exactly 2 arguments (1 given)




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            42
Funktionen


Argumente: Abgleich nach Argumentname


>>> def booktitle(title, author):
... 	 # title, author: required parameters
... 	 print "Author: %snTitle: %s" % (author, title)
...

>>> booktitle('Solaris', 'Lem')
Author: Lem
Title: Solaris

>>> booktitle(author='Tolkien', title='Der Hobbit')
Author: Tolkien
Title: Der Hobbit




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            43
Funktionen


Argumente: Abgleich nach Position und Argumentname


>>> def booktitle(title, author):
... 	 # title, author: required parameters
... 	 print "Author: %snTitle: %s" % (author, title)
...

>>> booktitle('Solaris', author='Lem')
Author: Lem
Title: Solaris

>>> booktitle(author='Lem', 'Solaris')
  File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            44
Funktionen


Argumente: Defaultwerte


>>> def booktitle(title, author='unknown'):
... 	 print "Author: %snTitle: %s" % (author, title)
...

>>> booktitle('Der Schwarm')
Author: unknown
Title: Der Schwarm

>>> booktitle('Der Schwarm', 'Frank Schätzing')
Author: Frank Schätzing
Title: Der Schwarm

>>> booktitle('Der Schwarm', author='Frank Schätzing')
Author: Frank Schätzing
Title: Der Schwarm




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            45
Funktionen


Argumente: variable Anzahl


# positionierte Argumente
>>> def func(*args):
... 	 print args
...
>>> func(1, 2, 42, 'vier')
(1, 2, 42, 'vier')

# keyword Argumente
>>> def func(**kwargs):
... 	 print kwargs
...
>>> func(author='Lem', title='Solaris')
{'title': 'Solaris', 'author': 'Lem'}




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            46
Funktionen


Funktionen sind Namensräume


>>> def changer(x, y):
... 	 x = 2
... 	 y[0] = 'spam'
...

>>> x = 1
>>> z = [42, 'ham', 'eggs']
>>> changer(x, z)
>>> x
1
>>> z
['spam', 'ham', 'eggs']




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            47
Funktionen


Funktionen sind Namensräume
                                                                            LGB-Regel:
>>> x = 1
>>> y = 2                                                                   local
>>> z = 5                                                                   global
                                                                            buildin
>>>    def spam():
...    	 global y
...    	 x = 42
...    	y = 3
...    	 print x, y, z
...

>>> spam()
42 3 5

>>> print x, y, z
1 3 5



Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                         48
Funktionen


Funktionen sind (wirklich!) Namensräume


>>> x = 1
>>> y = 2
>>> def spam():
... 	 print y
... 	 print x
... 	 x = 42
... 	 print x
...
>>> spam()
2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in spam
UnboundLocalError: local variable 'x' referenced before assignment




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            49
Module


Strukturieren und Wiederverwertung von Code


# datei: fakultaet.py

def berechne_fakultaet(num):
    if num == 0:
        return 1
    result = num * berechne_fakultaet(num - 1)
    return result

print berechne_fakultaet(5)




MacPro:module klaus$ python2.7 fakultaet.py
120




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            50
Module


Module sind Namensräume


# datei: main.py

import fakultaet
print fakultaet.berechne_fakultaet(6)




MacPro:module klaus$ python2.7 main.py
120
720




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            51
Module


Per Import werden externe Funktionen verfügbar


# datei: main.py

import fakultaet
print fakultaet.berechne_fakultaet(6)




MacPro:module klaus$ python2.7 main.py
120
720




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            52
Module


Module werden beim Import ausgeführt


# datei: main.py                                                            # datei: fakultaet.py

                                                                            def berechne_fakultaet(num):
import fakultaet
                                                                                if num == 0:
print fakultaet.berechne_fakultaet(6)                                               return 1
                                                                                result = num * berechne_fakultaet(num - 1)
                                                                                return result

                                                                            print berechne_fakultaet(5)




MacPro:module klaus$ python2.7 main.py
120
720




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                                                       53
Module


Module werden beim Import ausgeführt


# datei: fakultaet.py

def berechne_fakultaet(num):
    if num == 0:
        return 1
    result = num * berechne_fakultaet(num - 1)
    return result

if __name__ == '__main__':
    print berechne_fakultaet(5)




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            54
Module


Module sind Namensräume

from fakultaet import berechne_fakultaet as fkt

def calc_range(func, q):
    result = []
    for p in q:
        result.append(func(p))
    return result

if __name__ == '__main__':
    result = calc_range(fkt, range(6))
    print result




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            55
Module


Funktionen sind Objekte!

from fakultaet import berechne_fakultaet as fkt

def calc_range(func, q):
    result = []
    for p in q:
        result.append(func(p))
    return result

if __name__ == '__main__':
    result = calc_range(fkt, range(6))
    print result

MacPro:module klaus$ python2.7 facultator.py
[1, 1, 2, 6, 24, 120]




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            56
Klassen


Klassen erzeugen vielfache Instanz-Objekte

class Text(object):

       def __init__(self, author='', text=''):
           self.author = author
           self.text = text

>>> text1 = Text(author='Lem', text='Solaris ist ein dickes Buch')




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            57
Klassen


Klassen erzeugen vielfache Instanz-Objekte

class Text(object):

       def __init__(self, author='', text=''):
           self.author = author
           self.text = text

>>> text1 = Text(author='Lem', text='Solaris ist ein dickes Buch')
>>> text1.text
'Solaris ist ein dickes Buch'




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            58
Klassen


Klassen erzeugen vielfache Instanz-Objekte

class Text(object):

       def __init__(self, author='', text=''):
           self.author = author
           self.text = text

>>> text1 = Text(author='Lem', text='Solaris ist ein dickes Buch')
>>> text1.text
'Solaris ist ein dickes Buch'
>>> text2 = Text()
>>> text2.author='Preussler'
>>> text2.text='Das kleine Gespenst.'
>>> text2.text
'Das kleine Gespenst.'




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            59
Klassen


Methoden sind Funktionen in Klassen

class Text(object):

       def __init__(self, author='', text=''):
           self.author = author
           self.text = text

       def teaser(self, length=3):
           words = self.text.split(' ')
           limit = min(len(words), length)
           return ' '.join(words[:limit])


>>> text1 = Text(author='Lem', text='Solaris ist ein dickes Buch')
>>> text1.teaser()
'Solaris ist ein'




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            60
Klassen


Klassen bieten Vererbung

class Article(Text):

       def __init__(self, author='', text='', abstract=''):
           super(Article, self).__init__(author, text)
           self.abstract = abstract

       def teaser(self, length=3):
           words = self.abstract.split(' ')
           limit = min(len(words), length)
           return ' '.join(words[:limit])


>>> art1 = Article('Lem', 'Solaris ist ein dickes Buch',
                   'Ein Klassiker von Lem')
>>> art1.teaser(2)
'Ein Klassiker'
>>> art1.author
'Lem'


Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            61
Klassen


Klassen sind Namensräume

class Text(object):
                                                                             Vererbung
               self.author
                                                                             durchsucht
               self.text
                                                                            Namensraum-
                                                                               Bäume
class Article(Text):

               self.abstract




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                     62
Exceptions

>>> f = open('dummy.txt', 'r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'dummy.txt'

>>> try:
... 	 f = open('dummy.txt', 'r')
... except IOError:
... 	 print 'file not found'
...
file not found



• Better ask for forgivness than for permission




Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            63
Coding Styles


Möglichst einheitliche Codierung

import this                             # nur ein Import pro Zeile
from that import *                      # vermeide dieses

PAGE_SIZE = "A4"                      # Konstanten in Uppercase

class CamelCaseNaming(object):

       def method_with_underlines(self):
           pass # indent 4 spaces, no tabs!



def formatiere_artikel():                          #   verwende beschreibende Bezeichner
    is_public = False                              #   boolean: is
    has_content = True                             #   boolean: has
    text = 'ein Text'                              #   ein Text: Einzahl
    texts = []                                     #   viele Texte: Mehrzahl


PEP8: http://www.python.org/dev/peps/pep-0008/
Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                                           64
The Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            65
The Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            66
The Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            67
The Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            68
The Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin

                                                                            69
just scratching the surface


    </reloaded>

Weitere ähnliche Inhalte

Ähnlich wie Python crash-kurs

Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...gedoplan
 
Warum Python?
Warum Python?Warum Python?
Warum Python?tharwan
 
Back to Basics – Webinar 2: Ihre erste MongoDB-Anwendung
Back to Basics – Webinar 2: Ihre erste MongoDB-AnwendungBack to Basics – Webinar 2: Ihre erste MongoDB-Anwendung
Back to Basics – Webinar 2: Ihre erste MongoDB-AnwendungMongoDB
 
Java Streams und Lambdas
Java Streams und LambdasJava Streams und Lambdas
Java Streams und LambdasNane Kratzke
 
OSMC 2010 | Logverarbeitung mit syslog-ng - Status und Zukunft by Martin Grauel
OSMC 2010 | Logverarbeitung mit syslog-ng - Status und Zukunft by Martin GrauelOSMC 2010 | Logverarbeitung mit syslog-ng - Status und Zukunft by Martin Grauel
OSMC 2010 | Logverarbeitung mit syslog-ng - Status und Zukunft by Martin GrauelNETWAYS
 
C Sharp Einfuehrung Teil 2
C Sharp Einfuehrung Teil 2C Sharp Einfuehrung Teil 2
C Sharp Einfuehrung Teil 2DraphonyGames
 
Einführung in Suchmaschinen und Solr
Einführung in Suchmaschinen und SolrEinführung in Suchmaschinen und Solr
Einführung in Suchmaschinen und SolrNEOMO GmbH
 
Oracle workshop sessiontracing
Oracle workshop sessiontracingOracle workshop sessiontracing
Oracle workshop sessiontracingciganek
 
An Introduction to Ruby
An Introduction to RubyAn Introduction to Ruby
An Introduction to RubyJonathan Weiss
 
Multithreading in c# mit tpl
Multithreading in c# mit tplMultithreading in c# mit tpl
Multithreading in c# mit tplDavidT27
 
Go - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeGo - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeFrank Müller
 
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins Christian Kauhaus
 
Tech-Talk: Python vs. Ruby
Tech-Talk: Python vs. RubyTech-Talk: Python vs. Ruby
Tech-Talk: Python vs. Rubyschlauch
 
Dart (Teil II der Tour de Dart)
Dart (Teil II der Tour de Dart)Dart (Teil II der Tour de Dart)
Dart (Teil II der Tour de Dart)Nane Kratzke
 
Differenzial Analyse in der Praxis (Florian Walther)
Differenzial Analyse in der Praxis (Florian Walther)Differenzial Analyse in der Praxis (Florian Walther)
Differenzial Analyse in der Praxis (Florian Walther)GEEKcon
 
Schnell, schneller, Quarkus!!
Schnell, schneller, Quarkus!!Schnell, schneller, Quarkus!!
Schnell, schneller, Quarkus!!gedoplan
 

Ähnlich wie Python crash-kurs (20)

Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
 
Warum Python?
Warum Python?Warum Python?
Warum Python?
 
Windows Powershell
Windows PowershellWindows Powershell
Windows Powershell
 
Python
PythonPython
Python
 
Back to Basics – Webinar 2: Ihre erste MongoDB-Anwendung
Back to Basics – Webinar 2: Ihre erste MongoDB-AnwendungBack to Basics – Webinar 2: Ihre erste MongoDB-Anwendung
Back to Basics – Webinar 2: Ihre erste MongoDB-Anwendung
 
Java Streams und Lambdas
Java Streams und LambdasJava Streams und Lambdas
Java Streams und Lambdas
 
OSMC 2010 | Logverarbeitung mit syslog-ng - Status und Zukunft by Martin Grauel
OSMC 2010 | Logverarbeitung mit syslog-ng - Status und Zukunft by Martin GrauelOSMC 2010 | Logverarbeitung mit syslog-ng - Status und Zukunft by Martin Grauel
OSMC 2010 | Logverarbeitung mit syslog-ng - Status und Zukunft by Martin Grauel
 
C Sharp Einfuehrung Teil 2
C Sharp Einfuehrung Teil 2C Sharp Einfuehrung Teil 2
C Sharp Einfuehrung Teil 2
 
Einführung in Suchmaschinen und Solr
Einführung in Suchmaschinen und SolrEinführung in Suchmaschinen und Solr
Einführung in Suchmaschinen und Solr
 
Oracle workshop sessiontracing
Oracle workshop sessiontracingOracle workshop sessiontracing
Oracle workshop sessiontracing
 
Oracle TEXT
Oracle TEXTOracle TEXT
Oracle TEXT
 
An Introduction to Ruby
An Introduction to RubyAn Introduction to Ruby
An Introduction to Ruby
 
Multithreading in c# mit tpl
Multithreading in c# mit tplMultithreading in c# mit tpl
Multithreading in c# mit tpl
 
Pyparsing
PyparsingPyparsing
Pyparsing
 
Go - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeGo - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare Systeme
 
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
 
Tech-Talk: Python vs. Ruby
Tech-Talk: Python vs. RubyTech-Talk: Python vs. Ruby
Tech-Talk: Python vs. Ruby
 
Dart (Teil II der Tour de Dart)
Dart (Teil II der Tour de Dart)Dart (Teil II der Tour de Dart)
Dart (Teil II der Tour de Dart)
 
Differenzial Analyse in der Praxis (Florian Walther)
Differenzial Analyse in der Praxis (Florian Walther)Differenzial Analyse in der Praxis (Florian Walther)
Differenzial Analyse in der Praxis (Florian Walther)
 
Schnell, schneller, Quarkus!!
Schnell, schneller, Quarkus!!Schnell, schneller, Quarkus!!
Schnell, schneller, Quarkus!!
 

Python crash-kurs

  • 3. Strukturierung durch Einrückung def berechne_fakultaet(num): { if num == 0: { return 1 } result = num * berechne_fakultaet(num - 1) return result } Python kennt keine Klammern für { Codeblöcke } Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 3
  • 4. Strukturierung durch Einrückung def berechne_fakultaet(num): if num == 0: return 1 result = num * berechne_fakultaet(num - 1) return result Whitespaces am Zeilenanfang sind syntaktisch relevant 1 Tabulator entspricht 8 Leerzeichen Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 4
  • 5. Strukturierung durch Einrückung def berechne_fakultaet(num): ....if num == 0: ........return 1 ........ ....result = num * berechne_fakultaet(num - 1) ....return result .... Konvention: Einrücktiefe pro Block: 4 Leerzeichen Verwende nur Leerzeichen, keine Tabulatoren! Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 5
  • 6. Interaktiver Interpreter MacPro:~ klaus$ python Python 2.7 (r27:82500, Jul 26 2010, 10:14:29) [GCC 4.2.1 (Apple Inc. build 5659)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def berechne_fakultaet(num): ... if num == 0: ... return 1 ... result = num * berechne_fakultaet(num - 1) ... return result ... >>> berechne_fakultaet(2) 2 >>> berechne_fakultaet(3) 6 >>> berechne_fakultaet(6) 720 Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 6
  • 7. Welche Version wählen? Python 2 oder Python 3? ( ) • geringe Differenzen: viele Backports von Python 3 nach Python 2.7 • 2to3-Tool: z.B.: „print n“ „print(n)“ • Problem: externe Libraries Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 7
  • 8. Objektorientierung Python kennt nur Objekte: type • Alle Datenobjekte sind vom Typ type • Alle Funktionen und Klassen sind vom Typ type • Objekte vom Typ type sind „callable“ Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 8
  • 9. Datenobjekte Type Beispiel variabel Integer 42 immutable Float 42.0 immutable String „python“ immutable List [42, „python“, 42.0] mutable Tuple (42, „python“, 42.0) immutable Dictionary {„one“: 1, 2: „two“} mutable Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 9
  • 10. Listen >>> liste_1 = [1, 2, 3, 4] •Instanziierung eines Listen-Objekts durch: [ ] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 10
  • 11. Listen >>> liste_1 = [1, 2, 3, 4] >>> liste_1[0] 1 •Instanziierung eines Listen-Objekts durch: [ ] •Listen-Index ist 0-basiert. Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 11
  • 12. Listen >>> liste_1 = [1, 2, 3, 4] >>> liste_1[0] 1 >>> liste_1[-1] 4 •Instanziierung eines Listen-Objekts durch: [ ] •Listen-Index ist 0-basiert. •Index-Zugriff „von hinten“ möglich: [-1] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 12
  • 13. Listen >>> liste_1 = range(10) >>> liste_1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> liste_1[-1] 9 •Instanziierung eines Listen-Objekts durch: [ ] •Listen-Index ist 0-basiert. •Index-Zugriff „von hinten“ möglich: [-1] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 13
  • 14. Listen >>> liste_1 = range(10) >>> liste_1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> liste_1[-1] 9 >>> liste_1[-2] 8 •Index-Zugriff „von hinten“ möglich: [-2] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 14
  • 15. Listen >>> liste_1 = range(10) >>> liste_1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> liste_1[1:3] [1, 2] •Listen bieten Slicing: [p, q[ Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 15
  • 16. Listen >>> liste_1 = range(10) >>> liste_1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> liste_1[1:3] [1, 2] >>> liste_1[:3] [0, 1, 2] •Listen bieten Slicing: [p, q[ •Default: [:n] entspricht [0:n] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 16
  • 17. Listen >>> liste_1 = range(10) >>> liste_1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> liste_1[1:3] [1, 2] >>> liste_1[:3] [0, 1, 2] >>> liste_1[3:] [3, 4, 5, 6, 7, 8, 9] •Listen bieten Slicing: [p, q[ •Default: [:n] entspricht [0:n] •Default: [m:] entspricht [m:0] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 17
  • 18. Listen >>> liste_1 = range(10) >>> liste_1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> liste_1[:] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] •Default: [:] entspricht [0:0] (Kopie) Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 18
  • 19. Listen >>> liste_1 = range(10) >>> liste_1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> liste_1[:] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> liste_1[::3] [0, 3, 6, 9] •Default: [:] entspricht [0:0] (Kopie) •Slicing mit Intervall möglich: [m:n:i] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 19
  • 20. Listen >>> liste_2 = [4, "five", berechne_fakultaet, liste_1] •Listen können beliebige Objekte enthalten Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 20
  • 21. Listen >>> liste_2 = [4, "five", berechne_fakultaet, liste_1] >>> liste_2 [4, 'five', <function berechne_fakultaet at 0x1004846e0>, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] >>> liste_2[-1][-1] 9 •Listen können beliebige Objekte enthalten •Aufbau komplexer Datenstrukturen möglich Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 21
  • 22. Listen >>> liste_2 = [4, "five", berechne_fakultaet, liste_1] >>> liste_2 [4, 'five', <function berechne_fakultaet at 0x1004846e0>, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] >>> liste_2[-1][-1] 9 >>> liste_2[2](6) 720 •Listen können beliebige Objekte enthalten •Aufbau komplexer Datenstrukturen möglich •Funktionsaufrufe aus Listen möglich Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 22
  • 23. Zeichenketten >>> text = 'Dies ist ein String' >>> text[0] 'D' >>> text[-1] 'g' >>> text[-6:] 'String' >>> text.split()[-1] 'String' •Zeichenketten sind Sequenzen •Zeichenketten sind Objekte mit Methoden Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 23
  • 24. Dictionaries >>> dict_1 = {"one": 1, "two": 2} •Dictionary: key-value-storage Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 24
  • 25. Dictionaries >>> dict_1 = {"one": 1, "two": 2} >>> dict_1 {'two': 2, 'one': 1} •Dictionary: key-value-storage •Inhalte unsortiert Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 25
  • 26. Dictionaries >>> dict_1 = {"one": 1, "two": 2} >>> dict_1 {'two': 2, 'one': 1} >>> dict_1["two"] 2 •Dictionary: key-value-storage •Inhalte unsortiert •Zugriff per „key“ Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 26
  • 27. Dictionaries >>> dict_1 = {"one": 1, "two": 2} >>> dict_1 {'two': 2, 'one': 1} >>> dict_1["liste_2"] = liste_2 >>> dict_1 {'liste_2': [4, 'five', <function berechne_fakultaet at 0x1004846e0>, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], 'two': 2, 'one': 1} •Dictionary: key-value-storage •Inhalte unsortiert •Zugriff per „key“ •Beliebige Objekte als „value“ Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 27
  • 28. Dictionaries >>> dict_1 = {"one": 1, "two": 2} >>> dict_1["liste_2"] = liste_2 >>> dict_1 {'liste_2': [4, 'five', <function berechne_fakultaet at 0x1004846e0>, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], 'two': 2, 'one': 1} >>> dict_1["two"] 2 >>> dict_1["liste_2"][-1] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> dict_1["liste_2"][2](6) 720 •Dictionary: key-value-storage •Inhalte unsortiert •Zugriff per „key“ •Beliebige Objekte als „value“ Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 28
  • 29. Label Referenzierung immutabler Datenobjekte: >>> a = b = 42 Label Objekt >>> a, b (42, 42) >>> a 42 b •Daten sind Objekte •„Variable“ sind Referenzen (Label) auf diese Objekte Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 29
  • 30. Label Referenzierung immutabler Datenobjekte: >>> a = b = 42 Label Objekt >>> a, b (42, 42) >>> b = 4 a 42 >>> a, b (42, 4) >>> b 4 •Daten sind Objekte •„Variable“ sind Referenzen (Label) auf diese Objekte Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 30
  • 31. Label Referenzierung mutabler Datenobjekte: >>> l1 = ['one'] Label Objekt l1 ['one'] •Daten sind Objekte •„Variable“ sind Referenzen (Label) auf diese Objekte Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 31
  • 32. Label Referenzierung mutabler Datenobjekte: >>> l1 = ['one'] Label Objekt >>> l2 = l1 l1 ['one'] l2 •Daten sind Objekte •„Variable“ sind Referenzen (Label) auf diese Objekte Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 32
  • 33. Label Referenzierung mutabler Datenobjekte: >>> l1 = ['one'] Label Objekt >>> l2 = l1 >>> l2.append('two') l1 ['one'] l2 .append('two') ['one', 'two'] •Daten sind Objekte •„Variable“ sind Referenzen (Label) auf diese Objekte Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 33
  • 34. Label Referenzierung mutabler Datenobjekte: >>> l1 = ['one'] Label Objekt >>> l2 = l1 >>> l2.append('two') >>> l1 l1 ['one'] ['one', 'two'] l2 .append('two') ['one', 'two'] •Daten sind Objekte •„Variable“ sind Referenzen (Label) auf diese Objekte Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 34
  • 35. Datenobjekte: boolscher Kontext Datenobjekt boolscher Wert Singleton True True ja False False ja None False ja 0 False 0.0 False 1 True [] False {} False "" False "" True Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 35
  • 36. Datenobjekte: boolscher Kontext Vorsicht vor Fließkommazahlen: >>> p = 3 * 2.7 / 3 - 2.7 >>> p 4.440892098500626e-16 >>> if p: ... print True ... else: ... print False ... True Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 36
  • 37. Kontrollanweisungen # if-then-else in Python: # Auswahl Vergleichsoperatoren: >>> a = 1 >>> a = 1 >>> if a == 42: >>> b = 42 ... print "Das ist die Antwort" >>> a != b ... elif a == 41: True ... print "knapp daneben" >>> a < b ... elif a == 43: True ... print "auch daneben" >>> c = 43 ... else: >>> a < b < c ... print "leider ganz falsch" True ... leider ganz falsch Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 37
  • 38. Schleifen „for“ für Iterationen über gegebene Sequenzen >>> for n in range(20): # iteriert über n von [0, 20[ ... if not n % 3: ... continue # erzwingt nächsten Schleifendurchlauf ... if n > 10: ... break # erzwingt Schleifenabbruch ... print n ... 1 2 4 5 7 8 10 >>> Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 38
  • 39. Schleifen „while“ für Schleifen mit programmatischen Abbruch >>> import random >>> run = True >>> while run: ... r = random.random() ... run = r < 0.8 ... print r ... 0.783283639782 0.282615658576 0.821162495507 >>> Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 39
  • 40. Funktionen Erhalten Argumente und liefern Ergebnisse def berechne_fakultaet(num): if num == 0: return 1 result = num * berechne_fakultaet(num - 1) return result Allgemein: def <name>(arg1, arg2, ... argN): <statements> return <value> Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 40
  • 41. Funktionen Argumente: Abgleich von links nach rechts >>> def booktitle(title, author): ... # title, author: required parameters ... print "Author: %snTitle: %s" % (author, title) ... >>> booktitle('Solaris', 'Lem') Author: Lem Title: Solaris Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 41
  • 42. Funktionen Argumente: Abgleich von links nach rechts >>> def booktitle(title, author): ... # title, author: required parameters ... print "Author: %snTitle: %s" % (author, title) ... >>> booktitle('Solaris', 'Lem') Author: Lem Title: Solaris >>> booktitle('Der Hobbit') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: booktitle() takes exactly 2 arguments (1 given) Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 42
  • 43. Funktionen Argumente: Abgleich nach Argumentname >>> def booktitle(title, author): ... # title, author: required parameters ... print "Author: %snTitle: %s" % (author, title) ... >>> booktitle('Solaris', 'Lem') Author: Lem Title: Solaris >>> booktitle(author='Tolkien', title='Der Hobbit') Author: Tolkien Title: Der Hobbit Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 43
  • 44. Funktionen Argumente: Abgleich nach Position und Argumentname >>> def booktitle(title, author): ... # title, author: required parameters ... print "Author: %snTitle: %s" % (author, title) ... >>> booktitle('Solaris', author='Lem') Author: Lem Title: Solaris >>> booktitle(author='Lem', 'Solaris') File "<stdin>", line 1 SyntaxError: non-keyword arg after keyword arg Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 44
  • 45. Funktionen Argumente: Defaultwerte >>> def booktitle(title, author='unknown'): ... print "Author: %snTitle: %s" % (author, title) ... >>> booktitle('Der Schwarm') Author: unknown Title: Der Schwarm >>> booktitle('Der Schwarm', 'Frank Schätzing') Author: Frank Schätzing Title: Der Schwarm >>> booktitle('Der Schwarm', author='Frank Schätzing') Author: Frank Schätzing Title: Der Schwarm Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 45
  • 46. Funktionen Argumente: variable Anzahl # positionierte Argumente >>> def func(*args): ... print args ... >>> func(1, 2, 42, 'vier') (1, 2, 42, 'vier') # keyword Argumente >>> def func(**kwargs): ... print kwargs ... >>> func(author='Lem', title='Solaris') {'title': 'Solaris', 'author': 'Lem'} Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 46
  • 47. Funktionen Funktionen sind Namensräume >>> def changer(x, y): ... x = 2 ... y[0] = 'spam' ... >>> x = 1 >>> z = [42, 'ham', 'eggs'] >>> changer(x, z) >>> x 1 >>> z ['spam', 'ham', 'eggs'] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 47
  • 48. Funktionen Funktionen sind Namensräume LGB-Regel: >>> x = 1 >>> y = 2 local >>> z = 5 global buildin >>> def spam(): ... global y ... x = 42 ... y = 3 ... print x, y, z ... >>> spam() 42 3 5 >>> print x, y, z 1 3 5 Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 48
  • 49. Funktionen Funktionen sind (wirklich!) Namensräume >>> x = 1 >>> y = 2 >>> def spam(): ... print y ... print x ... x = 42 ... print x ... >>> spam() 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in spam UnboundLocalError: local variable 'x' referenced before assignment Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 49
  • 50. Module Strukturieren und Wiederverwertung von Code # datei: fakultaet.py def berechne_fakultaet(num): if num == 0: return 1 result = num * berechne_fakultaet(num - 1) return result print berechne_fakultaet(5) MacPro:module klaus$ python2.7 fakultaet.py 120 Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 50
  • 51. Module Module sind Namensräume # datei: main.py import fakultaet print fakultaet.berechne_fakultaet(6) MacPro:module klaus$ python2.7 main.py 120 720 Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 51
  • 52. Module Per Import werden externe Funktionen verfügbar # datei: main.py import fakultaet print fakultaet.berechne_fakultaet(6) MacPro:module klaus$ python2.7 main.py 120 720 Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 52
  • 53. Module Module werden beim Import ausgeführt # datei: main.py # datei: fakultaet.py def berechne_fakultaet(num): import fakultaet if num == 0: print fakultaet.berechne_fakultaet(6) return 1 result = num * berechne_fakultaet(num - 1) return result print berechne_fakultaet(5) MacPro:module klaus$ python2.7 main.py 120 720 Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 53
  • 54. Module Module werden beim Import ausgeführt # datei: fakultaet.py def berechne_fakultaet(num): if num == 0: return 1 result = num * berechne_fakultaet(num - 1) return result if __name__ == '__main__': print berechne_fakultaet(5) Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 54
  • 55. Module Module sind Namensräume from fakultaet import berechne_fakultaet as fkt def calc_range(func, q): result = [] for p in q: result.append(func(p)) return result if __name__ == '__main__': result = calc_range(fkt, range(6)) print result Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 55
  • 56. Module Funktionen sind Objekte! from fakultaet import berechne_fakultaet as fkt def calc_range(func, q): result = [] for p in q: result.append(func(p)) return result if __name__ == '__main__': result = calc_range(fkt, range(6)) print result MacPro:module klaus$ python2.7 facultator.py [1, 1, 2, 6, 24, 120] Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 56
  • 57. Klassen Klassen erzeugen vielfache Instanz-Objekte class Text(object): def __init__(self, author='', text=''): self.author = author self.text = text >>> text1 = Text(author='Lem', text='Solaris ist ein dickes Buch') Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 57
  • 58. Klassen Klassen erzeugen vielfache Instanz-Objekte class Text(object): def __init__(self, author='', text=''): self.author = author self.text = text >>> text1 = Text(author='Lem', text='Solaris ist ein dickes Buch') >>> text1.text 'Solaris ist ein dickes Buch' Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 58
  • 59. Klassen Klassen erzeugen vielfache Instanz-Objekte class Text(object): def __init__(self, author='', text=''): self.author = author self.text = text >>> text1 = Text(author='Lem', text='Solaris ist ein dickes Buch') >>> text1.text 'Solaris ist ein dickes Buch' >>> text2 = Text() >>> text2.author='Preussler' >>> text2.text='Das kleine Gespenst.' >>> text2.text 'Das kleine Gespenst.' Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 59
  • 60. Klassen Methoden sind Funktionen in Klassen class Text(object): def __init__(self, author='', text=''): self.author = author self.text = text def teaser(self, length=3): words = self.text.split(' ') limit = min(len(words), length) return ' '.join(words[:limit]) >>> text1 = Text(author='Lem', text='Solaris ist ein dickes Buch') >>> text1.teaser() 'Solaris ist ein' Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 60
  • 61. Klassen Klassen bieten Vererbung class Article(Text): def __init__(self, author='', text='', abstract=''): super(Article, self).__init__(author, text) self.abstract = abstract def teaser(self, length=3): words = self.abstract.split(' ') limit = min(len(words), length) return ' '.join(words[:limit]) >>> art1 = Article('Lem', 'Solaris ist ein dickes Buch', 'Ein Klassiker von Lem') >>> art1.teaser(2) 'Ein Klassiker' >>> art1.author 'Lem' Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 61
  • 62. Klassen Klassen sind Namensräume class Text(object): Vererbung self.author durchsucht self.text Namensraum- Bäume class Article(Text): self.abstract Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 62
  • 63. Exceptions >>> f = open('dummy.txt', 'r') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: 'dummy.txt' >>> try: ... f = open('dummy.txt', 'r') ... except IOError: ... print 'file not found' ... file not found • Better ask for forgivness than for permission Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 63
  • 64. Coding Styles Möglichst einheitliche Codierung import this # nur ein Import pro Zeile from that import * # vermeide dieses PAGE_SIZE = "A4" # Konstanten in Uppercase class CamelCaseNaming(object): def method_with_underlines(self): pass # indent 4 spaces, no tabs! def formatiere_artikel(): # verwende beschreibende Bezeichner is_public = False # boolean: is has_content = True # boolean: has text = 'ein Text' # ein Text: Einzahl texts = [] # viele Texte: Mehrzahl PEP8: http://www.python.org/dev/peps/pep-0008/ Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 64
  • 65. The Zen of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 65
  • 66. The Zen of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 66
  • 67. The Zen of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 67
  • 68. The Zen of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 68
  • 69. The Zen of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Python Crash Kurs - Klaus Bremer - FrOSCon 2012, 26.08.2012, St. Augustin 69
  • 70. just scratching the surface </reloaded>