>>> def Hello(name="world"): ... print "Hello", name ... >>> Hello() Hello world >>> Hello("Carsten") Hello Carsten >>> Hello(name = "Carsten") Hello Carsten >>>
def Hello():
def Hello(names=["world"]): for name in names: print "Hello", name
def Hello(): print "Hello World"ist ein Syntaxfehler!
>>> a = 1; type(a) <type 'int'> >>> a = "eins"; type(a) <type 'str'>
>>> class A: # mehr zu Klassen später ... def __init__(self, num): ... self.x = num >>> a = A(1) >>> b = a >>> a is b True >>> a = A(1) >>> b = A(1) >>> a is b False
>>> if x > 0: ... pass ... elif x < 0: ... pass ... else: ... pass
>>> a, b = 0, 1 >>> while b < 10: ... print b, ... a, b = b, a+b ... else: ... print "finished" ... 1 1 2 3 5 8 finished
>>> list = ['a', 'b', 3, 4] >>> for a in list: ... print a, # "," unterdrückt hier Zeilenumbruch ... a b 3 4 >>> for i, a in enumerate(list): ... print "%s-%s" % (i, a), # formatstring! ... 0-a 1-b 2-3 3-4 >>>
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(10, 2) [] >>> range(0, 10, 2) [0, 2, 4, 6, 8]
>>> ags = ['ai', 'pi', 'wbs'] >>> for ag in ags: ... if len(ag) > 2: ... ags.insert(0, ag)Produziert eine Endlosschleife, daher:
>>> for ag in ags[:]: # iteriert über Kopie der Liste ...
>>> x = [1, 2, 3, 4] >>> y = x >>> y is x True >>> y = x[:] # erstellt eine flache Kopie >>> y is x False >>> x.append([1, 2]) >>> x [1, 2, 3, 4, [1, 2]] >>> y = x[:] >>> y is x False >>> y[4] is x[4] True >>>
>>> x = [1, 2, 3, 4] >>> x[1] 2 >>> x[1:] [2, 3, 4] >>> x[:1] [1] >>> x[-1:] [4] >>> x[-1:] = [4, 5, 6] >>> x [1, 2, 3, 4, 5, 6]
>>> x.append(x) >>> x [1, 2, 3, 4, 5, 6, [...]] >>> x[-1:] [[1, 2, 3, 4, 5, 6, [...]]] >>> x[-1:] = [] # letztes Element wieder Löschen >>> x [1, 2, 3, 4, 5, 6]
>>> def f(x): return x % 2 != 0 and x % 3 != 0 ... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x ... >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def add(x,y): return x+y ... >>> reduce(add, range(1, 11)) 55
>>> def make_inc(n): ... return lambda x: x + n ... >>> f = make_inc(42) >>> f(0) 42 >>> f(1) 43 >>>
>>> filter(lambda x: x % 2 != 0 and x % 3 != 0, range(2, 25)) [5, 7, 11, 13, 17, 19, 23]
>>> [x*x*x for x in range(1, 11)] [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> [x for x in range(2, 25) ... if f(x)] [5, 7, 11, 13, 17, 19, 23] >>>
>>> [str(round(355/113.0, i)) for i in range(1,6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159']
>>> t = 1, 2, 3, "b" # tuple packing >>> t (1, 2, 3, 'b') >>> t[1] = 1 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment
>>> t = () >>> len(t) 0 >>> t = ("test",) >>> len(t) 1
>>> a, b, c, d = tDas funktioniert natürlich nur, wenn len(t) == 4!
>>> a, b, c = [1, 2, 3] >>> a, b, c (1, 2, 3) >>> a = (x for x in range(10)) >>> a <generator object at 0x81a8e8c> >>> b, c, d = a Traceback (most recent call last): File "<stdin> line 1, in <module> ValueError: too many values to unpack >>> a = (x for x in range(3)) >>> b, c, d = a >>> b, c, d (0, 1, 2)
>>> d = {'rbg': 'Rechnerbetriebsgruppe', ... 'pi': 'Praktische Informatik'} >>> for a in d: ... print a ... rbg pi >>> for a in d: ... print d[a] ... Rechnerbetriebsgruppe Praktische Informatik
>>> class Klasse: ... "Ich bin eine Klasse und tue nichts" ... pass ... >>> Klasse <class __main__.Klasse at 0x81a077c> >>> dir(Klasse) ['__doc__', '__module__'] >>> Klasse.__doc__ 'Ich bin eine Klasse und tue nichts' >>> Klasse.__module__ '__main__' >>>
>>> k = Klasse() >>> k <__main__.Klasse instance at 0x81a8e8c> >>> k.__doc__ 'Ich bin eine Klasse und tue nichts' >>>
>>> class Klasse: ... "Ich bin eine Klasse mit einem Zweck" ... def __init__(self, zweck=None): ... self.zweck = zweck ... >>> k = Klasse() >>> k.zweck None >>> k = Klasse("Demonstration") >>> k.zweck 'Demonstration'
>>> class Klasse: ... "Ich bin eine Klasse mit einem Zweck" ... def __init__(self, zweck=None): ... self.zweck = zweck ... def depressiv(self): ... if self.zweck is None: ... return True ... else: ... return False ...
>>> d = Klasse() >>> Klasse.depressiv <unbound method Klasse.depressiv> >>> d.depressiv <bound method Klasse.depressiv of <__main__.Klasse instance at 0x81a8eec>>
>>> d.depressiv() TrueIst exakt das gleiche wie
>>> Klasse.depressiv(d) True
>>> class Happy(Klasse): ... def depressiv(self): ... if Klasse.depressiv(self): ... return False # heute mit Antidepressiva! ... return False ... >>> h = Happy() >>> h <__main__.Happy instance at 0x838b6ec> >>> h.depressiv() False >>> Klasse.depressiv(h) # explizit Eltern-Methode aufrufen True >>> Happy.depressiv(h) False >>>
>>> class Reverse: ... "Iterator for looping over a sequence backwards" ... def __init__(self, data): ... self.data = data ... self.index = len(data) ... def __iter__(self): ... return self ... def next(self): ... if self.index == 0: ... raise StopIteration ... self.index = self.index - 1 ... return self.data[self.index] ... >>> for char in Reverse('spam'): ... print char, ... m a p s
raise StopIterationbeendet wird
>>> def fib(n): ... a, b = 0, 1 ... while b < n: ... a, b = b, a+b ... yield a ... >>> f = fib(100) >>> f <generator object at 0x838b4cc> >>> f.next() 1 >>> f.next() 1 >>> f.next() 2 >>> for n in f: print n, ... 3 5 8 13 21 34 55 89
>>> x = (i*i for i in range(10)) >>> y = [i*i for i in range(10)]
>>> x <generator object at 0x838b72c> >>> y [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
"Oddly enough, Python's use of whitespace stopped feeling unnatural after about twenty minutes. I just indented code, pretty much as I would have done in a C program anyway, and it worked."
"My second [surprise] came a couple of hours into the project, when I noticed [...] I was generating working code nearly as fast as I could type."