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
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
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
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