102
Einstieg in Python Zusammenstellung: Thure Dührsen, Juli 2017 Quellen im Fuß jeder Seite Erste Schritte 1 Grundkonzepte anhand der Turtle-Grafik 5 Einfaches Zeichnen mit turtle 5 Summary of Turtle Methods 10 Variablen 11 Schleifen 13 Benutzerdefinierte Funktionen 16 Funktionen mit Parametern 20 Verzweigungen 23 Bedingte Schleifen 25 Logische Operatoren 28 Python syntax and semantics 30 Design Philosophy 30 Keywords 31 Indentation 31 Data Structures Base types, collection types, object system 32 Literals Strings (normal, multi-line, raw, concatenation), numbers, lists, tuples, sets, dictionaries 33 Operators Arithmetic, comparison, logical 36 Functional Programming Comprehensions, first-class functions, closures, generators, generator expressions, dictionary and set comprehensions 37 Objects with statements, descriptors, class and static methods 40 Exceptions 41 Comments and docstrings 42 Function annotations 43 Decorators 43 Easter Eggs 44 Python Tutorial 46 Whetting your appetite 46 Using the Python interpreter 48 An Informal Introduction to Python 51 More Control Flow Tools 61 Data Structures 71 Input And Output 83 Errors And Exceptions 90 Brief Tour Of The Standard Library 97

Willkommen am Institut für Informatik — Institut für

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Willkommen am Institut für Informatik — Institut für

Einstieg in PythonZusammenstellung: Thure Dührsen, Juli 2017

Quellen im Fuß jeder Seite

Erste Schritte 1

Grundkonzepte anhand der Turtle-Grafik 5

Einfaches Zeichnen mit turtle 5Summary of Turtle Methods 10Variablen 11Schleifen 13Benutzerdefinierte Funktionen 16Funktionen mit Parametern 20Verzweigungen 23Bedingte Schleifen 25Logische Operatoren 28

Python syntax and semantics 30

Design Philosophy 30Keywords 31Indentation 31Data Structures Base types, collection types, object system 32Literals Strings (normal, multi-line, raw, concatenation), numbers, lists, tuples, sets, dictionaries 33Operators Arithmetic, comparison, logical 36Functional Programming Comprehensions, first-class functions, closures, generators,

generator expressions, dictionary and set comprehensions 37Objects with statements, descriptors, class and static methods 40Exceptions 41Comments and docstrings 42Function annotations 43Decorators 43Easter Eggs 44

Python Tutorial 46

Whetting your appetite 46Using the Python interpreter 48An Informal Introduction to Python 51More Control Flow Tools 61Data Structures 71Input And Output 83Errors And Exceptions 90Brief Tour Of The Standard Library 97

Page 2: Willkommen am Institut für Informatik — Institut für

Erste SchritteWas du brauchstEine Python!Falls Du Python noch nicht installiert hast, findest Du die jüngsten offiziellen Installationspakete hier:

http://python.org/download/ (http://python.org/download/)

Python 3 ist zu bevorzugen, da es die neueste verfügbare Version ist!

Bemerkung

Unter Windows wirst du Python zu deinem Systempfad hinzufügen wollen, sodass es von anderen Programmengefunden werden kann. Um dies zu tun, navigiere in dein Installationsverzeichnis ( C:\Python33\ ), öffne denTools und dann den Scripts -Ordner, und führe die Datei win_add2path.py aus indem du doppelt auf sie

klickst.

Und einen Quelltext-EditorEin Quelltext-Editor erlaubt das Lesen und Schreiben von Programmen. Es gibt viele, und es ist eine sehrpersönliche Wahl – wie ein Tennisspieler seinen Schläger oder ein Koch sein Lieblingsmesser wählt. Umanzufangen benötgist du nur einen simplen, einfach zu benutzenden Editor der dir nicht in die Quere kommt, aberimmer noch effektiv beim Schreiben vom Pythonquelltext ist. Hier sind ein paar Vorschläge:

Sublime Text (http://www.sublimetext.com/): Ein großartiger Allzweckeditor der einfach zu benutzen ist. SeinCtrl+B Tastaturkürzel lässt dich Pythondateien an denen du arbeitest direkt ausführen. Läuft auf Windows,Mac und Linux.

Geany (http://www.geany.org/): Ein einfacher Editor der darauf abzielt nicht zu kompliziert zu sein. Verfügbarunter Windows und Linux (und du kannst es wahrscheinlich in deinem Softwarecenter finden).

TextMate (http://macromates.com/): Einer der beliebtesten Quelltexteditoren für Mac. Ehemals einkommerzielles Produkt ist er nun frei erhältlich.

Gedit (https://projects.gnome.org/gedit/) und Kate (http://kate-editor.org/): Falls du ein Linux mit Gnome oderKDE benutzt, könnte einer dieser beiden bereits installiert sein!

Komodo Edit (http://www.activestate.com/komodo-edit): ein geschmeidiger, freier Editor für Mac, Windowsund Linux basierend auf dem mächtigeren Komodo IDE.

Falls du unsere Empfehlung hören willst, probier zuerst Sublime Text aus.

Tipp

Wordpad, TextEdit, Notepad und Word sind keine geeigneten Quelltexteditoren.

Was ist Python eigentlich?Also, Python ist etwas, das Programmiersprache genannt wird. Es liest Text ein den Du geschrieben hast(üblicherweise als Code bezeichnet), verwandelt ihn in Befehle für den Computer und führt diese aus. Wir werdenlernen Code zu schreiben, der coole und nützliche Dinge tut. Du wirst nicht länger daran gebunden sein,Programme von anderen Leuten zu verwenden um mit Deinem Computer Dinge zu tun.

Erste Schritte — Introduction to Programming wi... 7/19/17, 6:36 PM

https://opentechschool.github.io/python-beginners/de/getting_started.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 1

Page 3: Willkommen am Institut für Informatik — Institut für

Python ist praktisch einfach ein weiteres Programm auf Deinem Computer. Zuerst werden wir lernen Python zubenutzen und mit ihm zu interagieren. Es gibt mehrere Wege das zu tun; der erste ist mit dem Python Interpreterüber die Textkonsole Deines Betriebssystems zu interagieren.

Eine Konsole (auch ‘Terminal’ oder ‘Prompt’) ist ein schriftlicher Weg mit Deinem Betriebssystem zu interagieren,so wie der ‘Desktop’ zusammen mit Deiner Maus ein grafischer Weg zu Deinem System ist.

Eine Konsole auf Mac OS X öffnenDie Standardkonsole in OS X heißt Terminal. Öffne Terminal indem du nach Applications navigierst, dann nachUtilities und dort doppelt auf das Terminal-Programm klickst. Du kannst es auch durch die Systemsuche obenrechts suchen.

Das Kommandozeilenterminal ist ein Werkzeug um mit Deinem Computer zu interagieren. Ein Fenster mit einerNachricht und einem Prompt öffnet sich, ähnlich zu folgendem:

mycomputer:~ myusername$

Eine Konsole unter Linux öffnenVerschiedene Linuxdistributionen (bspw. Ubuntu, Fedora, Mint) können unterschiedliche Konsolenprogrammehaben, die üblicherweise Terminal genannt werden. Welches du genau startest, und wie, hängt von deinerDistribution ab. Unter Ubuntu wirst du vermutlich das Gnome Terminal öffnen wollen. Es sollte eine Aufforderung infolgendem Stil erscheinen:

myusername@mycomputer:~$

Eine Konsole unter Windows öffnenDie Windows-Konsole wird Eingabeaufforderung genannt, oder cmd. Ein leichter Weg zu ihr zu gelangen ist dieTastenkombination Windows+R ( Windows meint den Knopf mit dem Windows-Logo), welches den Ausführen-Dialog öffnen sollte. Gib dann cmd ein und drück Enter oder klick auf Ok. Du kannst sie auch aus dem Startmenüheraussuchen. Sie sollte in etwa so aussehen:

C:\Users\myusername>

Die Windows Kommandozeilenaufforderung ist nicht ganz so mächtig wie ihre Entsprechungen unter Linux und OSX, also möchtest du vielleicht den Python Interpreter (siehe unten) direkt ausführen, oder das IDLE-Programm dasmit Python mitkommt. Du kannst sie im Startmenü finden.

Python verwendenDas Pythonprogramm das du installiert hast agiert standardmäßig als etwas das sich Interpreter nennt. EinInterpreter nimmt Befehle entgegen und führt sie dann aus – sehr praktisch um Dinge auszuprobieren.

Tippe in deiner Konsole python ein, drücke Enter und der Python-Interpreter sollte starten.

Um herauszufinden welche Version von Python du hast, benutz python -V um es dir sagen zu lassen.

Mit Python interagierenSobald Python startet, zeigt es Dir einige Kontextinformationen ähnlich zu diesen:

Erste Schritte — Introduction to Programming wi... 7/19/17, 6:36 PM

https://opentechschool.github.io/python-beginners/de/getting_started.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 2

Page 4: Willkommen am Institut für Informatik — Institut für

Python 3.3.2 (default, May 21 2013, 15:40:45)

[GCC 4.8.0 20130502 (prerelease)] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>>

Bemerkung

Der Prompt >>> in der letzten Zeile signalisiert dass Du Dich nun in der interaktiven Python Konsole befindet,auch ‘’Python Shell’’ genannt. Diese Konsole ist etwas anderes als das normale Kommandozeilenterminal!

Nun kannst Du Python Code eingeben. Versuche:

print("Hello world")

Press Enter and see what happens. After showing the results, Python will bring you back to the interactive prompt,where you could enter another command:

>>> print("Hello world")

Hello world

>>> (1 + 4) * 2

10

Ein extrem nützlicher Befehl ist help() , welcher eine Hilfefunktion startet um all die Dinge herauszufinden, diePython dich machen lässt, direkt im Interpreter. Drücke q um das Hilfefenster wieder zu schließen

Um die Python Shell zuverlassen, drücke Ctrl-Z und Enter unter Windows, oder Ctrl-D unter OS X oder Linux.Alternativ kannst Du auch den Python-Befehl exit() ausführen.

Pythonprogramme ausführenFalls du viel Pythonquelltext auszuführen hast wirst du ihn in eine Datei speichern wollen damit du zum Beispielkleine Stücke verändern kannst (einen Fehler beheben) und es nochmal ausführen kannst ohne den Rest wiederund wieder einzutippen. Stattdessen kannst du deinen Quelltext in eine Datei speichern und den Dateinamen andas python-Programm liefern. Es wird dann diese Datei ausführen statt den interaktiven Interpreter auszuführen.

Lass uns das ausprobieren. Erstelle eine Datei hello.py in deinem aktuellen Verzeichnis mit deinemLieblingseditor und schreib den print-Befehl von oben. Jetzt speicher die Datei. Unter Linux und OS X kannst duauch touch hello.py ausführen um eine leere Datei zu erstellen. Diese Datei mit Python auszuführen ist ganzeinfach:

$ python hello.py

Bemerkung

Versichere dich, dass du dich in der Kommandozeile befindest, die du an $ oder > am Ende erkennst, nicht inPythons (welche >>> hat).

Unter Windows solltest du doppelt auf die Pythondatei klicken können um sie auszuführen.

Wenn du jetzt Enter drückst, wird die Datei ausgeführt und du siehst ihre Ausgabe wie vorher. Aber diesmal,nachdem Python fertig ist all die Befehle aus der Datei auszuführen, wird es zur System-Eingabeaufforderungzurückkehren, statt zur interaktiven Shell zurückzugehen.

Wir sind jetzt startklar und können mit der Schildkröte anfangen!

Bemerkung

Erste Schritte — Introduction to Programming wi... 7/19/17, 6:36 PM

https://opentechschool.github.io/python-beginners/de/getting_started.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 3

Page 5: Willkommen am Institut für Informatik — Institut für

Back to top

Edit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/getting_started.rst)Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+getting_started)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

Du siehst kein “Hello world” sondern irgendeinen komischen Fehler wie “can’t open file” oder “No such file ordirectory”? Vielleicht befindet sich deine Kommandozeile nicht in dem Ordner, in dem du die Datei gespeicherthast. In der Kommandozeile kannst du den Befehl cd (“change directory”) benutzen um deinen ausgewähltenOrdner zu wechseln. Unter Windows kannst du folgendes ausprobieren:

> cd Desktop\Python_Exercises

Unter Linux und OS X möchtest du etwas wie:

$ cd Desktop/Python_Exercises

Dieser Befehl wechselt in das Verzeichnis Python_Exercises innerhalb des Desktop-Ordners (auf DeinemComputer heißt dieser eventuell anders). Falls Du nicht weisst in welchem Verzeichnis Du die Textdatei mit demProgramm abgespeichert hast, kannst Du einfach das Ordnersymbol in das Terminalfenster ziehen. Falls Dunicht weisst in welchem Verzeichnis sich Deine Textkonsole grade befindet, verwende den Befehl pwd, der für“print working directory” steht.

Warnung

Wenn Du mit dem turtle-Modul experimentierst, vermeide es Deine Datei turtle.py zu nennen — verwendelieber Namen wie quadrat.py oder rechteck.py . Andernfalls wird Python jedesmal wenn Du den Namenturtle verwendest, Deine Datei anstatt dem Modul turtle verwenden.

Erste Schritte — Introduction to Programming wi... 7/19/17, 6:36 PM

https://opentechschool.github.io/python-beginners/de/getting_started.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 4

Page 6: Willkommen am Institut für Informatik — Institut für

Einfaches Zeichnen mit turtleEinführungTurtle ist wie ein Zeichenbrett.

Das Modul besitzt Funktionen wie turtle.forward(...) und turtle.left(...) welche die Schildkröte umherbewegen.

Bevor du turtle benutzen kannst musst du es importieren. Wir empfehlen erstmal mit ihr in einem interaktivenInterpreter herumzuexperimentieren, da ein bisschen zusätzliche Arbeit notwendig ist um aus Dateien zu arbeiten.Gehe in deine Konsole und tippe:

import turtle

Bemerkung

Du siehst nichts unter Mac OS? Probier einen Befehl wie turtle.forward(0) zu erteilen und zu schauen, obsich ein neues Fenster hinter deiner Kommandozeile geöffnet hat.

Bemerkung

Arbeitest du mit Ubuntu und hast die Fehlermeldung “No module named _tkiner” bekommen? Installier dasfehlende Paket mit sudo apt-get install python3-tk

Bemerkung

Auch wenn es verlockend ist einfach alles auf dieser Seite in dein Terminal zu kopieren würden wir dichermutigen, alle Befehle selbst zu tippen. Tippen bringt die Syntax in deine Finger (um das Muskelgedächtnisaufzubauen!) und kann sogar helfen komische Syntaxfehler zu vermeiden.

turtle.forward(25)

turtle.left(30)

Einfaches Zeichnen mit turtle — Introduction to ... 7/19/17, 6:35 PM

https://opentechschool.github.io/python-beginners/de/simple_drawing.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 5

Page 7: Willkommen am Institut für Informatik — Institut für

Die Funktion turtle.forward(...) weist die Schildkröte an, sich eine gewisse Distanz vorwärts zu bewegen.turtle.left(...) erwartet einen Winkel, den du nach links drehen willst. Es gibt außerdem nochturtle.backward(...) und turtle.right(...) .

Bemerkung

Du willst neu anfangen? Du kannst turtle.reset() eintippen um die Zeichnungen, die deine turtle bishergemacht hat, zu löschen. Wir werden turtle.reset() gleich detaillierter beleuchten.

Standardmässig wird die Schildkröte auf dem Bildschirm als Dreieck dargestellt. Wie langweilig! Lass uns mit derFunktion turtle.shape() eine richtige Schildkröte daraus machen:

turtle.shape("turtle")

Das ist doch viel niedlicher!

Wenn Du die Befehle in eine Datei geschrieben hast, hast Du vielleicht bemerkt, dass das turtle-Fensterverschwindet, nachdem die Schildkröte ihre Bewegung vollendet hatte. (Das geschieht weil Python beendet wird,sobald der letzte Befehl ausgeführt wurde. Und da das turtle-Fenster mit zu Python gehört, wird es auchgeschlossen.) Um das zu verhindern, füge am Ende Deines Programms turle.exitonclick() hinzu. Jetzt bleibtdas Fenster offen bis Du noch einmal darauf klickst:

import turtle

turtle.shape("turtle")

turtle.forward(25)

turtle.exitonclick()

Bemerkung

Python ist eine Programmiersprache in der horizontale Einrückung des Textes wichtig ist. Wir werden allesdarüber später im Kapitel “Funktionen” lernen, behalte bis dahin im Kopf das herumirrende Leerzeichen oderTabs vor einer Zeile Pythoncode einen unvorhergesehenen Fehler auslösen können.

Ein Rechteck zeichnenBemerkung

Niemand erwartet von Dir, dass Du sofort auf die Antwort kommst. Lerne durch Ausprobieren! Experimentieredamit was Python tut wenn Du verschiedene Befehle erteilst, was zu schönen (wenn auch manchmalunerwarteten) Ergebnissen führt, und was Fehler verursacht. Wenn Du etwas findest dass für Dich interessanteErgebnisse erzeugt und Du weiter damit herumprobieren möchtest, ist das auch in Ordnung. Zögere nicht etwaszu versuchen, und daraus zu lernen falls es schief geht!

Einfaches Zeichnen mit turtle — Introduction to ... 7/19/17, 6:35 PM

https://opentechschool.github.io/python-beginners/de/simple_drawing.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 6

Page 8: Willkommen am Institut für Informatik — Institut für

ÜbungZeichne ein Quadrat so wie im folgenden Bild:

Für ein Viereck brauchst du vermutlich einen rechten Winkel, welcher 90˚ beträgt.

Lösungturtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

Bemerkung

Beachte wie die Schildkröte an der gleichen Stelle in der gleichen Richtung startet und nach Zeichnen desQuadrats stoppt. Dies ist als Konvention nützlich, denn es erleichtert das Zeichnen von mehreren geometrischenFormen hintereinander.

Hide

BonusFalls Du kreativ werden möchtest, kannst Du die geometrische Form mit den Funktionen turtle.width(...) undturtle.color(...) verändern. Wie kannst Du diese Funktionen verwenden? Bevor Du eine Funktion benutzen

kannst, musst Du ihre Signatur (zum Beispiel die Anzahl und Bedeutung ihrer Parameter). Um das herauszufindenkannst Du in der interaktiven Python Shell help(turtle.color) eingeben. Falls sich dort eine grosse Menge Textbefindet, schreibt Python den Hilfetext in einen Pager, in welchem Du auf- und abscrollen kannst. Drücke die Tasteq um den Pager wieder zu verlassen.

Tipp

Siehst du ungefähr folgenden Fehler:

NameError: name 'turtle' is not defined

In Python musst Du Namen von Modulen oder Funktionen importieren bevor Du sie verwenden kannst. Alsomusst Du in einem neuen Python-Shell Fenster zuerst import turtle schreiben, bevor help(turtle.color)funktioniert.

Ein anderer Weg die Funktionen herauszufinden ist die online documentation (http://docs.python.org/library/turtle).

Vorsicht

Falls Du etwas falsch gezeichnet hast, kannst Du turtle befehlen, die Zeichenfläche mit dem turtle.reset()Befehl vollständig zu löschen oder den letzten Befehl mit turtle.undo() Rückgängig zu machen.

Einfaches Zeichnen mit turtle — Introduction to ... 7/19/17, 6:35 PM

https://opentechschool.github.io/python-beginners/de/simple_drawing.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 7

Page 9: Willkommen am Institut für Informatik — Institut für

Tipp

Wie du vielleicht in der Hilfe gelesen hast, kannst du die Farbe mit turtle.color(colorstring) ändern. Daskönnte unter Anderem “red”, “green” oder “violet” sein. Schau in das colours manual (http://www.tcl.tk/man/tcl8.5/TkCmd/colors.htm) für eine ausführliche Liste.

Ein Rechteck zeichnenÜbungKannst du auch ein Rechteck zeichenn?

Lösungturtle.forward(100)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(100)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

Hide

BonusWie wäre es mit einem Dreieck? In einem gleichseitigen Dreieck (alle Seiten haben die gleiche Länge) hat jedeEcke einen Winkel von 60 Grad.

Mehr QuadrateÜbungJetzt zeichne ein schräg zur Seite gekipptes Quadrat. Und noch eins, und noch eins. Experimentiere mit denWinkeln zwischen den einzelnen Quadraten.

Das Bild zeigt drei Drehungen um jeweils 20 Grad. Du kannst zum Beispiel auch 20, 30 oder 40 Grad ausprobieren.

Einfaches Zeichnen mit turtle — Introduction to ... 7/19/17, 6:35 PM

https://opentechschool.github.io/python-beginners/de/simple_drawing.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 8

Page 10: Willkommen am Institut für Informatik — Institut für

Back to top

Edit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/simple_drawing.rst)Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+simple_drawing)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

Lösungturtle.left(20)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.left(30)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.left(40)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

Hide

Einfaches Zeichnen mit turtle — Introduction to ... 7/19/17, 6:35 PM

https://opentechschool.github.io/python-beginners/de/simple_drawing.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 9

Page 11: Willkommen am Institut für Informatik — Institut für

7/19/2017 Summary of Turtle Methods — IntroToPythonUsingTurtles

http://interactivepython.org/runestone/static/IntroPythonTurtles/Summary/summary.html 1/6

Summary of Turtle MethodsMethod Parameters Description

Turtle None Creates and returns a new turtle object

forward amount Moves the turtle forward by the specified amount

backward amount Moves the turle backward by the specified amount

right angle Turns the turtle clockwise

left angle Turns the turtle counter clockwise

penup None Picks up the turtle’s pen

pendown None Puts down the turtle’s pen

up None Picks up the turtle’s pen

down None Puts down the turtle’s pen

color color name Changes the color of the turtle’s pen

fillcolor color name Changes the color of the turtle will use to fill a polygon

heading None Returns the current heading

position None Returns the current position

goto x,y Move the turtle to position x,y

begin_fill None Remember the starting point for a filled polygon

end_fill None Close the polygon and fill with the current fill color

dot None Leave a dot at the current position

stamp None Leaves an impression of a turtle shape at the current location

shape shapename Should be ‘arrow’, ‘classic’, ‘turtle’, or ‘circle’

Note

This workspace is provided for your convenience. You can use this activecode window to try outanything you like.

1

2

http://interactivepython.org/runestone/static/IntroPythonTurtles/Summary/summary.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 10

Page 12: Willkommen am Institut für Informatik — Institut für

VariablenEinführungPuh. Wenn Du mit den Winkeln experimentierst, musst Du jedes Mal an drei verschiedenen Stellen den Codeverändern. Jetzt stelle Dir vor Du möchtest mit allen Abmessungen des Quadrates experimentieren, oder sogar mitRechtecken! Das muss besser gehen.

An dieser Stelle kommen Variablen ins Spiel: Du kannst ab nun Python befehlen, jedes Mal wenn Du einebestimmte Variable verwendest, an dieser Stelle etwas anderes einzusetzen. Dieses Konzept ist ähnlich zurAlgebra, wo Du schreiben könntest: x sei 5. Dann ist x * 2 natürlich 10.

In der Syntax von Python hat die gleiche Bedeutung:

x = 5

Falls Du nach diesem Befehl print(x) ausführst, wird der Wert von x ausgegeben — 5. Du kannst das gleicheauch mit turtle kombinieren.

turtle.forward(x)

Variablen können alles mögliche speichern, nicht nur Zahlen. Etwas anderes typisches das oft in Variablengespeichert wird sind Strings - Textzeilen. Strings werden durch " (doppelte Anführungszeichen) vor und nachdem Text gekennzeichnet. Du wirst später noch mehr über diese sogenannten Datentypen in Python und was Dumit ihnen tun kannst, lernen.

Du kannst sogar eine Variable verwenden um der Schildkröte einen Namen zu geben:

timmy = turtle

Jedes Mal wenn Du nun timmy schreibst, weiß Python, dass Du turtle meinst. Du kannst auch weiterhinturtle verwenden:

timmy.forward(50)

timmy.left(90)

turtle.forward(50)

Eine Variable genannt angleÜbungWenn wir eine Variable angle (Winkel) nennen, wie könnten wir sie verwenden um mit dem Programm mit dengekippten Quadraten zu experimentieren?

Lösung

Variablen — Introduction to Programming with P... 7/19/17, 6:37 PM

https://opentechschool.github.io/python-beginners/de/variables.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 11

Page 13: Willkommen am Institut für Informatik — Institut für

Back to topEdit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/variables.rst)

Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+variables)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

angle = 20

turtle.left(angle)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.left(angle)

... und so weiter

Hide

BonusKannst Du das gleiche Prinzip auch auf die Grösse der Quadrate anwenden?

Das Haus vom NikolausÜbungZeichne ein Haus.

Du kannst die Länge der diagonalen Linie mit dem Satz des Pythagoras ausrechnen. Diese Zahl ist es wert in einerVariable gespeichert zu werden. Um die Quadratwurzel einer Zahl in Python zu berechnen, musst Du das mathModul importieren und die Funktion math.sqrt() aufrufen. Das Quadrat einer Zahl kannst Du mit dem Operator** ausrechnen:

import math

c = math.sqrt(a**2 + b**2)

Variablen — Introduction to Programming with P... 7/19/17, 6:37 PM

https://opentechschool.github.io/python-beginners/de/variables.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 12

Page 14: Willkommen am Institut für Informatik — Institut für

SchleifenEinführungWie du sicher bemerkt hast, enthalten unsere Programme oft Wiederholungen. In Python gibt es ein mächtigesKonzept genannt Schleifen (Jargon: Iterationen), welches wir später genauer erkunden werden. Probieren wir dochzunächst mal dieses simple Beispiel aus:

for name in "John", "Sam", "Jill":

print("Hello " + name)

Dies ist außerordentlich hilfreich wenn wir etwas mehrere Male tun möchten — beispielsweise die Umrandung einergeometrischen Form zeichnen — aber den Programmcode dafür nur einmal schreiben möchten. Hier ist eineandere Version einer Schleife:

for i in range(10):

print(i)

Beachte dass wir nur eine einzige Programme Zeile mit i schreiben, es aber 10 unterschiedliche Werte annimmt.

Die range(n) -Funktion kann man als eine Abkürzung für 0, 1, 2, ..., n-1 sehen. Falls du mehr über siewissen möchtest kannst du die Hilfe im Pythoninterpreter benutzen indem du help(range) tippst. Benutz dieq -Taste um die Hilfe wieder zu verlassen.

Du kannst auch Elemente Deiner Wahl in einer Schleife verarbeiten:

total = 0

for i in 5, 7, 11, 13:

print(i)

total = total + i

print(total)

Schreib das Beispiel aus und führ es mit Python aus um zu überprüfen, ob es so funktioniert wie du möchtest.

Bemerkung

Beachte wie oben die Zeilen, die wiederholt werden, die sind die eingerückt sind. Das ist ein wichtiges Konzept inPython - das ist wie es weiß welche Zeilen zur for -Schleife gehören und welche danach kommen, als Rest desProgramms. Benutz vier Leerzeichen (drück Tab) um deinen Quelltext einzurücken.

Manchmal möchtest du Code wiederholen aber scherst dich nicht um den Wert von der Variable i ; hier bietet essich an diese durch _ zu ersetzen. Das macht deutlich, dass uns der Wert egal ist, oder wir ihn nicht benutzen.Hier ist ein einfaches Beispiel:

for _ in range(10):

print("Hello!")

Du magst dich vielleicht über die Variable i wundern oder auch nicht – warum wird sie oben die ganze Zeitverwendet? Nunja, sie steht einfach für “index” und ist der häufigste Variablenname den man überhaupt in Quelltextfindet. Aber wenn du eine Schleife über etwas anderes als nur Zahlen ausführst, wähle besser einen anderenNamen. Zum Beispiel:

Schleifen — Introduction to Programming with P... 7/19/17, 6:37 PM

https://opentechschool.github.io/python-beginners/de/loops.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 13

Page 15: Willkommen am Institut für Informatik — Institut für

for drink in list_of_beverages:

print("Would you like a " + drink + "?")

Das ist sofort klarer zu verstehen als wenn wir i statt drink benutzt hätten.

Eine gestrichelte Linie zeichnenÜbungZeichne eine gestrichelte Linie. Du kannst die Schildkröte bewegen ohne dass sie zeichnet, indem Du die Funktionturtle.penup() aufrufst; um sie wieder zeichnen zu lassen, verwende turtle.pendown() .

Lösungfor i in range(10):

turtle.forward(15)

turtle.penup()

turtle.forward(5)

turtle.pendown()

Hide

BonusKannst du die Striche immer größer werden lassen?

Hinweis

Verwirrt? Schau dir i in jedem Schleifendurchlauf an:

for i in range(10):

print(i)

# write more code here

Kannst du i — üblicherweise als Index- oder Schleifenvariable bezeichnet — benutzen um immer größereSchritte zu machen?

KommentareIm obigen Beispiel wird die Zeile die mit # anfängt ein Kommentar genannt. In Python wird alles das auf der Zeilenach # folgt ignoriert. Benutz Kommentare um zu erklären was dein Programm macht ohne dasProgrammverhalten zu verändern. Sie können auch benutzt werden um kurzzeitig Quelltext zu deaktiveren, oder“auszukommentieren”.

Kommentare können auch an das Zeilenende gepackt werden, wie hier:

turtle.left(20) # tilt our next square slightly

Schleifen — Introduction to Programming with P... 7/19/17, 6:37 PM

https://opentechschool.github.io/python-beginners/de/loops.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 14

Page 16: Willkommen am Institut für Informatik — Institut für

Back to topEdit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/loops.rst)

Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+loops)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

Effizientere QuadrateÜbungDie Quadrate die wir am Anfang des Materials gemalt haben erforderten viele wiederholten Quelltextzeilen. Kannstdu ein Programm zum Malen von Quadraten mit weniger Zeilen schreiben wenn du Schleifen benutzt?

Lösungfor _ in range(4):

turtle.forward(100)

turtle.left(90)

Hide

BonusProbier Schleifen zu verschachteln (nesting) indem du eine direkt in die andere packst, mit einigen Malanweisungendie in beiden drin sind. Das könnte in etwa so aussehen:

for ...:

for ...:

# drawing code inside the inner loop goes here

...

# you can put some code here to move

# around after!

...

Ersetz ... mit deinem eigenen Quelltext und schau, ob du etwas lustiges oder interessantes erstellen kannst.Fehler sind erwünscht!

Schleifen — Introduction to Programming with P... 7/19/17, 6:37 PM

https://opentechschool.github.io/python-beginners/de/loops.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 15

Page 17: Willkommen am Institut für Informatik — Institut für

Benutzerdefinierte FunktionenEinführungProgrammierer können mit einigen ganz schön komplexen und abstrakten Probleme umgehen, aber ein Zug vonguten Programmierern ist, dass sie faul sind. Sie wollen nur mit einer Sache gleichzeitig umgehen müssen. Alsobrauchst du einen Weg um Probleme in kleinere, abgesonderte Teile zu zerlegen, damit du dich auf nur einen Teilkonzentrieren kannst.

Funktionen sind ein Weg um diese Abstraktion in Python abzubilden. Lass uns turtle.reset() betrachten. resetist eine Funktion die wir auf unserer turtle aufrufen und es ist eigentlich eine Abstraktion für eine Vielzahl vonSchritten, und zwar:

Lösche die Zeichenfläche.

Setze die Linienbreite und -Farbe zurück zu den Startwerten.

Bewege die Schildkröte in ihre Ausgangsposition zurück.

Aber weil all dieser Quelltext in der Funktion enthalten ist müssen wir uns keine Sorgen über die Details machen.Wir können die Funktion einfach ausführen und wissen, was sie für uns tun wird.

Also - wie schreiben wir unsere eigene?

Eine Funktion kann in Python mit dem Schlüsselwort def definiert werden:

def line_without_moving():

turtle.forward(50)

turtle.backward(50)

Diese von uns definierte Funktion heisst line_without_moving . Sie ist eine Abstraktion für zwei Bewegungen derSchildkröte - ein Schritt vorwärts und ein Schritt rückwärts.

Um sie zu benutzen (oder wie es häufig genannt wird, “sie aufzurufen”), schreib ihren Namen gefolgt von rundenKlammern:

line_without_moving()

turtle.right(90)

line_without_moving()

turtle.right(90)

line_without_moving()

turtle.right(90)

line_without_moving()

Wir könnten mehr Funktionen implementieren, um einige der Wiederholungen loszuwerden:

def star_arm():

line_without_moving()

turtle.right(360 / 5)

for _ in range(5):

star_arm()

Wichtig

Benutzerdefinierte Funktionen — Introduction to ... 7/19/17, 7:09 PM

https://opentechschool.github.io/python-beginners/de/functions.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 16

Page 18: Willkommen am Institut für Informatik — Institut für

Python benutzt Einrückung mit Leerzeichen um zusammengehörende Codeabschnitte zu kennzeichnen. EinBlock (wie die obige Funktion) wird in Python mit einem Doppelpunkt am Ende der Zeile und Einrückung derfolgenden Zeilen — üblicherweise vier Leerzeichen — gekennzeichnet. Der Block endet sobald die Zeilen nichtmehr eingerückt sind.Das ist ein Unterschied zu vielen anderen Programmiersprachen, die Sonderzeichen (etwa geschweifteKlammern {} ) verwenden um Codeblöcke zu kennzeichnen.

Verwende niemals Tabulatoren um Codeblöcke einzurücken, nur Leerzeichen. Du kannst – und solltest – DeinenEditor so konfigurieren, dass er vier Leerzeichen einsetzt sobald Du die Tab-Taste drückst. Das Problem mit denTabulatoren ist, dass andere Programmierer Leerzeichen verwenden, und falls beide in der gleichen Python-Dateiverwendet werden, wird Python sie fehlerhaft interpretieren. Im besten Fall gibt es eine Fehlermeldung und imschlimmsten Fall tauchen undurchsichtige schwer zu findende Fehler auf.

Eine Funktion für ein ViereckÜbungSchreibe eine Funktion die ein Viereck zeichnet. Kannst du diese Funktion benutzen um das Programm mit dengekippten Vierecken zu verbessern? Lässt es sich leichter mit dem Programm experimentieren wenn du Funktionenbenutzt?

Lösungdef tilted_square():

turtle.left(20) # now we can change the angle only here

for _ in range(4):

turtle.forward(50)

turtle.left(90)

tilted_square()

tilted_square()

tilted_square()

# bonus: you could have a separate function for drawing a square,

# which might be useful later:

def square():

for _ in range(4):

turtle.forward(50)

turtle.left(90)

def tilted_square():

turtle.left(20)

square()

# etc

Hide

Eine Funktion für ein HexagonÜbungSchreibe eine Funktion die ein Hexagon zeichnet.

Benutzerdefinierte Funktionen — Introduction to ... 7/19/17, 7:09 PM

https://opentechschool.github.io/python-beginners/de/functions.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 17

Page 19: Willkommen am Institut für Informatik — Institut für

Jetzt kombiniere diese Funktion zu einer Honigwabe. Zeichne erst einmal nur eine einzige Ebene, ungefähr so:

Probier es selbst!

Hinweis

Stell sicher das deine Hexagonfunktion die Schildkröte zu exakt derselben Position und Ausrichtung zurückkehrenlässt bevor es das Hexagon gemalt hat. Das macht es einfacher darüber nachzudenken.

Lösung

Benutzerdefinierte Funktionen — Introduction to ... 7/19/17, 7:09 PM

https://opentechschool.github.io/python-beginners/de/functions.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 18

Page 20: Willkommen am Institut für Informatik — Institut für

Back to topEdit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/functions.rst)

Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+functions)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

def hexagon():

for _ in range(6):

turtle.forward(100)

turtle.left(60)

for _ in range (6):

hexagon()

turtle.forward(100)

turtle.right(60)

Du könntest auch die Befehle turtle.forward(100); turtle.right(60) in die Funktion stellen, aber in diesemFall solltest Du die Funktion besser nicht hexagon nennen. Das wäre irreführend, da die Funktion dann nicht nur einSechseck zeichnen, sondern auch zur Position der nächsten Wabe vorrücken würde. Fall Du später die Funktionhexgon ausserhalb des Wabenprogramms verwenden möchtest wäre diese Namensgebung verwirrend.

Hide

Benutzerdefinierte Funktionen — Introduction to ... 7/19/17, 7:09 PM

https://opentechschool.github.io/python-beginners/de/functions.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 19

Page 21: Willkommen am Institut für Informatik — Institut für

Funktionen mit ParameternEinführungWenn wir unseren Code minimieren und Funktionen hinzufügen um Wiederholungen zu entfernen faktorisieren wirihn. Das ist eine gute Sache. Aber die Funktionen die wir bis jetzt definiert haben sind nicht sehr flexibel. DieVariablen sind innerhalb der Funktionen definiert, falls wir also einen anderen Winkel oder Distanz benutzen wollenmüssen wir eine neue Funktion schreiben. Unsere hexagon-Funktion kann nur Hexagone einer Größe zeichnen!

Deshalb benötigen wir die Möglichkeit Parameter, auch Argumente genannt, an eine Funktion zu übergeben. Sokönnen die Variablen innerhalb der Funktion jedes Mal wenn die Funktion aufgerufen wird, andere Werteannehmen:

Erinnere Dich wie wir die Funktion line_without_moving() im vorigen Abschnitt definiert haben:

def line_without_moving():

turtle.forward(50)

turtle.backward(50)

Wir können die Funktion verbessern, indem wir ihr einen Parameter übergeben:

def line_without_moving(length):

turtle.forward(length)

turtle.backward(length)

Der Parameter fungiert als Variable die nur innerhalb der Funktionsdefinition bekannt ist. Wir verwenden diese neudefinierte Funktion, indem wir sie mit dem Wert für den Parameter aufrufen:

line_without_moving(50)

line_without_moving(40)

Wir haben bereits seit dem Anfang des Tutorials Funktionen mit Parametern verwendet, z.B. turtle.forward() ,turtle.left() , etc...

Wir können so viele Argumente (oder Parameter) wie wir möchten für eine Funktio definieren. Die einzelnenArgumente sind dabei durch Kommata getrennt und haben alle unterschiedliche Namen:

def tilted_line_without_moving(length, angle):

turtle.left(angle)

turtle.forward(length)

turtle.backward(length)

Eine parametrisierte Funktion für ein Hexagon mitvariabler GrösseÜbungSchreibe eine Funktion die Dir jedes Mal wenn Du die Funktion aufrufsts, erlaubt Hexagone mit beliebiger Grösse zuzeichnen.

Funktionen mit Parametern — Introduction to Pr... 7/19/17, 7:09 PM

https://opentechschool.github.io/python-beginners/de/functions_parameters.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 20

Page 22: Willkommen am Institut für Informatik — Institut für

Lösungdef hexagon(size):

for _ in range(6):

turtle.forward(size)

turtle.left(60)

Hide

Eine Funktion mit mehreren ParameternÜbungSchreib eine Funktion die eine Form mit irgendeiner Anzahl von Seiten (lass uns annehmen mehr als zwei) vonirgendeiner Seitenlänge zeichnet. Lass sie ein paar verschiedene Formen malen.

Hier ist ein Beispiel wie man Formen mit dieser Funktion malt:

Tipp

Die Summe der Außenwinkel in jeder Form ist immer 360 Grad!

Lösungdef draw_shape(sides, length):

for _ in range(sides):

turtle.forward(length)

turtle.right(360 / sides)

Hide

BonusEs mag verrückt klingen, aber es ist durchaus möglich eine Funktion als Parameter einer anderen Funktion zuübergeben. Python betrachten Funktionen als total normale ‘Dinge’, genauso wie Variablen, Nummern oderZeichenketten (Strings).

Man könnte zum Beispiel eine Funktion zum Zeichnen von Formen schreiben die, abhängig von der turtle-Funktion( turtle.left oder ``turtle.right ) die man ihr übergibt, die Zeichenrichtung ändert.

Schau ob du das implementieren kannst!

Funktionen mit Parametern — Introduction to Pr... 7/19/17, 7:09 PM

https://opentechschool.github.io/python-beginners/de/functions_parameters.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 21

Page 23: Willkommen am Institut für Informatik — Institut für

Back to top

Edit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/functions_parameters.rst)Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+functions_parameters)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

Bemerkung

Eine Funktion (bspw. turtle.left ) zu übergeben heißt nicht sie aufzurufen, was man als turtle.left(45)schreiben würde.

Funktionen mit Parametern — Introduction to Pr... 7/19/17, 7:09 PM

https://opentechschool.github.io/python-beginners/de/functions_parameters.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 22

Page 24: Willkommen am Institut für Informatik — Institut für

VerzweigungenEinführungBisher haben wir vordefinierte Aufgaben erledigt, aber einmal ehrlich, die Programme waren kaum komplizierter alseine antike Drehorgel die eine vordefinierte Melodie vom Anfang bis zum Ende abspult. Verzweigugen sind das, wasProgrammieren sehr viel mächtiger macht. Verzweigungen testen den Inhalt einer Variablen und verhalten sicheinmal so falls die Variable einen bestimmten Wert hat, und anders falls nicht. Programmierer nennenVerzweigungen auch if Ausdrücke.

Um zu wissen ob eine Bedingung True oder False ist, brauchen wir einen neuen Datentyp: Boolean. Booleanserlauben logische Operationen, die entweder als wahr oder falsch ausgewertet werden. Unsere Verzweigung kannalso folgendermassen verstanden werden:

if (eine Bedingung die als True ausgewertet wird)*:dann führe diese Anweisungen nur für ‘True’ aus

else:andernfalls führe diese Anweisungen nur für ‘False’ aus.

Eine Bedingung kann alles sein, was zu wahr (True) oder falsch (False) evaluiert werden kann. Vergleiche ergebenimmer wahr oder falsch, zum Beispiel == (ist gleich), > (größer als), < (kleiner als).

Der else Block ist optional. Falls Du ihn auslässt und die Bedingung als ‘False’ ausgewertet wird, passiert nichtsweiter.

BeispieleHier sind einige Beispiele. Du kannst sie Zeile für Zeile lesen und nachdenken was sie tun, oder gleich ausführenum auf Nummer sicher zu gehen.

condition = True

if condition:

print("condition met")

if not condition:

print("condition not met")

direction = -30

if direction > 0 :

turtle.forward(direction)

else:

turtle.left(180)

turtle.forward(-direction)

Die Richtung festlegenDie Schildkröten in Python sind sehr gut darin, Befehle auszuführen. Lass uns die input() Funktion verwenden,

Verzweigungen — Introduction to Programming ... 7/19/17, 7:10 PM

https://opentechschool.github.io/python-beginners/de/conditionals.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 23

Page 25: Willkommen am Institut für Informatik — Institut für

Back to topEdit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/conditionals.rst)

Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+conditionals)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

um den Benutzer nach einer Richtung zu fragen, in die die Schildkröte bewegt werden soll. Um es nicht zukompliziert zu machen, erlauben wir nur zwei Befehle: ‘’links’’ und ‘’rechts’‘.

Bemerkung

Python 2 verwenden? Die Funktion input() heisst auch raw_input() .

Es ist viel einfacher dies als eine Funktion zu definieren, etwa folgendermassen:

def move():

direction = input("Go left or right? ")

if direction == "left":

turtle.left(60)

turtle.forward(50)

if direction == "right":

turtle.right(60)

turtle.forward(50)

Immer wenn Du nun move() verwendest, wirst Du gefragt entweder links oder rechts auszuwählen.

‘’Datenbastelei’‘In diesem Programm wird die Schildkröte nur auf die Befehle links und rechts reagieren, ohne jeglicheAbweichungen. Obwohl Links oder LINKS für einen Menschen das gleiche bedeutet wie links , ist das für einProgramm nicht der Fall. Python hat einige Hilfsmethoden die dabei helfen. Ein String hat die Methoden .strip() ,die Leerzeichen und Zeilenumbrüche von den Enden entfernt, und .lower() , welche den gesamten String inKleinbuchstaben umwandelt.

Here sind einige Beispiele, die die Auswirkungen von .strip() und .lower() illustrieren:

my_variable = " I Am Capitalised"

print(my_variable)

my_stripped = my_variable.strip()

print(my_stripped)

my_lower = my_variable.lower()

print(my_lower)

Versuche de Befehl direction = direction.strip().lower zu der Funktion move() hinzuzufügen. Beobachtedie Auswirkungen. Diese Art von Code wird von uns ‘’data munging’’ (Datenbastelei) genannt. Sie ist sehr häufig.

Kannst Du einig zusätzliche Eingabeoptionen hinzufügen, die die Schildkröte andere Dinge zeichnen lassen? Wiewäre es mit einem ‘’Sechseck’’ ( hexagon )?

Verzweigungen — Introduction to Programming ... 7/19/17, 7:10 PM

https://opentechschool.github.io/python-beginners/de/conditionals.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 24

Page 26: Willkommen am Institut für Informatik — Institut für

Bedingte SchleifenEinführungBedingte Schleifen sind ein Weg etwas zu wiederholen, solange eine bestimmte Bedingung erfüllt, oder True, ist.Falls die Bedingung immer erfüllt ist (also nie False wird), läuft die Schleife endlos weiter. Falls die Bedingung schonanfänglich falsch ist, wird der Code in der Schleife niemals ausgeführt! In Python werden bedingte Schleifen mit derwhile -Anweisung definiert:

word = ''

sentence = ''

print('Please enter some words.')

print('Include a period (.) when you are finished.')

while '.' not in word:

word = input('next word: ')

sentence = word + ' ' + sentence

print()

print('Aha! You said:')

print(sentence)

Wir nennen diesen Teil des Quelltextes die ‘Bedingung’: '.' not in word

Ob die Bedingung wahr (True) zurückgibt oder nicht entscheidet, ob der Quelltext innerhalb der while -Schleifeausgeführt wird.

Lies den obigen Quellcode und schau, ob du im Kopf herleiten kannst, was er tut (und was die endgültige Ausgabesein wird).

Dann kopier ihn in eine Datei, sagen wir satz.py , und führe ihn aus – schau genau, was er tut. Trifft das, was dudir gedacht hast, zu?

Bemerkung

Falls du Python 2 benutzt, wirst du input``mit ``raw_input ersetzen müssen, um das Programm korrektauszuführen.

SchildkrötengefängnisÜbungThe turtle has been up to its usual tricks again, robbing liquor stores and building up huge gambling debts. It’s timefor turtle to be put into a cell that it can’t get out of.

Lass uns eine neue Version von forward() bauen. Eine, die die Schildkröte herumdreht, falls sie versucht, sichweiter als 100 von ihrem Ursprung zu entfernen. Wir brauchen eine while -Schleife und einige neue turtle-Funktionen:

turtle.distance(0, 0) - Entfernung der Schildkröte vom Ursprung

turtle.towards(0, 0) - Der Winkel, der zurück zum Ursprungspunkt führt

turtle.setheading(Winkel) - Lege die Ausrichtung der Schildkröte direkt fest

Du kannst, wenn du magst, versuchen, mit der turtle in einem Interpreter herumzuspielen und die Funktionen zu

Bedingte Schleifen — Introduction to Programmi... 7/19/17, 7:10 PM

https://opentechschool.github.io/python-beginners/de/conditional_loops.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 25

Page 27: Willkommen am Institut für Informatik — Institut für

benutzen, um genau zu sehen, was sie tut.

Jetzt wirst du die Gefängnislogik implementieren müssen, indem du die turtle-Funktionen, vielleicht eine while -Schleife und ein bisschen bedingte Logik, verwendest. Es ist ein bisschen haarig, aber bleib dran! Scheue nichtdavor zurück, deine Idee mit einem Coach oder einem anderen Lernenden durchzusprechen.

Lösungdef forward(distance):

while distance > 0:

if turtle.distance(0,0) > 100:

angle = turtle.towards(0,0)

turtle.setheading(angle)

turtle.forward(1)

distance = distance - 1

Hide

Zeichne eine SpiraleSchleifen können mit der break -Anweisung unterbrochen werden. Das ist besonders nützlich, wenn du eineEndlosschleife schreibst, welches eine Schleife ist, deren Bedingung immer wahr (True) ist.

ÜbungSchreibe eine while -Schleife mit einer Bedingung, die immer wahr (True) ist, um eine Spirale zu malen. Unterbrichdie Schleife, wenn die turtle eine gewisse Distanz zum Mittelpunkt erreicht hat. Benutze die Funktionturtle.distance(x, y) , um die Entfernung der Schildkröte zu dem durch die x - und y -Koordinaten bestimmten

Punkt zu errechnen.

Um das zu tun, brauchst Du die Funktionen turtle.xcor() und turtle.ycor() , welche die Position derSchildkröte auf der X- und Y-Achse zurückgeben.

Bemerkung

Um eine Spirale zu zeichnen, muss die Schildkröte um einen konstanten Winkel gedreht werden und dabei umeine anwachsende Strecke vorwärts bewegt werden.

Lösungdef draw_spiral(radius):

original_xcor = turtle.xcor()

original_ycor = turtle.ycor()

speed = 1

while True:

turtle.forward(speed)

turtle.left(10)

speed += 0.1

if turtle.distance(original_xcor, original_ycor) > radius:

break

Hide

Bonus

Bedingte Schleifen — Introduction to Programmi... 7/19/17, 7:10 PM

https://opentechschool.github.io/python-beginners/de/conditional_loops.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 26

Page 28: Willkommen am Institut für Informatik — Institut für

Back to top

Edit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/conditional_loops.rst)Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+conditional_loops)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

Kannst du eine Bedingung für die Schleife formulieren, so dass du du keine Endlosschleife while True oder diebreak -Anweisung benötigst? Welche Version findest du einfacher zu verstehen?

Bedingte Schleifen — Introduction to Programmi... 7/19/17, 7:10 PM

https://opentechschool.github.io/python-beginners/de/conditional_loops.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 27

Page 29: Willkommen am Institut für Informatik — Institut für

Logische OperatorenEinführungVerzweigungen sind ein guter Weg um im Programm Entscheidungen zu treffen, indem geprüft wird ob etwas Trueist oder nicht. Aber häufig reicht eine Bedingung allein nicht aus. Vielleicht möchtest Du auch das Gegenteil DeinesErgebnisses prüfen. Oder falls Du eine Entscheidung aufgrund von turtle.xcor() und turtle.ycor() treffenmöchtest, musst Du beide verknüpfen. Das kannst Du mit logischen Operatoren erreichen.

Verneinung eines AusdrucksWenn wir möchten, dass etwas False ist, können wir den logischen Operator not verwenden:

x = False

if not x :

print("condition met")

else:

print("condition not met")

ÜbungDie Schildkröte enthält eine nützliche Funktion die sagt ob grade gezeichnet wird oder nicht; turtle.isdown() .Diese Funktion liefert True falls die Schildkröte im Zeichenmodus ist. Wie wir bereits gesehen haben, schalten dieFunktionen turtle.penup() und turtle.pendown() zwischen dem Modus zum Zeichnen beim Bewegen unddem Bewegungsmodus ohne Zeichnen hin und her.

Können wir eine Funktion schreiben die nur vorwärts geht falls die Schildkröte nicht im Zeichenmodus ist?

Lösungdef stealthed_forward(distance):

if not turtle.isdown():

turtle.forward(distance)

Hide

Dies und jenes oder etwas anderesZwei einfach zu verstehende Operatoren sind and und or . Sie tun genau das wonach sie sich anhören::

if 1 < 2 and 4 > 2:

print("condition met")

if 1 > 2 and 4 < 10:

print("condition not met")

if 4 < 10 or 1 < 2:

print("condition met")

Du bist nicht darauf angewiesen nur einen logischen Operator zu verwenden. Du kannst so viele miteinander

Logische Operatoren — Introduction to Program... 7/19/17, 7:11 PM

https://opentechschool.github.io/python-beginners/de/logical_operators.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 28

Page 30: Willkommen am Institut für Informatik — Institut für

Back to top

Edit on Github (https://github.com/opentechschool/python-beginners/edit/master/source/logical_operators.rst)Report a problem (https://github.com/OpenTechSchool/python-beginners/issues/new?title=Problem+with+logical_operators)

© Copyright (copyright.html) 2012–2014, OpenTechSchool and contributors.Mit Sphinx (http://sphinx-doc.org/) 1.3.1 erstellt.

kombinieren wie Du möchtest.

ÜbungWeiter oben haben wir die Schildkröte in einem kreisförmigen Gefängnis eingesperrt. Diesmal werden wir einQuadrat dazu verwenden. Falls die Schildkröte sich mehr als 100 Einheiten entlang der x- oder y-Achse vomMittelpunkt entfernt, drehen wir sie zurück zur Mitte um.

Lösungdef forward(distance):

while distance > 0:

if (turtle.xcor() > 100

or turtle.xcor() < -100

or turtle.ycor() > 100

or turtle.ycor() < -100):

turtle.setheading(turtle.towards(0,0))

turtle.forward(1)

distance = distance - 1

Hide

Logische Operatoren — Introduction to Program... 7/19/17, 7:11 PM

https://opentechschool.github.io/python-beginners/de/logical_operators.html

Einstieg in Python – Version vom 19. Juli 2017 Seite 29

Page 31: Willkommen am Institut für Informatik — Institut für

Python syntax and semanticsFrom Wikipedia, the free encyclopedia

The syntax of the Python programming language is the set of rules that defines how a Pythonprogram will be written and interpreted (by both the runtime system and by human readers).

Contents

1 Design philosophy2 Keywords3 Indentation4 Data structures

4.1 Base types4.2 Collection types4.3 Object system

5 Literals5.1 Strings

5.1.1 Normal string literals5.1.2 Multi-line string literals5.1.3 Raw strings5.1.4 Concatenation of adjacent string literals

5.2 Numbers5.3 Lists, tuples, sets, dictionaries

6 Operators6.1 Arithmetic6.2 Comparison operators6.3 Logical operators

7 Functional programming7.1 Comprehensions7.2 First-class functions7.3 Closures7.4 Generators7.5 Generator expressions7.6 Dictionary and set comprehensions

8 Objects8.1 With statements8.2 Properties8.3 Descriptors8.4 Class and static methods

9 Exceptions10 Comments and docstrings11 Function annotations12 Decorators13 Easter eggs14 References15 External links

Design philosophy

Python was designed to be a highly readable language.[1] It has a relatively uncluttered visual layoutand uses English keywords frequently where other languages use punctuation. Python aims to besimple and consistent in the design of its syntax, encapsulated in the mantra "There should beone—and preferably only one—obvious way to do it", from "The Zen of Python".[2]

This mantra is deliberately opposed to the Perl and Ruby mantra, "there's more than one way to doit".

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 30

Page 32: Willkommen am Institut für Informatik — Institut für

Keywords

Python has the following keywords or reserved words; they cannot be used as identifiers.[3][4]

and

as

assert

async[note 1]

await[note 1]

break

class

continue

def

del

elif

else

except

exec[note 2]

False[note 3]

finally

for

from

global

if

import

in

is

lambda

None

nonlocal[note 3]

not

or

pass

print[note 2]

raise

return

True[note 3]

try

while

with

yield

Notes

Starting from Python 3.5, async and await were introduced.[5]1. Starting from Python 3, exec and print are functions, so they are not keywords anymore.2. Starting from Python 3, keywords True, False and nonlocal were introduced.3.

Indentation

Python uses whitespace to delimit control flow blocks (following the off-side rule). Python borrowsthis feature from its predecessor ABC: instead of punctuation or keywords, it uses indentation toindicate the run of a block.

In so-called "free-format" languages — that use the block structure derived from ALGOL — blocks ofcode are set off with braces ({ }) or keywords. In most coding conventions for these languages,programmers conventionally indent the code within a block, to visually set it apart from thesurrounding code (prettyprinting).

Consider a function, foo, which is passed a single parameter, x, and if the parameter is 0 will call barand baz, otherwise it will call qux, passing x, and also call itself recursively, passing x-1 as theparameter. Here are implementations of this function in both C and Python:

foo function in C with K&R indent style:

void foo(int x){

if (x == 0) {bar();baz();

} else {qux(x);foo(x - 1);

}}

foo function in Python:

def foo(x):if x == 0:

bar()baz()

else:qux(x)foo(x - 1)

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 31

Page 33: Willkommen am Institut für Informatik — Institut für

Python mandates a convention that programmers in ALGOL-style languages often follow. Incorrectlyindented code can be understood by human reader differently than does a compiler or interpreter.

This example illustrates an indentation error in Python:

def foo(x):if x == 0:

bar()baz()

else:qux(x)

foo(x - 1)

Here, in contrast to the above Python foo example, the function call foo(x - 1) always gets executed,resulting in an endless recursion. Such an indentation error (like the accidental removal of theindentation in the last line) is only possible in programming languages that do not mark blocks withdistinct markers, like curly brackets in C. In this particular case, not even an editor with automaticindentation could prevent the erroneous behaviour of this Python code. This unintended error caneasily pass into the code base without prior noticing by the programmer. In most other programminglanguages, this would not be possible (deleting a block-end marker in C would lead to a compilererror), and this makes the Python syntax less robust than most other languages.

Both space characters and tab characters are currently accepted as forms of indentation in Python.Since many tools do not visually distinguish them, mixing spaces and tabs can create bugs that takespecific efforts to find (a perennial suggestion among Python users has been removing tabs as blockmarkers; other Python users propound removing spaces instead). Moreover, formatting routineswhich remove whitespace—for instance, many Internet forums—can destroy the syntax of a Pythonprogram, whereas a program in a bracketed language would merely become more difficult to read.

Many popular code editors handle Python's indentation conventions seamlessly, sometimes after aconfiguration option is enabled.

Data structures

Since Python is a dynamically typed language, Python values, not variables, carry type. This hasimplications for many aspects of the way the language functions.

All variables in Python hold references to objects, and these references are passed to functions; afunction cannot change the value of variable references in its calling function (not entirely true, seebelow). Some people (including Guido van Rossum himself) have called this parameter-passingscheme "Call by object reference." An object reference means a name, and the passed reference isan "alias", i.e. a copy of the reference to the same object, just like in C/C++. The object's value maybe changed in the called function with the "alias", for example:

>>> alist = ['a', 'b', 'c']>>> def myfunc(al):... al.append('x')... print al...>>> myfunc(alist)['a', 'b', 'c', 'x']>>> alist['a', 'b', 'c', 'x']

Function "myfunc" changed the value of "alist" with the formal argument "al", which is an alias of"alist". However, any attempt to operate on the alias itself will have no effect on the original object.In Python, non-innermost-local and not-declared-global accessible names are all aliases.

Among dynamically typed languages, Python is moderately type-checked. Implicit conversion isdefined for numeric types (as well as booleans), so one may validly multiply a complex number by along integer (for instance) without explicit casting. However, there is no implicit conversion between(e.g.) numbers and strings; a string is an invalid argument to a mathematical function expecting anumber.

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 32

Page 34: Willkommen am Institut für Informatik — Institut für

Base types

Python has a broad range of basic data types. Alongside conventional integer and floating-pointarithmetic, it transparently supports arbitrary-precision arithmetic, complex numbers, and decimalfloating point numbers.

Python supports a wide variety of string operations. Strings in Python are immutable, so a stringoperation such as a substitution of characters, that in other programming languages might alter astring in place, returns a new string in Python. Performance considerations sometimes push for usingspecial techniques in programs that modify strings intensively, such as joining character arrays intostrings only as needed.

Collection types

One of the very useful aspects of Python is the concept of collection (or container) types. In generala collection is an object that contains other objects in a way that is easily referenced or indexed.Collections come in two basic forms: sequences and mappings.

The ordered sequential types are lists (dynamic arrays), tuples, and strings. All sequences areindexed positionally (0 through length − 1) and all but strings can contain any type of object,including multiple types in the same sequence. Both strings and tuples are immutable, making themperfect candidates for dictionary keys (see below). Lists, on the other hand, are mutable; elementscan be inserted, deleted, modified, appended, or sorted in-place.

Mappings, on the other hand, are unordered types implemented in the form of dictionaries which"map" a set of immutable keys to corresponding elements (much like a mathematical function). Forexample, one could define a dictionary having a string "toast" mapped to the integer 42 or viceversa. The keys in a dictionary must be of an immutable Python type, such as an integer or a string,because under the hood they are implemented via a hash function. This makes for much fasterlookup times, but requires keys not change (and also results in a dictionary's lack of order).

Dictionaries are also central to the internals of the language as they reside at the core of all Pythonobjects and classes: the mappings between variable names (strings) and the values which thenames reference are stored as dictionaries (see Object system). Since these dictionaries are directlyaccessible (via an object's __dict__ attribute), metaprogramming is a straightforward and naturalprocess in Python.

A set collection type was added to the core language in version 2.4. A set is an unindexed,unordered collection that contains no duplicates, and implements set theoretic operations such asunion, intersection, difference, symmetric difference, and subset testing. There are two types ofsets: set and frozenset, the only difference being that set is mutable and frozenset is immutable.Elements in a set must be hashable and immutable. Thus, for example, a frozenset can be anelement of a regular set whereas the opposite is not true.

Python also provides extensive collection manipulating abilities such as built in containmentchecking and a generic iteration protocol.

Object system

In Python, everything is an object, even classes. Classes, as objects, have a class, which is known astheir metaclass. Python also supports multiple inheritance and mixins.

The language supports extensive introspection of types and classes. Types can be read andcompared—types are instances of type. The attributes of an object can be extracted as a dictionary.

Operators can be overloaded in Python by defining special member functions - for instance, defining__add__ on a class permits one to use the + operator on members of that class.

Literals

Strings

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 33

Page 35: Willkommen am Institut für Informatik — Institut für

Python has various kinds of string literals.

Normal string literals

Either single or double quotes can be used to quote strings. Unlike in Unix shell languages, Perl orPerl-influenced languages such as Ruby or Groovy, single quotes and double quotes functionidentically, i.e. there is no string interpolation of $foo expressions. However, interpolation can bedone in various ways: with the % string-format operator, using the "format" method or with "f-strings" (since Python 3.6[6]).

For instance, the Perl statement:

print "I just printed $num pages to the printer $printer\n"

is equivalent to any of these Python statements:

print("I just printed %s pages to the printer %s" % (num, printer))print("I just printed {0} pages to the printer {1}".format(num, printer))print("I just printed {num} pages to the printer {printer}".format(num=num, printer=printer))print(f"I just printed {num} pages to the printer {printer}")

Multi-line string literals

There are also multi-line strings, which begin and end with a series of three single or double quotesand function like here documents in Perl and Ruby.

A simple example with variable interpolation (using the % string-format operator) is:

print("""Dear %(recipient)s,

I wish you to leave Sunnydale and never return.

Not Quite Love,%(sender)s""" % {'sender': 'Buffy the Vampire Slayer', 'recipient': 'Spike'})

Raw strings

Finally, all of the previously mentioned string types come in "raw" varieties (denoted by placing aliteral r before the opening quote), which do no backslash-interpolation and hence are very usefulfor regular expressions; compare "@-quoting" in C#. Raw strings were originally included specificallyfor regular expressions. Due to limitations of the tokenizer, raw strings may not have a trailingbackslash.[7] Creating a raw string holding a Windows path ending with a backslash requires somevariety of workaround (commonly, using forward slashes instead of backslashes, since Windowsaccepts both).

Examples include:

>>> # A Windows path, even raw strings cannot end in a backslash>>> r"C:\Foo\Bar\Baz\" File "<stdin>", line 1

r"C:\Foo\Bar\Baz\"^

SyntaxError: EOL while scanning string literal

>>> dos_path = r"C:\Foo\Bar\Baz\ " # avoids the error by adding>>> dos_path.rstrip() # and removing trailing space'C:\\Foo\\Bar\\Baz\\'

>>> quoted_dos_path = r'"{}"'.format(dos_path)>>> quoted_dos_path'"C:\\Foo\\Bar\\Baz\\ "'

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 34

Page 36: Willkommen am Institut für Informatik — Institut für

>>> # A regular expression matching a quoted string with possible backslash quoting>>> re.match(r'"(([^"\\]|\\.)*)"', quoted_dos_path).group(1).rstrip()'C:\\Foo\\Bar\\Baz\\'

>>> code = 'foo(2, bar)'>>> # Reverse the arguments in a two-arg function call>>> re.sub(r'\(([^,]*?),([^ ,]*?)\)', r'(\2, \1)', code)'foo(2, bar)'>>> # Note that this won't work if either argument has parens or commas in it.

Concatenation of adjacent string literals

String literals (using possibly different quote conventions) appearing contiguously and onlyseparated by whitespace (including new lines), are allowed and are aggregated into a single longerstring.[8] Thus

title = "One Good Turn: " \'A Natural History of the Screwdriver and the Screw'

is equivalent to

title = "One Good Turn: A Natural History of the Screwdriver and the Screw"

Numbers

Numeric literals in Python are of the normal sort, e.g. 0, -1, 3.4, 3.5e-8.

Python has arbitrary-length integers and automatically increases the storage size as necessary. Priorto Python version 3, there were two kinds of integral numbers: traditional fixed size integers and"long" integers of arbitrary range. The conversion to "long" integers was performed automaticallywhen required, and thus the programmer usually didn't have to be aware of the two integral types.In newer language versions the fixed-size integers are completely gone.

Python supports normal floating point numbers, which are created when a dot is used in a literal(e.g. 1.1), when an integer and a floating point number are used in an expression, or as a result ofsome mathematical operations ("true division" via the / operator, or exponentiation with a negativeexponent).

Python also supports complex numbers natively. Complex numbers are indicated with the J or jsuffix, e.g. 3 + 4j.

Lists, tuples, sets, dictionaries

Python has syntactic support for the creation of container types.

Lists (class list) are mutable sequences of items of arbitrary types, and can be created either withthe special syntax

a_list = [1, 2, 3, "a dog"]

or using normal object creation

a_second_list = list()a_second_list.append(4)a_second_list.append(5)

Tuples (class tuple) are immutable sequences of items of arbitrary types. There is also a specialsyntax to create tuples

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 35

Page 37: Willkommen am Institut für Informatik — Institut für

a_tuple = 1, 2, 3, "four"

Although tuples are created by separating items with commas, the whole construct is usuallywrapped in parentheses to increase readability. An empty tuple is denoted by ().

Sets (class set) are mutable containers of items of arbitrary types, with no duplicate. The items arenot ordered, but sets support iteration over the items. A syntax for set creation appeared in Python2.7/3.0

some_set = {0, (), False}

In earlier Python versions, sets would be created by initializing the set class with a list argument.Python sets are very much like mathematical sets, and support operations like set intersection andunion.

Python also features a frozenset class for immutable sets.

Dictionaries (class dict) are mutable mappings tying keys and corresponding values. Python hasspecial syntax to create dictionaries ({key: value})

a_dictionary = {"key 1": "value 1", 2: 3, 4: []}

The dictionary syntax is similar to the set syntax, the difference is the presence of colons. Theempty literal {} results in an empty dictionary rather than an empty set, which is instead createdusing the non-literal constructor: set().

Operators

Arithmetic

Python includes the +, -, *, /, % (modulus), and ** (exponentiation) operators, with their usualmathematical precedence.

Traditionally, x / y performed integer division if both x and y were integers (returning the floor of thequotient), and returned a float if either was a float. However, because Python is a dynamically typedlanguage, it was not always possible to tell which operation was being performed, which often led tosubtle bugs. For example, with

def mean(seq):return sum(seq) / len(seq)

A call to mean([3.0, 4.0]) would return 3.5, but mean([3, 4]) would return 3. If this was not the intendedbehavior, it was necessary to use a workaround such as

def mean(seq):return float(sum(seq)) / len(seq)

To avoid this issue, a proposal (https://www.python.org/dev/peps/pep-0238/) was made to changethe behavior of the Python division operator. In Python 2.2, a new operator // was introduced forfloor division, both for integer and floating-point arguments. The / operator was changed so that thequotient of two integers returned a float, but for backwards compatibility, this behavior had to beexplicitly requested until Python 3.0.

Comparison operators

The basic comparison operators such as ==, <, >=, and so forth are used on all manner of values.

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 36

Page 38: Willkommen am Institut für Informatik — Institut für

Numbers, strings, sequences, and mappings can all be compared. Although disparate types (such asa str and an int) are defined to have a consistent relative ordering, this is considered a historicaldesign quirk and will no longer be allowed in Python 3.0.

Chained comparison expressions such as a < b < c have roughly the meaning that they have inmathematics, rather than the unusual meaning found in C and similar languages. The terms areevaluated and compared in order. The operation has short-circuit semantics, meaning thatevaluation is guaranteed to stop as soon as a verdict is clear: if a < b is false, c is never evaluated asthe expression cannot possibly be true anymore.

For expressions without side effects, a < b < c is equivalent to a < b and b < c. However, there is asubstantial difference when the expressions have side effects. a < f(x) < b will evaluate f(x) exactlyonce, whereas a < f(x) and f(x) < b will evaluate it twice if the value of a is less than f(x) and onceotherwise.

Logical operators

Python 2.2 and earlier does not have an explicit boolean type. In all versions of Python, booleanoperators treat zero values or empty values such as "", 0, None, 0.0, [], and {} as false, while ingeneral treating non-empty, non-zero values as true. In Python 2.2.1 the boolean constants True andFalse were added to the language (subclassed from 1 and 0). The binary comparison operators suchas == and > return either True or False.

The boolean operators and and or use minimal evaluation. For example, y == 0 or x/y > 100 will neverraise a divide-by-zero exception. These operators return the value of the last operand evaluated,rather than True or False. Thus the expression (4 and 5) evaluates to 5, and (4 or 5) evaluates to 4.

Functional programming

As mentioned above, another strength of Python is the availability of a functional programmingstyle. As may be expected, this makes working with lists and other collections much morestraightforward.

Comprehensions

One such construction is the list comprehension, which can be expressed with the following format:

L = [mapping-expression for element in source-list if filter-expression]

Using list comprehension to calculate the first five powers of two:

powers_of_two = [2**n for n in range(1, 6)]

The Quicksort algorithm can be expressed elegantly (albeit inefficiently) using list comprehensions:

def qsort(L):if L == []:

return []pivot = L[0]return (qsort([x for x in L[1:] if x < pivot]) +

[pivot] +qsort([x for x in L[1:] if x >= pivot]))

Python 2.7+[9] also supports set comprehensions[10] and dictionary comprehensions.[11]

First-class functions

In Python, functions are first-class objects that can be created and passed around dynamically.

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 37

Page 39: Willkommen am Institut für Informatik — Institut für

Python's limited support for anonymous functions is the lambda construct. Lambdas are limited tocontaining an expression rather than statements, although control flow can still be implemented lesselegantly within lambda by using short-circuiting,[12] and more idiomatically with conditionalexpressions.[13]

Closures

Python has had support for lexical closures since version 2.2. Here's an example:

def derivative(f, dx):"""Return a function that approximates the derivative of f

using an interval of dx, which should be appropriately small. """

def function(x):return (f(x + dx) - f(x)) / dx

return function

Python's syntax, though, sometimes leads programmers of other languages to think that closuresare not supported. Variable scope in Python is implicitly determined by the scope in which oneassigns a value to the variable, unless scope is explicitly declared with global or nonlocal.[14]

Note that the closure's binding of a name to some value is not mutable from within the function.Given:

>>> def foo(a, b):... print 'a: %r' % a... print 'b: %r' % b... def bar(c):... b = c... print 'b*: %r' % b...... bar(a)... print 'b: %r' % b

>>> foo(1,2)a: 1b: 2b*: 1b: 2

and you can see that b, as visible from the closure's scope, retains the value it had; the changedbinding of b inside the inner function did not propagate out. The way around this is to use a nonlocal bstatement in bar. In Python 2 (which lacks nonlocal), the usual workaround is to use mutable valueand change that value, not the binding. E.g., a list with one element.

Generators

Introduced in Python 2.2 as an optional feature and finalized in version 2.3, generators are Python'smechanism for lazy evaluation of a function that would otherwise return a space-prohibitive orcomputationally intensive list.

This is an example to lazily generate the prime numbers:

from itertools import count

def generate_primes(stop_at=0):primes = []for n in count(2):

if 0 < stop_at < n:return # raises the StopIteration exception

composite = Falsefor p in primes:

if not n % p:composite = Truebreak

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 38

Page 40: Willkommen am Institut für Informatik — Institut für

elif p ** 2 > n:break

if not composite:primes.append(n)yield n

To use this function simply call, e.g.:

for i in generate_primes(): # iterate over ALL primesif i > 100:

breakprint(i)

The definition of a generator appears identical to that of a function, except the keyword yield is usedin place of return. However, a generator is an object with persistent state, which can repeatedlyenter and leave the same scope. A generator call can then be used in place of a list, or otherstructure whose elements will be iterated over. Whenever the for loop in the example requires thenext item, the generator is called, and yields the next item.

Generators don't have to be infinite like the prime-number example above. When a generatorterminates, an internal exception is raised which indicates to any calling context that there are nomore values. A for loop or other iteration will then terminate.

Generator expressions

Introduced in Python 2.4, generator expressions are the lazy evaluation equivalent of listcomprehensions. Using the prime number generator provided in the above section, we might definea lazy, but not quite infinite collection.

from itertools import islice

primes_under_million = (i for i in generate_primes() if i < 1000000)two_thousandth_prime = islice(primes_under_million, 1999, 2000).next()

Most of the memory and time needed to generate this many primes will not be used until theneeded element is actually accessed. Unfortunately, you cannot perform simple indexing and slicingof generators, but must use the itertools modules or "roll your own" loops. In contrast, a listcomprehension is functionally equivalent, but is greedy in performing all the work:

primes_under_million = [i for i in generate_primes(2000000) if i < 1000000]two_thousandth_prime = primes_under_million[1999]

The list comprehension will immediately create a large list (with 78498 items, in the example, buttransiently creating a list of primes under two million), even if most elements are never accessed.The generator comprehension is more parsimonious.

Dictionary and set comprehensions

While lists and generators had comprehensions/expressions, in Python versions older than 2.7 theother Python built-in collection types (dicts and sets) had to be kludged in using lists or generators:

>>> dict((n, n*n) for n in range(5)){0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Python 2.7 and 3.0 unify all collection types by introducing dict and set comprehensions, similar tolist comprehensions:

>>> [ n*n for n in range(5) ] # regular list comprehension[0, 1, 4, 9, 16]>>>

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 39

Page 41: Willkommen am Institut für Informatik — Institut für

>>> { n*n for n in range(5) } # set comprehension{0, 1, 4, 9, 16}>>>>>> { n: n*n for n in range(5) } # dict comprehension{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Objects

Python supports most object oriented programming techniques. It allows polymorphism, not onlywithin a class hierarchy but also by duck typing. Any object can be used for any type, and it willwork so long as it has the proper methods and attributes. And everything in Python is an object,including classes, functions, numbers and modules. Python also has support for metaclasses, anadvanced tool for enhancing classes' functionality. Naturally, inheritance, including multipleinheritance, is supported. It has limited support for private variables using name mangling. See the"Classes" section of the tutorial (https://docs.python.org/2/tutorial/classes.html) for details. ManyPython users don't feel the need for private variables, though. The slogan "We're all responsibleusers here" is used to describe this attitude.[15] Some consider information hiding to be unpythonic,in that it suggests that the class in question contains unaesthetic or ill-planned internals. However,the strongest argument for name mangling is prevention of unpredictable breakage of programs:introducing a new public variable in a superclass can break subclasses if they don't use "private"variables.

From the tutorial: As is true for modules, classes in Python do not put an absolute barrier betweendefinition and user, but rather rely on the politeness of the user not to "break into the definition."

OOP doctrines such as the use of accessor methods to read data members are not enforced inPython. Just as Python offers functional-programming constructs but does not attempt to demandreferential transparency, it offers an object system but does not demand OOP behavior. Moreover, itis always possible to redefine the class using properties so that when a certain variable is set orretrieved in calling code, it really invokes a function call, so that spam.eggs = toast might really invokespam.set_eggs(toast). This nullifies the practical advantage of accessor functions, and it remains OOPbecause the property eggs becomes a legitimate part of the object's interface: it need not reflect animplementation detail.

In version 2.2 of Python, "new-style" classes were introduced. With new-style classes, objects andtypes were unified, allowing the subclassing of types. Even entirely new types can be defined,complete with custom behavior for infix operators. This allows for many radical things to be donesyntactically within Python. A new method resolution order (https://www.python.org/download/releases/2.3/mro/) for multiple inheritance was also adopted with Python 2.3. It is also possible torun custom code while accessing or setting attributes, though the details of those techniques haveevolved between Python versions.

With statements

The "with" statement handles resources.[16] One function is called when entering scope and anotherwhen leaving. This prevents forgetting to remove the resource and also handles more complicatedsituations such as exceptions.

Properties

Properties allow specially defined methods to be invoked on an object instance by using the samesyntax as used for attribute access. An example of a class defining some properties is:

class MyClass(object):def get_a(self):

return self._adef set_a(self, value):

self._a = value - 1a = property(get_a, set_a, doc="Off by one a")

# Python 2.6 styleclass MyClass(object):

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 40

Page 42: Willkommen am Institut für Informatik — Institut für

@propertydef a(self):

return [email protected] # makes the property writabledef a(self, value):

self._a = value - 1

Descriptors

A class that defines one or more of the special methods __get__(self,instance,owner),__set__(self,instance,value), __delete__(self,instance) can be used as a descriptor. Creating an instanceof a descriptor as a class member of a second class makes the instance a property of the secondclass.

Class and static methods

Python allows the creation of class methods and static method via the use of the @classmethod and@staticmethod decorators. The first argument to a class method is the class object instead of theself-reference to the instance. A static method has no special first argument. Neither the instance,nor the class object is passed to a static method.

Exceptions

Python supports (and extensively uses) exception handling as a means of testing for error conditionsand other "exceptional" events in a program. Indeed, it is even possible to trap the exception causedby a syntax error.

Python style calls for the use of exceptions whenever an error condition might arise. Rather thantesting for access to a file or resource before actually using it, it is conventional in Python to just goahead and try to use it, catching the exception if access is rejected.

Exceptions can also be used as a more general means of non-local transfer of control, even when anerror is not at issue. For instance, the Mailman mailing list software, written in Python, usesexceptions to jump out of deeply nested message-handling logic when a decision has been made toreject a message or hold it for moderator approval.

Exceptions are often used as an alternative to the if-block, especially in threaded situations. A

commonly invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than Permission,"[17] whichis attributed to Grace Hopper.[18][19] In this first code sample, there is an explicit check for theattribute (i.e., "asks permission"):

if hasattr(spam, 'eggs'):ham = spam.eggs

else:handle_error()

This second sample follows the EAFP paradigm:

try:ham = spam.eggs

except AttributeError:handle_error()

These two code samples have the same effect, although there will be performance differences.When spam has the attribute eggs, the EAFP sample will run faster. When spam does not have theattribute eggs (the "exceptional" case), the EAFP sample will run slower. The Python profiler(https://docs.python.org/3.6/library/profile.html) can be used in specific cases to determineperformance characteristics. If exceptional cases are rare, then the EAFP version will have superioraverage performance than the alternative. In addition, it avoids the whole class of time-of-check-to-time-of-use (TOCTTOU) vulnerabilities, other race conditions,[19][20] and is compatible with duck

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 41

Page 43: Willkommen am Institut für Informatik — Institut für

typing. A drawback of EAFP is that it can be used only with statements; an exception cannot becaught in a generator expression, list comprehension, or lambda function.

Comments and docstrings

Python has two ways to annotate Python code. One is by using comments to indicate what somepart of the code does. Single-line comments begin with the hash character ("#") and are terminatedby the end of line. Comments spanning more than one line are achieved by inserting a multi-linestring (with """ as the delimiter on each end) that is not used in assignment or otherwise evaluated,but sits in between other statements.

Commenting a piece of code:

def getline():return sys.stdin.readline() # Get one line and return it

Commenting a piece of code with multiple lines:

def getline():return sys.stdin.readline() """this function

gets one line and returns it"""

Docstrings (documentation strings), that is, strings that are located alone without assignment as thefirst indented line within a module, class, method or function, automatically set their contents as anattribute named __doc__, which is intended to store a human-readable description of the object'spurpose, behavior, and usage. The built-in help function generates its output based on __doc__attributes. Such strings can be delimited with " or ' for single line strings, or may span multiple linesif delimited with either """ or ''' which is Python's notation for specifying multi-line strings. However,the style guide for the language specifies that triple double quotes (""") are preferred for both singleand multi-line docstrings.

Single line docstring:

def getline():"""Get one line from stdin and return it."""return sys.stdin.readline()

Multi-line docstring:

def getline():"""Get one line

from stdin and return it."""

return sys.stdin.readline()

Docstrings can be as large as the programmer wants and contain line breaks. In contrast withcomments, docstrings are themselves Python objects and are part of the interpreted code thatPython runs. That means that a running program can retrieve its own docstrings and manipulatethat information. But the normal usage is to give other programmers information about how toinvoke the object being documented in the docstring.

There are tools available that can extract the docstrings to generate an API documentation from thecode. Docstring documentation can also be accessed from the interpreter with the help() function, orfrom the shell with the pydoc command pydoc.

The doctest standard module uses interactions copied from Python shell sessions into docstrings, tocreate tests.

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 42

Page 44: Willkommen am Institut für Informatik — Institut für

Function annotations

Function annotations are defined in PEP 3107 (https://www.python.org/dev/peps/pep-3107/). Theyallow attaching data to the arguments and return of a function. The behaviour of annotations is notdefined by the language, and is left to third party frameworks. For example, a library could bewritten to handle static typing:[21]

def haul(item: Haulable, *vargs: PackAnimal) -> Distance

Decorators

A decorator is any callable Python object that is used to modify a function, method or classdefinition. A decorator is passed the original object being defined and returns a modified object,which is then bound to the name in the definition. Python decorators were inspired in part by Javaannotations, and have a similar syntax; the decorator syntax is pure syntactic sugar, using @ as thekeyword:

@viking_chorusdef menu_item():

print("spam")

is equivalent to

def menu_item():print("spam")

menu_item = viking_chorus(menu_item)

Decorators are a form of metaprogramming; they enhance the action of the function or method theydecorate. For example, in the sample below, viking_chorus might cause menu_item to be run 8 times(see Spam sketch) for each time it is called:

def viking_chorus(myfunc):def inner_func(*args, **kwargs):

for i in range(8):myfunc(*args, **kwargs)

return inner_func

Canonical uses of function decorators are for creating class methods or static methods, addingfunction attributes, tracing, setting pre- and postconditions, and synchronisation,[22] but can beused for far more besides, including tail recursion elimination,[23] memoization and even improvingthe writing of decorators.[24]

Decorators can be chained by placing several on adjacent lines:

@invincible@favorite_color("Blue")def black_knight():

pass

is equivalent to

def black_knight():pass

black_knight = invincible(favorite_color("Blue")(black_knight))

or, using intermediate variables

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 43

Page 45: Willkommen am Institut für Informatik — Institut für

def black_knight():pass

blue_decorator = favorite_color("Blue")decorated_by_blue = blue_decorator(black_knight)black_knight = invincible(decorated_by_blue)

In the example above, the favorite_color decorator factory takes an argument. Decorator factoriesmust return a decorator, which is then called with the object to be decorated as its argument:

def favorite_color(color):def decorator(func):

def wrapper():print(color)func()

return wrapperreturn decorator

This would then decorate the black_knight function such that the color, "Blue", would be printed priorto the black_knight function running. Closure ensures that the color argument is accessible to theinnermost wrapper function even when it is returned and goes out of scope, which is what allowsdecorators to work.

In Python prior to version 2.6, decorators apply to functions and methods, but not to classes.Decorating a (dummy) __new__ method can modify a class, however.[25] Class decorators are

supported[26] starting with Python 2.6.

Despite the name, Python decorators are not an implementation of the decorator pattern. Thedecorator pattern is a design pattern used in statically typed object-oriented programminglanguages to allow functionality to be added to objects at run time; Python decorators addfunctionality to functions and methods at definition time, and thus are a higher-level construct thandecorator-pattern classes. The decorator pattern itself is trivially implementable in Python, becausethe language is duck typed, and so is not usually considered as such.

Easter eggs

Users of curly bracket programming languages, such as C or Java, sometimes expect or wish Pythonto follow a block-delimiter convention. Brace-delimited block syntax has been repeatedly requested,and consistently rejected by core developers. The Python interpreter contains an easter egg thatsummarizes its developers' feelings on this issue. The code from __future__ import braces raises theexception SyntaxError: not a chance. The __future__ module is normally used to provide features fromfuture versions of Python.

Another hidden message, The Zen of Python (a summary of Python philosophy), is displayed whentrying to import this.

The message Hello world! is printed when the import statement import __hello__ is used. In Python 2.7,instead of Hello world! it prints Hello world....

An antigravity module was added to Python 2.7 and 3.0. Importing it opens a web browser to an xkcdcomic that portrays a humorous fictional use for such a module, intended to demonstrate the easewith which Python modules enable additional functionality.[27]

References

"Readability counts." - PEP 20 - The Zen of Python (https://www.python.org/dev/peps/pep-0020/)1. "PEP 20 - The Zen of Python" (https://www.python.org/dev/peps/pep-0020/). Python SoftwareFoundation. 2004-08-23. Retrieved 2008-11-24.

2.

"2. Lexical analysis" (https://docs.python.org/dev/reference/lexical_analysis.html#keywords). Pythonv3.4.0a1 documentation. Docs.python.org. Retrieved 2013-08-16.

3.

"2. Lexical analysis" (https://docs.python.org/reference/lexical_analysis.html#keywords). Python v2.7.5documentation. Docs.python.org. Retrieved 2013-08-16.

4.

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 44

Page 46: Willkommen am Institut für Informatik — Institut für

"New Keywords" (https://docs.python.org/3/whatsnew/3.5.html#new-keywords). Python v3.5documentation. Docs.python.org. Retrieved 2016-06-01.

5.

"PEP 498 - Literal String Interpolation" (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498). What’s New In Python 3.6. 2016-12-23. Retrieved 2017-03-29.

6.

"2. Lexical analysis" (https://docs.python.org/reference/lexical_analysis.html#string-literals). Pythonv2.7.5 documentation. Docs.python.org. Retrieved 2013-08-16.

7.

"2. Lexical analysis" (https://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation). Python v2.7.5 documentation. Docs.python.org. Retrieved 2013-08-16.

8.

https://www.python.org/download/releases/2.7/9. https://docs.python.org/2/tutorial/datastructures.html#sets10. https://docs.python.org/2/tutorial/datastructures.html#dictionaries11. David Mertz. "Functional Programming in Python" (http://gnosis.cx/publish/programming/charming_python_13.html). IBM developerWorks.

12.

"PEP 308 -- Conditional Expressions" (https://www.python.org/dev/peps/pep-0308/).13. The nonlocal keyword was adopted by PEP 3104 (https://www.python.org/dev/peps/pep-3104/)14. "Python Style Guide" (http://docs.python-guide.org/en/latest/writing/style/#we-are-all-responsible-users). docs.python-guide.org. Retrieved 2015-03-08.

15.

https://www.python.org/dev/peps/pep-0343/16. EAFP (https://docs.python.org/glossary.html#term-eafp), Python Glossary17. Hamblen, Diane. "Only the Limits of Our Imagination: An exclusive interview with RADM Grace M.Hopper" (https://web.archive.org/web/20090114165606/http://www.chips.navy.mil/archives/86_jul/interview.html). Department of the Navy Information Technology Magazine. Archived from the original(http://www.chips.navy.mil/archives/86_jul/interview.html) on January 14, 2009. Retrieved 2007-01-31.

18.

Python in a nutshell, Alex Martelli, p. 134 (https://books.google.com/books?id=JnR9hQA3SncC&pg=PA134)

19.

Alex Martelli (19 May 2003). "EAFP v. LBYL" (http://code.activestate.com/lists/python-list/337643/).python-list mailing list.

20.

https://www.python.org/dev/peps/pep-3107/21. "Python 2.4 Decorators: Reducing code duplication and consolidating knowledge" (http://www.ddj.com/184406073#l11). Dr. Dobb's. 2005-05-01. Retrieved 2007-02-08.

22.

"New Tail Recursion Decorator" (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691).ASPN: Python Cookbook. 2006-11-14. Retrieved 2007-02-08.

23.

"The decorator module" (http://www.phyast.pitt.edu/~micheles/python/documentation.html). Retrieved2007-02-08.

24.

David Mertz (2006-12-29). "Charming Python: Decorators make magic easy; A look at the newestPython facility for metaprogramming" (http://www-128.ibm.com/developerworks/linux/library/l-cpdecor.html). IBM developerWorks. Retrieved 2007-02-08.

25.

"PEP 3129 - Class Decorators" (https://docs.python.org/whatsnew/2.6.html#pep-3129-class-decorators).What's New in Python 2.6. 2010-08-11. Retrieved 2011-01-23.

26.

The referenced comic strip is xkcd #353 (http://xkcd.com/353/); the module was added to the Pythontrunk (https://github.com/python/cpython/blob/206e3074d34aeb5a4d0c1e24d970b6569f7ad702/Lib/antigravity.py) for the 3.0 release. In Python 3.0 there has been added a geohash function(https://github.com/python/cpython/commit/b1614a7b6705f939b29df4045e591fcf53a8611b), whichcalculates a hash as described in xkcd #426 (http://xkcd.com/426).

27.

External links

Python tutorial (https://docs.python.org/3/tutorial/) written by the author of Python, Guido vanRossum.

Retrieved from "https://en.wikipedia.org/w/index.php?title=Python_syntax_and_semantics&oldid=788682114"

Categories: Programming language syntax Python (programming language)

This page was last edited on 2 July 2017, at 21:30.Text is available under the Creative Commons Attribution-ShareAlike License; additional termsmay apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is aregistered trademark of the Wikimedia Foundation, Inc., a non-profit organization.

Python syntax and semantics - Wikipedia 7/19/17, 7:17 PM

https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Einstieg in Python – Version vom 19. Juli 2017 Seite 45

Page 47: Willkommen am Institut für Informatik — Institut für

7/14/2017 1. Whetting Your Appetite — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/appetite.html 1/2

1. Whetting Your AppetiteIf you do much work on computers, eventually you find that there’s some task you’d like toautomate. For example, you may wish to perform a search-and-replace over a large number of textfiles, or rename and rearrange a bunch of photo files in a complicated way. Perhaps you’d like towrite a small custom database, or a specialized GUI application, or a simple game.

If you’re a professional software developer, you may have to work with several C/C++/Javalibraries but find the usual write/compile/test/re-compile cycle is too slow. Perhaps you’re writing atest suite for such a library and find writing the testing code a tedious task. Or maybe you’ve writtena program that could use an extension language, and you don’t want to design and implement awhole new language for your application.

Python is just the language for you.

You could write a Unix shell script or Windows batch files for some of these tasks, but shell scriptsare best at moving around files and changing text data, not well-suited for GUI applications orgames. You could write a C/C++/Java program, but it can take a lot of development time to geteven a first-draft program. Python is simpler to use, available on Windows, Mac OS X, and Unixoperating systems, and will help you get the job done more quickly.

Python is simple to use, but it is a real programming language, offering much more structure andsupport for large programs than shell scripts or batch files can offer. On the other hand, Python alsooffers much more error checking than C, and, being a very-high-level language, it has high-leveldata types built in, such as flexible arrays and dictionaries. Because of its more general data typesPython is applicable to a much larger problem domain than Awk or even Perl, yet many things areat least as easy in Python as in those languages.

Python allows you to split your program into modules that can be reused in other Python programs.It comes with a large collection of standard modules that you can use as the basis of yourprograms — or as examples to start learning to program in Python. Some of these modulesprovide things like file I/O, system calls, sockets, and even interfaces to graphical user interfacetoolkits like Tk.

Python is an interpreted language, which can save you considerable time during programdevelopment because no compilation and linking is necessary. The interpreter can be usedinteractively, which makes it easy to experiment with features of the language, to write throw-awayprograms, or to test functions during bottom-up program development. It is also a handy deskcalculator.

Python enables programs to be written compactly and readably. Programs written in Python aretypically much shorter than equivalent C, C++, or Java programs, for several reasons:

the high-level data types allow you to express complex operations in a single statement;statement grouping is done by indentation instead of beginning and ending brackets;no variable or argument declarations are necessary.

Python is extensible: if you know how to program in C it is easy to add a new built-in function ormodule to the interpreter, either to perform critical operations at maximum speed, or to link Pythonprograms to libraries that may only be available in binary form (such as a vendor-specific graphicslibrary). Once you are really hooked, you can link the Python interpreter into an application written inC and use it as an extension or command language for that application.

Einstieg in Python – Version vom 19. Juli 2017 Seite 46

Page 48: Willkommen am Institut für Informatik — Institut für

7/14/2017 1. Whetting Your Appetite — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/appetite.html 2/2

By the way, the language is named after the BBC show “Monty Python’s Flying Circus” and hasnothing to do with reptiles. Making references to Monty Python skits in documentation is not onlyallowed, it is encouraged!

Now that you are all excited about Python, you’ll want to examine it in some more detail. Since thebest way to learn a language is to use it, the tutorial invites you to play with the Python interpreteras you read.

In the next chapter, the mechanics of using the interpreter are explained. This is rather mundaneinformation, but essential for trying out the examples shown later.

The rest of the tutorial introduces various features of the Python language and system throughexamples, beginning with simple expressions, statements and data types, through functions andmodules, and finally touching upon advanced concepts like exceptions and user-defined classes.

Einstieg in Python – Version vom 19. Juli 2017 Seite 47

Page 49: Willkommen am Institut für Informatik — Institut für

7/14/2017 2. Using the Python Interpreter — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/interpreter.html 1/3

2. Using the Python Interpreter

2.1. Invoking the Interpreter

The Python interpreter is usually installed as /usr/local/bin/python on those machines where it isavailable; putting /usr/local/bin in your Unix shell’s search path makes it possible to start it bytyping the command

to the shell. Since the choice of the directory where the interpreter lives is an installation option,other places are possible; check with your local Python guru or system administrator. (E.g.,/usr/local/python is a popular alternative location.)

On Windows machines, the Python installation is usually placed in C:\Python27, though you canchange this when you’re running the installer. To add this directory to your path, you can type thefollowing command into the command prompt in a DOS box:

Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary promptcauses the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreterby typing the following command: quit().

The interpreter’s line-editing features usually aren’t very sophisticated. On Unix, whoever installedthe interpreter may have enabled support for the GNU readline library, which adds more elaborateinteractive editing and history features. Perhaps the quickest check to see whether command lineediting is supported is typing Control-P to the first Python prompt you get. If it beeps, you havecommand line editing; see Appendix Interactive Input Editing and History Substitution for anintroduction to the keys. If nothing appears to happen, or if ^P is echoed, command line editing isn’tavailable; you’ll only be able to use backspace to remove characters from the current line.

The interpreter operates somewhat like the Unix shell: when called with standard input connectedto a tty device, it reads and executes commands interactively; when called with a file nameargument or with a file as standard input, it reads and executes a script from that file.

A second way of starting the interpreter is python -c command [arg] ..., which executes thestatement(s) in command, analogous to the shell’s -c option. Since Python statements oftencontain spaces or other characters that are special to the shell, it is usually advised to quotecommand in its entirety with single quotes.

Some Python modules are also useful as scripts. These can be invoked using python -m module[arg] ..., which executes the source file for module as if you had spelled out its full name on thecommand line.

When a script file is used, it is sometimes useful to be able to run the script and enter interactivemode afterwards. This can be done by passing -i before the script.

All command-line options are described in Command line and environment.

python

set path=%path%;C:\python27

Einstieg in Python – Version vom 19. Juli 2017 Seite 48

Page 50: Willkommen am Institut für Informatik — Institut für

7/14/2017 2. Using the Python Interpreter — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/interpreter.html 2/3

2.1.1. Argument Passing

When known to the interpreter, the script name and additional arguments thereafter are turned intoa list of strings and assigned to the argv variable in the sys module. You can access this list byexecuting import sys. The length of the list is at least one; when no script and no arguments aregiven, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standardinput), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -mmodule is used, sys.argv[0] is set to the full name of the located module. Options found after -ccommand or -m module are not consumed by the Python interpreter’s option processing but left insys.argv for the command or module to handle.

2.1.2. Interactive Mode

When commands are read from a tty, the interpreter is said to be in interactive mode. In this modeit prompts for the next command with the primary prompt, usually three greater-than signs (>>>); forcontinuation lines it prompts with the secondary prompt, by default three dots (...). The interpreterprints a welcome message stating its version number and a copyright notice before printing thefirst prompt:

pythonPython 2.7 (#1, Feb 28 2010, 00:02:06)Type "help", "copyright", "credits" or "license" for more information.>>>

Continuation lines are needed when entering a multi-line construct. As an example, take a look atthis if statement:

For more on interactive mode, see Interactive Mode.

2.2. The Interpreter and Its Environment

2.2.1. Source Code Encoding

By default, Python source files are treated as encoded in UTF-8. In that encoding, characters ofmost languages in the world can be used simultaneously in string literals, identifiers and comments— although the standard library only uses ASCII characters for identifiers, a convention that anyportable code should follow. To display all these characters properly, your editor must recognizethat the file is UTF-8, and it must use a font that supports all the characters in the file.

To declare an encoding other than the default one, a special comment line should be added as thefirst line of the file. The syntax is as follows:

where encoding is one of the valid codecs supported by Python.

>>> the_world_is_flat = 1>>> if the_world_is_flat:... print "Be careful not to fall off!"...Be careful not to fall off!

>>>

# -*- coding: encoding -*-

Einstieg in Python – Version vom 19. Juli 2017 Seite 49

Page 51: Willkommen am Institut für Informatik — Institut für

7/14/2017 2. Using the Python Interpreter — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/interpreter.html 3/3

For example, to declare that Windows-1252 encoding is to be used, the first line of your sourcecode file should be:

One exception to the first line rule is when the source code starts with a UNIX “shebang” line. In thiscase, the encoding declaration should be added as the second line of the file. For example:

# -*- coding: cp-1252 -*-

#!/usr/bin/env python# -*- coding: cp-1252 -*-

Einstieg in Python – Version vom 19. Juli 2017 Seite 50

Page 52: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 1/10

3. An Informal Introduction to PythonIn the following examples, input and output are distinguished by the presence or absence ofprompts (>>> and ...): to repeat the example, you must type everything after the prompt, when theprompt appears; lines that do not begin with a prompt are output from the interpreter. Note that asecondary prompt on a line by itself in an example means you must type a blank line; this is used toend a multi-line command.

Many of the examples in this manual, even those entered at the interactive prompt, includecomments. Comments in Python start with the hash character, #, and extend to the end of thephysical line. A comment may appear at the start of a line or following whitespace or code, but notwithin a string literal. A hash character within a string literal is just a hash character. Sincecomments are to clarify code and are not interpreted by Python, they may be omitted when typingin examples.

Some examples:

3.1. Using Python as a Calculator

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>.(It shouldn’t take long.)

3.1.1. Numbers

The interpreter acts as a simple calculator: you can type an expression at it and it will write thevalue. Expression syntax is straightforward: the operators +, -, * and / work just like in most otherlanguages (for example, Pascal or C); parentheses (()) can be used for grouping. For example:

The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) havetype float. We will see more about numeric types later in the tutorial.

The return type of a division (/) operation depends on its operands. If both operands are of typeint, floor division is performed and an int is returned. If either operand is a float, classic divisionis performed and a float is returned. The // operator is also provided for doing floor division nomatter what the operands are. The remainder can be calculated with the % operator:

# this is the first commentspam = 1 # and this is the second comment # ... and now a third!text = "# This is not a comment because it's inside quotes."

>>> 2 + 24>>> 50 - 5*620>>> (50 - 5.0*6) / 45.0>>> 8 / 5.01.6

>>>

>>> 17 / 3 # int / int -> int5>>> 17 / 3.0 # int / float -> float

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 51

Page 53: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 2/10

With Python, it is possible to use the ** operator to calculate powers [1]:

The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed beforethe next interactive prompt:

If a variable is not “defined” (assigned a value), trying to use it will give you an error:

There is full support for floating point; operators with mixed type operands convert the integeroperand to floating point:

In interactive mode, the last printed expression is assigned to the variable _. This means that whenyou are using Python as a desk calculator, it is somewhat easier to continue calculations, forexample:

This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — youwould create an independent local variable with the same name masking the built-in variable withits magic behavior.

In addition to int and float, Python supports other types of numbers, such as Decimal andFraction. Python also has built-in support for complex numbers, and uses the j or J suffix toindicate the imaginary part (e.g. 3+5j).

5.666666666666667>>> 17 // 3.0 # explicit floor division discards the fractional part5.0>>> 17 % 3 # the % operator returns the remainder of the division2>>> 5 * 3 + 2 # result * divisor + remainder17

>>> 5 ** 2 # 5 squared25>>> 2 ** 7 # 2 to the power of 7128

>>>

>>> width = 20>>> height = 5 * 9>>> width * height900

>>>

>>> n # try to access an undefined variableTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'n' is not defined

>>>

>>> 3 * 3.75 / 1.57.5>>> 7.0 / 23.5

>>>

>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax12.5625>>> price + _113.0625>>> round(_, 2)113.06

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 52

Page 54: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 3/10

3.1.2. Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways.They can be enclosed in single quotes ('...') or double quotes ("...") with the same result [2]. \can be used to escape quotes:

In the interactive interpreter, the output string is enclosed in quotes and special characters areescaped with backslashes. While this might sometimes look different from the input (the enclosingquotes could change), the two strings are equivalent. The string is enclosed in double quotes if thestring contains a single quote and no double quotes, otherwise it is enclosed in single quotes. Theprint statement produces a more readable output, by omitting the enclosing quotes and by printingescaped and special characters:

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use rawstrings by adding an r before the first quote:

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. Endof lines are automatically included in the string, but it’s possible to prevent this by adding a \ at theend of the line. The following example:

produces the following output (note that the initial newline is not included):

>>> 'spam eggs' # single quotes'spam eggs'>>> 'doesn\'t' # use \' to escape the single quote..."doesn't">>> "doesn't" # ...or use double quotes instead"doesn't">>> '"Yes," he said.''"Yes," he said.'>>> "\"Yes,\" he said."'"Yes," he said.'>>> '"Isn\'t," she said.''"Isn\'t," she said.'

>>>

>>> '"Isn\'t," she said.''"Isn\'t," she said.'>>> print '"Isn\'t," she said.'"Isn't," she said.>>> s = 'First line.\nSecond line.' # \n means newline>>> s # without print, \n is included in the output'First line.\nSecond line.'>>> print s # with print, \n produces a new lineFirst line.Second line.

>>>

>>> print 'C:\some\name' # here \n means newline!C:\someame>>> print r'C:\some\name' # note the r before the quoteC:\some\name

>>>

print """\Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to"""

Einstieg in Python – Version vom 19. Juli 2017 Seite 53

Page 55: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 4/10

Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to

Strings can be concatenated (glued together) with the + operator, and repeated with *:

Two or more string literals (i.e. the ones enclosed between quotes) next to each other areautomatically concatenated.

This only works with two literals though, not with variables or expressions:

If you want to concatenate variables or a variable and a literal, use +:

This feature is particularly useful when you want to break long strings:

Strings can be indexed (subscripted), with the first character having index 0. There is no separatecharacter type; a character is simply a string of size one:

Indices may also be negative numbers, to start counting from the right:

Note that since -0 is the same as 0, negative indices start from -1.

>>> # 3 times 'un', followed by 'ium'>>> 3 * 'un' + 'ium''unununium'

>>>

>>> 'Py' 'thon''Python'

>>>

>>> prefix = 'Py'>>> prefix 'thon' # can't concatenate a variable and a string literal ...SyntaxError: invalid syntax>>> ('un' * 3) 'ium' ...SyntaxError: invalid syntax

>>>

>>> prefix + 'thon''Python'

>>>

>>> text = ('Put several strings within parentheses '... 'to have them joined together.')>>> text'Put several strings within parentheses to have them joined together.'

>>>

>>> word = 'Python'>>> word[0] # character in position 0'P'>>> word[5] # character in position 5'n'

>>>

>>> word[-1] # last character'n'>>> word[-2] # second-last character'o'>>> word[-6]'P'

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 54

Page 56: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 5/10

In addition to indexing, slicing is also supported. While indexing is used to obtain individualcharacters, slicing allows you to obtain a substring:

Note how the start is always included, and the end always excluded. This makes sure that s[:i] +s[i:] is always equal to s:

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second indexdefaults to the size of the string being sliced.

One way to remember how slices work is to think of the indices as pointing between characters,with the left edge of the first character numbered 0. Then the right edge of the last character of astring of n characters has index n, for example:

The first row of numbers gives the position of the indices 0...6 in the string; the second row givesthe corresponding negative indices. The slice from i to j consists of all characters between theedges labeled i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are withinbounds. For example, the length of word[1:3] is 2.

Attempting to use an index that is too large will result in an error:

However, out of range slice indexes are handled gracefully when used for slicing:

>>> word[0:2] # characters from position 0 (included) to 2 (excluded)'Py'>>> word[2:5] # characters from position 2 (included) to 5 (excluded)'tho'

>>>

>>> word[:2] + word[2:]'Python'>>> word[:4] + word[4:]'Python'

>>>

>>> word[:2] # character from the beginning to position 2 (excluded)'Py'>>> word[4:] # characters from position 4 (included) to the end'on'>>> word[-2:] # characters from the second-last (included) to the end'on'

>>>

+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6-6 -5 -4 -3 -2 -1

>>> word[42] # the word only has 6 charactersTraceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: string index out of range

>>>

>>> word[4:42]'on'>>> word[42:]''

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 55

Page 57: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 6/10

Python strings cannot be changed — they are immutable. Therefore, assigning to an indexedposition in the string results in an error:

If you need a different string, you should create a new one:

The built-in function len() returns the length of a string:

See also:

Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrangeStrings, and the Unicode strings described in the next section, are examples of sequencetypes, and support the common operations supported by such types.

String MethodsBoth strings and Unicode strings support a large number of methods for basictransformations and searching.

Format String SyntaxInformation about string formatting with str.format().

String Formatting OperationsThe old formatting operations invoked when strings and Unicode strings are the left operandof the % operator are described in more detail here.

3.1.3. Unicode Strings

Starting with Python 2.0 a new data type for storing text data is available to the programmer: theUnicode object. It can be used to store and manipulate Unicode data (see http://www.unicode.org/)and integrates well with the existing string objects, providing auto-conversions where necessary.

Unicode has the advantage of providing one ordinal for every character in every script used inmodern and ancient texts. Previously, there were only 256 possible ordinals for script characters.Texts were typically bound to a code page which mapped the ordinals to script characters. Thislead to very much confusion especially with respect to internationalization (usually written as i18n— 'i' + 18 characters + 'n') of software. Unicode solves these problems by defining one codepage for all scripts.

Creating Unicode strings in Python is just as simple as creating normal strings:

>>> word[0] = 'J' ...TypeError: 'str' object does not support item assignment>>> word[2:] = 'py' ...TypeError: 'str' object does not support item assignment

>>>

>>> 'J' + word[1:]'Jython'>>> word[:2] + 'py''Pypy'

>>>

>>> s = 'supercalifragilisticexpialidocious'>>> len(s)34

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 56

Page 58: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 7/10

The small 'u' in front of the quote indicates that a Unicode string is supposed to be created. If youwant to include special characters in the string, you can do so by using the Python Unicode-Escape encoding. The following example shows how:

The escape sequence \u0020 indicates to insert the Unicode character with the ordinal value0x0020 (the space character) at the given position.

Other characters are interpreted by using their respective ordinal values directly as Unicodeordinals. If you have literal strings in the standard Latin-1 encoding that is used in many Westerncountries, you will find it convenient that the lower 256 characters of Unicode are the same as the256 characters of Latin-1.

For experts, there is also a raw mode just like the one for normal strings. You have to prefix theopening quote with ‘ur’ to have Python use the Raw-Unicode-Escape encoding. It will only applythe above \uXXXX conversion if there is an uneven number of backslashes in front of the small ‘u’.

The raw mode is most useful when you have to enter lots of backslashes, as can be necessary inregular expressions.

Apart from these standard encodings, Python provides a whole set of other ways of creatingUnicode strings on the basis of a known encoding.

The built-in function unicode() provides access to all registered Unicode codecs (COders andDECoders). Some of the more well known encodings which these codecs can convert are Latin-1,ASCII, UTF-8, and UTF-16. The latter two are variable-length encodings that store each Unicodecharacter in one or more bytes. The default encoding is normally set to ASCII, which passesthrough characters in the range 0 to 127 and rejects any other characters with an error. When aUnicode string is printed, written to a file, or converted with str(), conversion takes place using thisdefault encoding.

To convert a Unicode string into an 8-bit string using a specific encoding, Unicode objects providean encode() method that takes one argument, the name of the encoding. Lowercase names forencodings are preferred.

>>> u'Hello World !'u'Hello World !'

>>>

>>> u'Hello\u0020World !'u'Hello World !'

>>>

>>> ur'Hello\u0020World !'u'Hello World !'>>> ur'Hello\\u0020World !'u'Hello\\\\u0020World !'

>>>

>>> u"abc"u'abc'>>> str(u"abc")'abc'>>> u"äöü"u'\xe4\xf6\xfc'>>> str(u"äöü")Traceback (most recent call last): File "<stdin>", line 1, in ?UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 57

Page 59: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 8/10

If you have data in a specific encoding and want to produce a corresponding Unicode string fromit, you can use the unicode() function with the encoding name as the second argument.

3.1.4. Lists

Python knows a number of compound data types, used to group together other values. The mostversatile is the list, which can be written as a list of comma-separated values (items) betweensquare brackets. Lists might contain items of different types, but usually the items all have thesame type.

Like strings (and all other built-in sequence type), lists can be indexed and sliced:

All slice operations return a new list containing the requested elements. This means that thefollowing slice returns a new (shallow) copy of the list:

Lists also supports operations like concatenation:

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change theircontent:

You can also add new items at the end of the list, by using the append() method (we will see moreabout methods later):

>>> u"äöü".encode('utf-8')'\xc3\xa4\xc3\xb6\xc3\xbc'

>>>

>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')u'\xe4\xf6\xfc'

>>>

>>> squares = [1, 4, 9, 16, 25]>>> squares[1, 4, 9, 16, 25]

>>>

>>> squares[0] # indexing returns the item1>>> squares[-1]25>>> squares[-3:] # slicing returns a new list[9, 16, 25]

>>>

>>> squares[:][1, 4, 9, 16, 25]

>>>

>>> squares + [36, 49, 64, 81, 100][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>>

>>> cubes = [1, 8, 27, 65, 125] # something's wrong here>>> 4 ** 3 # the cube of 4 is 64, not 65!64>>> cubes[3] = 64 # replace the wrong value>>> cubes[1, 8, 27, 64, 125]

>>>

>>> cubes.append(216) # add the cube of 6>>> cubes.append(7 ** 3) # and the cube of 7

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 58

Page 60: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 9/10

Assignment to slices is also possible, and this can even change the size of the list or clear itentirely:

The built-in function len() also applies to lists:

It is possible to nest lists (create lists containing other lists), for example:

3.2. First Steps Towards Programming

Of course, we can use Python for more complicated tasks than adding two and two together. Forinstance, we can write an initial sub-sequence of the Fibonacci series as follows:

This example introduces several new features.

>>> cubes[1, 8, 27, 64, 125, 216, 343]

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> letters['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> # replace some values>>> letters[2:5] = ['C', 'D', 'E']>>> letters['a', 'b', 'C', 'D', 'E', 'f', 'g']>>> # now remove them>>> letters[2:5] = []>>> letters['a', 'b', 'f', 'g']>>> # clear the list by replacing all the elements with an empty list>>> letters[:] = []>>> letters[]

>>>

>>> letters = ['a', 'b', 'c', 'd']>>> len(letters)4

>>>

>>> a = ['a', 'b', 'c']>>> n = [1, 2, 3]>>> x = [a, n]>>> x[['a', 'b', 'c'], [1, 2, 3]]>>> x[0]['a', 'b', 'c']>>> x[0][1]'b'

>>>

>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1>>> while b < 10:... print b... a, b = b, a+b...112358

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 59

Page 61: Willkommen am Institut für Informatik — Institut für

7/14/2017 3. An Informal Introduction to Python — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/introduction.html 10/10

The first line contains a multiple assignment: the variables a and b simultaneously get thenew values 0 and 1. On the last line this is used again, demonstrating that the expressions onthe right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

The while loop executes as long as the condition (here: b < 10) remains true. In Python, likein C, any non-zero integer value is true; zero is false. The condition may also be a string orlist value, in fact any sequence; anything with a non-zero length is true, empty sequences arefalse. The test used in the example is a simple comparison. The standard comparisonoperators are written the same as in C: < (less than), > (greater than), == (equal to), <= (lessthan or equal to), >= (greater than or equal to) and != (not equal to).

The body of the loop is indented: indentation is Python’s way of grouping statements. At theinteractive prompt, you have to type a tab or space(s) for each indented line. In practice youwill prepare more complicated input for Python with a text editor; all decent text editors havean auto-indent facility. When a compound statement is entered interactively, it must befollowed by a blank line to indicate completion (since the parser cannot guess when you havetyped the last line). Note that each line within a basic block must be indented by the sameamount.

The print statement writes the value of the expression(s) it is given. It differs from just writingthe expression you want to write (as we did earlier in the calculator examples) in the way ithandles multiple expressions and strings. Strings are printed without quotes, and a space isinserted between items, so you can format things nicely, like this:

A trailing comma avoids the newline after the output:

Note that the interpreter inserts a newline before it prints the next prompt if the last line wasnot completed.

Footnotes

[1] Since ** has higher precedence than -, -3**2 will be interpreted as -(3**2) and thus result in-9. To avoid this and get 9, you can use (-3)**2.

[2] Unlike other languages, special characters such as \n have the same meaning with bothsingle ('...') and double ("...") quotes. The only difference between the two is that withinsingle quotes you don’t need to escape " (but you have to escape \') and vice versa.

>>> i = 256*256>>> print 'The value of i is', iThe value of i is 65536

>>>

>>> a, b = 0, 1>>> while b < 1000:... print b,... a, b = b, a+b...1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 60

Page 62: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 1/10

4. More Control Flow ToolsBesides the while statement just introduced, Python knows the usual control flow statements knownfrom other languages, with some twists.

4.1. if Statements

Perhaps the most well-known statement type is the if statement. For example:

There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for‘else if’, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is asubstitute for the switch or case statements found in other languages.

4.2. for Statements

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather thanalways iterating over an arithmetic progression of numbers (like in Pascal), or giving the user theability to define both the iteration step and halting condition (as C), Python’s for statement iteratesover the items of any sequence (a list or a string), in the order that they appear in the sequence.For example (no pun intended):

If you need to modify the sequence you are iterating over while inside the loop (for example toduplicate selected items), it is recommended that you first make a copy. Iterating over a sequencedoes not implicitly make a copy. The slice notation makes this especially convenient:

>>> x = int(raw_input("Please enter an integer: "))Please enter an integer: 42>>> if x < 0:... x = 0... print 'Negative changed to zero'... elif x == 0:... print 'Zero'... elif x == 1:... print 'Single'... else:... print 'More'...More

>>>

>>> # Measure some strings:... words = ['cat', 'window', 'defenestrate']>>> for w in words:... print w, len(w)...cat 3window 6defenestrate 12

>>>

>>> for w in words[:]: # Loop over a slice copy of the entire list.... if len(w) > 6:... words.insert(0, w)...>>> words['defenestrate', 'cat', 'window', 'defenestrate']

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 61

Page 63: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 2/10

4.3. The range() Function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. Itgenerates lists containing arithmetic progressions:

The given end point is never part of the generated list; range(10) generates a list of 10 values, thelegal indices for items of a sequence of length 10. It is possible to let the range start at anothernumber, or to specify a different increment (even negative; sometimes this is called the ‘step’):

To iterate over the indices of a sequence, you can combine range() and len() as follows:

In most such cases, however, it is convenient to use the enumerate() function, see LoopingTechniques.

4.4. break and continue Statements, and else Clauses onLoops

The break statement, like in C, breaks out of the innermost enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates throughexhaustion of the list (with for) or when the condition becomes false (with while), but not when theloop is terminated by a break statement. This is exemplified by the following loop, which searchesfor prime numbers:

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

>>>

>>> range(5, 10)[5, 6, 7, 8, 9]>>> range(0, 10, 3)[0, 3, 6, 9]>>> range(-10, -100, -30)[-10, -40, -70]

>>>

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']>>> for i in range(len(a)):... print i, a[i]...0 Mary1 had2 a3 little4 lamb

>>>

>>> for n in range(2, 10):... for x in range(2, n):... if n % x == 0:... print n, 'equals', x, '*', n/x... break... else:... # loop fell through without finding a factor... print n, 'is a prime number'...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 62

Page 64: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 3/10

(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the ifstatement.)

When used with a loop, the else clause has more in common with the else clause of a trystatement than it does that of if statements: a try statement’s else clause runs when no exceptionoccurs, and a loop’s else clause runs when no break occurs. For more on the try statement andexceptions, see Handling Exceptions.

The continue statement, also borrowed from C, continues with the next iteration of the loop:

4.5. pass Statements

The pass statement does nothing. It can be used when a statement is required syntactically but theprogram requires no action. For example:

This is commonly used for creating minimal classes:

Another place pass can be used is as a place-holder for a function or conditional body when youare working on new code, allowing you to keep thinking at a more abstract level. The pass is silentlyignored:

4.6. Defining Functions

We can create a function that writes the Fibonacci series to an arbitrary boundary:

6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3

>>> for num in range(2, 10):... if num % 2 == 0:... print "Found an even number", num... continue... print "Found a number", numFound an even number 2Found a number 3Found an even number 4Found a number 5Found an even number 6Found a number 7Found an even number 8Found a number 9

>>>

>>> while True:... pass # Busy-wait for keyboard interrupt (Ctrl+C)...

>>>

>>> class MyEmptyClass:... pass...

>>>

>>> def initlog(*args):... pass # Remember to implement this!...

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 63

Page 65: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 4/10

The keyword def introduces a function definition. It must be followed by the function name and theparenthesized list of formal parameters. The statements that form the body of the function start atthe next line, and must be indented.

The first statement of the function body can optionally be a string literal; this string literal is thefunction’s documentation string, or docstring. (More about docstrings can be found in the sectionDocumentation Strings.) There are tools which use docstrings to automatically produce online orprinted documentation, or to let the user interactively browse through code; it’s good practice toinclude docstrings in code that you write, so make a habit of it.

The execution of a function introduces a new symbol table used for the local variables of thefunction. More precisely, all variable assignments in a function store the value in the local symboltable; whereas variable references first look in the local symbol table, then in the local symboltables of enclosing functions, then in the global symbol table, and finally in the table of built-innames. Thus, global variables cannot be directly assigned a value within a function (unless namedin a global statement), although they may be referenced.

The actual parameters (arguments) to a function call are introduced in the local symbol table of thecalled function when it is called; thus, arguments are passed using call by value (where the valueis always an object reference, not the value of the object). [1] When a function calls anotherfunction, a new local symbol table is created for that call.

A function definition introduces the function name in the current symbol table. The value of thefunction name has a type that is recognized by the interpreter as a user-defined function. This valuecan be assigned to another name which can then also be used as a function. This serves as ageneral renaming mechanism:

Coming from other languages, you might object that fib is not a function but a procedure since itdoesn’t return a value. In fact, even functions without a return statement do return a value, albeit arather boring one. This value is called None (it’s a built-in name). Writing the value None is normallysuppressed by the interpreter if it would be the only value written. You can see it if you really want tousing print:

It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead ofprinting it:

>>> def fib(n): # write Fibonacci series up to n... """Print a Fibonacci series up to n."""... a, b = 0, 1... while a < n:... print a,... a, b = b, a+b...>>> # Now call the function we just defined:... fib(2000)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

>>>

>>> fib<function fib at 10042ed0>>>> f = fib>>> f(100)0 1 1 2 3 5 8 13 21 34 55 89

>>>

>>> fib(0)>>> print fib(0)None

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 64

Page 66: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 5/10

This example, as usual, demonstrates some new Python features:

The return statement returns with a value from a function. return without an expressionargument returns None. Falling off the end of a function also returns None.The statement result.append(a) calls a method of the list object result. A method is afunction that ‘belongs’ to an object and is named obj.methodname, where obj is some object(this may be an expression), and methodname is the name of a method that is defined by theobject’s type. Different types define different methods. Methods of different types may havethe same name without causing ambiguity. (It is possible to define your own object types andmethods, using classes, see Classes) The method append() shown in the example is definedfor list objects; it adds a new element at the end of the list. In this example it is equivalent toresult = result + [a], but more efficient.

4.7. More on Defining Functions

It is also possible to define functions with a variable number of arguments. There are three forms,which can be combined.

4.7.1. Default Argument Values

The most useful form is to specify a default value for one or more arguments. This creates afunction that can be called with fewer arguments than it is defined to allow. For example:

This function can be called in several ways:

giving only the mandatory argument: ask_ok('Do you really want to quit?')giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes orno!')

>>> def fib2(n): # return Fibonacci series up to n... """Return a list containing the Fibonacci series up to n."""... result = []... a, b = 0, 1... while a < n:... result.append(a) # see below... a, b = b, a+b... return result...>>> f100 = fib2(100) # call it>>> f100 # write the result[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

>>>

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print complaint

Einstieg in Python – Version vom 19. Juli 2017 Seite 65

Page 67: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 6/10

This example also introduces the in keyword. This tests whether or not a sequence contains acertain value.

The default values are evaluated at the point of function definition in the defining scope, so that

will print 5.

Important warning: The default value is evaluated only once. This makes a difference when thedefault is a mutable object such as a list, dictionary, or instances of most classes. For example, thefollowing function accumulates the arguments passed to it on subsequent calls:

This will print

If you don’t want the default to be shared between subsequent calls, you can write the function likethis instead:

4.7.2. Keyword Arguments

Functions can also be called using keyword arguments of the form kwarg=value. For instance, thefollowing function:

accepts one required argument (voltage) and three optional arguments (state, action, and type).This function can be called in any of the following ways:

i = 5

def f(arg=i): print arg

i = 6f()

def f(a, L=[]): L.append(a) return L

print f(1)print f(2)print f(3)

[1][1, 2][1, 2, 3]

def f(a, L=None): if L is None: L = [] L.append(a) return L

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print "-- This parrot wouldn't", action, print "if you put", voltage, "volts through it." print "-- Lovely plumage, the", type print "-- It's", state, "!"

parrot(1000) # 1 positional argumentparrot(voltage=1000) # 1 keyword argument

Einstieg in Python – Version vom 19. Juli 2017 Seite 66

Page 68: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 7/10

but all the following calls would be invalid:

In a function call, keyword arguments must follow positional arguments. All the keyword argumentspassed must match one of the arguments accepted by the function (e.g. actor is not a validargument for the parrot function), and their order is not important. This also includes non-optionalarguments (e.g. parrot(voltage=1000) is valid too). No argument may receive a value more thanonce. Here’s an example that fails due to this restriction:

When a final formal parameter of the form **name is present, it receives a dictionary (see MappingTypes — dict) containing all keyword arguments except for those corresponding to a formalparameter. This may be combined with a formal parameter of the form *name (described in the nextsubsection) which receives a tuple containing the positional arguments beyond the formalparameter list. (*name must occur before **name.) For example, if we define a function like this:

It could be called like this:

and of course it would print:

-- Do you have any Limburger ?-- I'm sorry, we're all out of LimburgerIt's very runny, sir.It's really very, VERY runny, sir.----------------------------------------client : John Cleeseshopkeeper : Michael Palinsketch : Cheese Shop Sketch

parrot(voltage=1000000, action='VOOOOOM') # 2 keyword argumentsparrot(action='VOOOOOM', voltage=1000000) # 2 keyword argumentsparrot('a million', 'bereft of life', 'jump') # 3 positional argumentsparrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword

parrot() # required argument missingparrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argumentparrot(110, voltage=220) # duplicate value for the same argumentparrot(actor='John Cleese') # unknown keyword argument

>>> def function(a):... pass...>>> function(0, a=0)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: function() got multiple values for keyword argument 'a'

>>>

def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print "-" * 40 keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw]

cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper='Michael Palin', client="John Cleese", sketch="Cheese Shop Sketch")

Einstieg in Python – Version vom 19. Juli 2017 Seite 67

Page 69: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 8/10

Note that the list of keyword argument names is created by sorting the result of the keywordsdictionary’s keys() method before printing its contents; if this is not done, the order in which thearguments are printed is undefined.

4.7.3. Arbitrary Argument Lists

Finally, the least frequently used option is to specify that a function can be called with an arbitrarynumber of arguments. These arguments will be wrapped up in a tuple (see Tuples andSequences). Before the variable number of arguments, zero or more normal arguments may occur.

4.7.4. Unpacking Argument Lists

The reverse situation occurs when the arguments are already in a list or tuple but need to beunpacked for a function call requiring separate positional arguments. For instance, the built-inrange() function expects separate start and stop arguments. If they are not available separately,write the function call with the *-operator to unpack the arguments out of a list or tuple:

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

4.7.5. Lambda Expressions

Small anonymous functions can be created with the lambda keyword. This function returns the sumof its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objectsare required. They are syntactically restricted to a single expression. Semantically, they are justsyntactic sugar for a normal function definition. Like nested function definitions, lambda functionscan reference variables from the containing scope:

def write_multiple_items(file, separator, *args): file.write(separator.join(args))

>>> range(3, 6) # normal call with separate arguments[3, 4, 5]>>> args = [3, 6]>>> range(*args) # call with arguments unpacked from a list[3, 4, 5]

>>>

>>> def parrot(voltage, state='a stiff', action='voom'):... print "-- This parrot wouldn't", action,... print "if you put", voltage, "volts through it.",... print "E's", state, "!"...>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}>>> parrot(**d)-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

>>>

>>> def make_incrementor(n):... return lambda x: x + n...>>> f = make_incrementor(42)>>> f(0)42>>> f(1)43

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 68

Page 70: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 9/10

The above example uses a lambda expression to return a function. Another use is to pass a smallfunction as an argument:

4.7.6. Documentation Strings

There are emerging conventions about the content and formatting of documentation strings.

The first line should always be a short, concise summary of the object’s purpose. For brevity, itshould not explicitly state the object’s name or type, since these are available by other means(except if the name happens to be a verb describing a function’s operation). This line should beginwith a capital letter and end with a period.

If there are more lines in the documentation string, the second line should be blank, visuallyseparating the summary from the rest of the description. The following lines should be one or moreparagraphs describing the object’s calling conventions, its side effects, etc.

The Python parser does not strip indentation from multi-line string literals in Python, so tools thatprocess documentation have to strip indentation if desired. This is done using the followingconvention. The first non-blank line after the first line of the string determines the amount ofindentation for the entire documentation string. (We can’t use the first line since it is generallyadjacent to the string’s opening quotes so its indentation is not apparent in the string literal.)Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string.Lines that are indented less should not occur, but if they occur all their leading whitespace shouldbe stripped. Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces,normally).

Here is an example of a multi-line docstring:

4.8. Intermezzo: Coding Style

Now that you are about to write longer, more complex pieces of Python, it is a good time to talkabout coding style. Most languages can be written (or more concise, formatted) in different styles;some are more readable than others. Making it easy for others to read your code is always a goodidea, and adopting a nice coding style helps tremendously for that.

For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a veryreadable and eye-pleasing coding style. Every Python developer should read it at some point; hereare the most important points extracted for you:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]>>> pairs.sort(key=lambda pair: pair[1])>>> pairs[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

>>>

>>> def my_function():... """Do nothing, but document it....... No, really, it doesn't do anything.... """... pass...>>> print my_function.__doc__Do nothing, but document it.

No, really, it doesn't do anything.

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 69

Page 71: Willkommen am Institut für Informatik — Institut für

7/14/2017 4. More Control Flow Tools — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/controlflow.html 10/10

Use 4-space indentation, and no tabs.

4 spaces are a good compromise between small indentation (allows greater nesting depth)and large indentation (easier to read). Tabs introduce confusion, and are best left out.

Wrap lines so that they don’t exceed 79 characters.

This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.

Use blank lines to separate functions and classes, and larger blocks of code insidefunctions.

When possible, put comments on a line of their own.

Use docstrings.

Use spaces around operators and after commas, but not directly inside bracketingconstructs: a = f(1, 2) + g(3, 4).

Name your classes and functions consistently; the convention is to use CamelCase for classesand lower_case_with_underscores for functions and methods. Always use self as the name forthe first method argument (see A First Look at Classes for more on classes and methods).

Don’t use fancy encodings if your code is meant to be used in international environments.Plain ASCII works best in any case.

Footnotes

[1] Actually, call by object reference would be a better description, since if a mutable object ispassed, the caller will see any changes the callee makes to it (items inserted into a list).

Einstieg in Python – Version vom 19. Juli 2017 Seite 70

Page 72: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 1/12

5. Data StructuresThis chapter describes some things you’ve learned about already in more detail, and adds somenew things as well.

5.1. More on Lists

The list data type has some more methods. Here are all of the methods of list objects:

list.append (x)Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend (L)Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert (i, x)Insert an item at a given position. The first argument is the index of the element before which toinsert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent toa.append(x).

list.remove (x)Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop ([i])Remove the item at the given position in the list, and return it. If no index is specified, a.pop()removes and returns the last item in the list. (The square brackets around the i in the methodsignature denote that the parameter is optional, not that you should type square brackets atthat position. You will see this notation frequently in the Python Library Reference.)

list.index (x)Return the index in the list of the first item whose value is x. It is an error if there is no suchitem.

list.count (x)Return the number of times x appears in the list.

list.sort (cmp=None, key=None, reverse=False)Sort the items of the list in place (the arguments can be used for sort customization, seesorted() for their explanation).

list.reverse ()Reverse the elements of the list, in place.

An example that uses most of the list methods:

>>> a = [66.25, 333, 333, 1, 1234.5]>>> print a.count(333), a.count(66.25), a.count('x')2 1 0>>> a.insert(2, -1)>>> a.append(333)>>> a[66.25, 333, -1, 333, 1, 1234.5, 333]>>> a.index(333)

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 71

Page 73: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 2/12

You might have noticed that methods like insert, remove or sort that only modify the list have noreturn value printed – they return the default None. This is a design principle for all mutable datastructures in Python.

5.1.1. Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the firstelement retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). Toretrieve an item from the top of the stack, use pop() without an explicit index. For example:

5.1.2. Using Lists as Queues

It is also possible to use a list as a queue, where the first element added is the first elementretrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends andpops from the end of list are fast, doing inserts or pops from the beginning of a list is slow(because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and popsfrom both ends. For example:

1>>> a.remove(333)>>> a[66.25, -1, 333, 1, 1234.5, 333]>>> a.reverse()>>> a[333, 1234.5, 1, 333, -1, 66.25]>>> a.sort()>>> a[-1, 1, 66.25, 333, 333, 1234.5]>>> a.pop()1234.5>>> a[-1, 1, 66.25, 333, 333]

>>> stack = [3, 4, 5]>>> stack.append(6)>>> stack.append(7)>>> stack[3, 4, 5, 6, 7]>>> stack.pop()7>>> stack[3, 4, 5, 6]>>> stack.pop()6>>> stack.pop()5>>> stack[3, 4]

>>>

>>> from collections import deque>>> queue = deque(["Eric", "John", "Michael"])>>> queue.append("Terry") # Terry arrives>>> queue.append("Graham") # Graham arrives>>> queue.popleft() # The first to arrive now leaves'Eric'>>> queue.popleft() # The second to arrive now leaves'John'

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 72

Page 74: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 3/12

5.1.3. Functional Programming Tools

There are three built-in functions that are very useful when used with lists: filter(), map(), andreduce().

filter(function, sequence) returns a sequence consisting of those items from the sequence forwhich function(item) is true. If sequence is a str, unicode or tuple, the result will be of the sametype; otherwise, it is always a list. For example, to compute a sequence of numbers divisible by 3or 5:

map(function, sequence) calls function(item) for each of the sequence’s items and returns a list ofthe return values. For example, to compute some cubes:

More than one sequence may be passed; the function must then have as many arguments as thereare sequences and is called with the corresponding item from each sequence (or None if somesequence is shorter than another). For example:

reduce(function, sequence) returns a single value constructed by calling the binary function functionon the first two items of the sequence, then on the result and the next item, and so on. For example,to compute the sum of the numbers 1 through 10:

If there’s only one item in the sequence, its value is returned; if the sequence is empty, an exceptionis raised.

A third argument can be passed to indicate the starting value. In this case the starting value isreturned for an empty sequence, and the function is first applied to the starting value and the firstsequence item, then to the result and the next item, and so on. For example,

>>> queue # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])

>>> def f(x): return x % 3 == 0 or x % 5 == 0...>>> filter(f, range(2, 25))[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

>>>

>>> def cube(x): return x*x*x...>>> map(cube, range(1, 11))[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>>

>>> seq = range(8)>>> def add(x, y): return x+y...>>> map(add, seq, seq)[0, 2, 4, 6, 8, 10, 12, 14]

>>>

>>> def add(x,y): return x+y...>>> reduce(add, range(1, 11))55

>>>

>>> def sum(seq):... def add(x,y): return x+y... return reduce(add, seq, 0)...

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 73

Page 75: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 4/12

Don’t use this example’s definition of sum(): since summing numbers is such a common need, abuilt-in function sum(sequence) is already provided, and works exactly like this.

5.1.4. List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make newlists where each element is the result of some operations applied to each member of anothersequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

We can obtain the same result with:

This is also equivalent to squares = map(lambda x: x**2, range(10)), but it’s more concise andreadable.

A list comprehension consists of brackets containing an expression followed by a for clause, thenzero or more for or if clauses. The result will be a new list resulting from evaluating the expressionin the context of the for and if clauses which follow it. For example, this listcomp combines theelements of two lists if they are not equal:

and it’s equivalent to:

Note how the order of the for and if statements is the same in both these snippets.

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

>>> sum(range(1, 11))55>>> sum([])0

>>> squares = []>>> for x in range(10):... squares.append(x**2)...>>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>>

squares = [x**2 for x in range(10)]

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y][(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

>>>

>>> combs = []>>> for x in [1,2,3]:... for y in [3,1,4]:... if x != y:... combs.append((x, y))...>>> combs[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

>>>

>>> vec = [-4, -2, 0, 2, 4]>>> # create a new list with the values doubled>>> [x*2 for x in vec][-8, -4, 0, 4, 8]

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 74

Page 76: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 5/12

List comprehensions can contain complex expressions and nested functions:

5.1.4.1. Nested List Comprehensions

The initial expression in a list comprehension can be any arbitrary expression, including another listcomprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

The following list comprehension will transpose rows and columns:

As we saw in the previous section, the nested listcomp is evaluated in the context of the for thatfollows it, so this example is equivalent to:

which, in turn, is the same as:

>>> # filter the list to exclude negative numbers>>> [x for x in vec if x >= 0][0, 2, 4]>>> # apply a function to all the elements>>> [abs(x) for x in vec][4, 2, 0, 2, 4]>>> # call a method on each element>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']>>> [weapon.strip() for weapon in freshfruit]['banana', 'loganberry', 'passion fruit']>>> # create a list of 2-tuples like (number, square)>>> [(x, x**2) for x in range(6)][(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]>>> # the tuple must be parenthesized, otherwise an error is raised>>> [x, x**2 for x in range(6)] File "<stdin>", line 1, in <module> [x, x**2 for x in range(6)] ^SyntaxError: invalid syntax>>> # flatten a list using a listcomp with two 'for'>>> vec = [[1,2,3], [4,5,6], [7,8,9]]>>> [num for elem in vec for num in elem][1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> from math import pi>>> [str(round(pi, i)) for i in range(1, 6)]['3.1', '3.14', '3.142', '3.1416', '3.14159']

>>>

>>> matrix = [... [1, 2, 3, 4],... [5, 6, 7, 8],... [9, 10, 11, 12],... ]

>>>

>>> [[row[i] for row in matrix] for i in range(4)][[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

>>>

>>> transposed = []>>> for i in range(4):... transposed.append([row[i] for row in matrix])...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 75

Page 77: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 6/12

In the real world, you should prefer built-in functions to complex flow statements. The zip() functionwould do a great job for this use case:

See Unpacking Argument Lists for details on the asterisk in this line.

5.2. The del statement

There is a way to remove an item from a list given its index instead of its value: the del statement.This differs from the pop() method which returns a value. The del statement can also be used toremove slices from a list or clear the entire list (which we did earlier by assignment of an empty listto the slice). For example:

del can also be used to delete entire variables:

Referencing the name a hereafter is an error (at least until another value is assigned to it). We’llfind other uses for del later.

5.3. Tuples and Sequences

We saw that lists and strings have many common properties, such as indexing and slicingoperations. They are two examples of sequence data types (see Sequence Types — str, unicode,list, tuple, bytearray, buffer, xrange). Since Python is an evolving language, other sequence datatypes may be added. There is also another standard sequence data type: the tuple.

A tuple consists of a number of values separated by commas, for instance:

>>> transposed = []>>> for i in range(4):... # the following 3 lines implement the nested listcomp... transposed_row = []... for row in matrix:... transposed_row.append(row[i])... transposed.append(transposed_row)...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

>>>

>>> zip(*matrix)[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

>>>

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.25, 333, 333, 1234.5]>>> del a[2:4]>>> a[1, 66.25, 1234.5]>>> del a[:]>>> a[]

>>>

>>> del a >>>

>>> t = 12345, 54321, 'hello!'>>> t[0]12345

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 76

Page 78: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 7/12

As you see, on output tuples are always enclosed in parentheses, so that nested tuples areinterpreted correctly; they may be input with or without surrounding parentheses, although oftenparentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible toassign to the individual items of a tuple, however it is possible to create tuples which containmutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for differentpurposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements thatare accessed via unpacking (see later in this section) or indexing (or even by attribute in the caseof namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessedby iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extraquirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; atuple with one item is constructed by following a value with a comma (it is not sufficient to enclose asingle value in parentheses). Ugly, but effective. For example:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321and 'hello!' are packed together in a tuple. The reverse operation is also possible:

This is called, appropriately enough, sequence unpacking and works for any sequence on theright-hand side. Sequence unpacking requires the list of variables on the left to have the samenumber of elements as the length of the sequence. Note that multiple assignment is really just acombination of tuple packing and sequence unpacking.

5.4. Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicateelements. Basic uses include membership testing and eliminating duplicate entries. Set objects

>>> t(12345, 54321, 'hello!')>>> # Tuples may be nested:... u = t, (1, 2, 3, 4, 5)>>> u((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))>>> # Tuples are immutable:... t[0] = 88888Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment>>> # but they can contain mutable objects:... v = ([1, 2, 3], [3, 2, 1])>>> v([1, 2, 3], [3, 2, 1])

>>> empty = ()>>> singleton = 'hello', # <-- note trailing comma>>> len(empty)0>>> len(singleton)1>>> singleton('hello',)

>>>

>>> x, y, z = t >>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 77

Page 79: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 8/12

also support mathematical operations like union, intersection, difference, and symmetricdifference.

Curly braces or the set() function can be used to create sets. Note: to create an empty set youhave to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss inthe next section.

Here is a brief demonstration:

Similarly to list comprehensions, set comprehensions are also supported:

5.5. Dictionaries

Another useful data type built into Python is the dictionary (see Mapping Types — dict).Dictionaries are sometimes found in other languages as “associative memories” or “associativearrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed bykeys, which can be any immutable type; strings and numbers can always be keys. Tuples can beused as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable objecteither directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can bemodified in place using index assignments, slice assignments, or methods like append() andextend().

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement thatthe keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}.Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs tothe dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the valuegiven the key. It is also possible to delete a key:value pair with del. If you store using a key that is

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> fruit = set(basket) # create a set without duplicates>>> fruitset(['orange', 'pear', 'apple', 'banana'])>>> 'orange' in fruit # fast membership testingTrue>>> 'crabgrass' in fruitFalse

>>> # Demonstrate set operations on unique letters from two words...>>> a = set('abracadabra')>>> b = set('alacazam')>>> a # unique letters in aset(['a', 'r', 'b', 'c', 'd'])>>> a - b # letters in a but not in bset(['r', 'd', 'b'])>>> a | b # letters in either a or bset(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])>>> a & b # letters in both a and bset(['a', 'c'])>>> a ^ b # letters in a or b but not bothset(['r', 'd', 'b', 'm', 'z', 'l'])

>>>

>>> a = {x for x in 'abracadabra' if x not in 'abc'}>>> aset(['r', 'd'])

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 78

Page 80: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 9/12

already in use, the old value associated with that key is forgotten. It is an error to extract a valueusing a non-existent key.

The keys() method of a dictionary object returns a list of all the keys used in the dictionary, inarbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a singlekey is in the dictionary, use the in keyword.

Here is a small example using a dictionary:

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and valueexpressions:

When the keys are simple strings, it is sometimes easier to specify pairs using keywordarguments:

5.6. Looping Techniques

When looping through a sequence, the position index and corresponding value can be retrieved atthe same time using the enumerate() function.

To loop over two or more sequences at the same time, the entries can be paired with the zip()function.

>>> tel = {'jack': 4098, 'sape': 4139}>>> tel['guido'] = 4127>>> tel{'sape': 4139, 'guido': 4127, 'jack': 4098}>>> tel['jack']4098>>> del tel['sape']>>> tel['irv'] = 4127>>> tel{'guido': 4127, 'irv': 4127, 'jack': 4098}>>> tel.keys()['guido', 'irv', 'jack']>>> 'guido' in telTrue

>>>

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]){'sape': 4139, 'jack': 4098, 'guido': 4127}

>>>

>>> {x: x**2 for x in (2, 4, 6)}{2: 4, 4: 16, 6: 36}

>>>

>>> dict(sape=4139, guido=4127, jack=4098){'sape': 4139, 'jack': 4098, 'guido': 4127}

>>>

>>> for i, v in enumerate(['tic', 'tac', 'toe']):... print i, v...0 tic1 tac2 toe

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 79

Page 81: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 10/12

To loop over a sequence in reverse, first specify the sequence in a forward direction and then callthe reversed() function.

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted listwhile leaving the source unaltered.

When looping through dictionaries, the key and corresponding value can be retrieved at the sametime using the iteritems() method.

It is sometimes tempting to change a list while you are looping over it; however, it is often simplerand safer to create a new list instead.

5.7. More on Conditions

The conditions used in while and if statements can contain any operators, not just comparisons.

>>> questions = ['name', 'quest', 'favorite color']>>> answers = ['lancelot', 'the holy grail', 'blue']>>> for q, a in zip(questions, answers):... print 'What is your {0}? It is {1}.'.format(q, a)...What is your name? It is lancelot.What is your quest? It is the holy grail.What is your favorite color? It is blue.

>>>

>>> for i in reversed(xrange(1,10,2)):... print i...97531

>>>

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):... print f...applebananaorangepear

>>>

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}>>> for k, v in knights.iteritems():... print k, v...gallahad the purerobin the brave

>>>

>>> import math>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]>>> filtered_data = []>>> for value in raw_data:... if not math.isnan(value):... filtered_data.append(value)...>>> filtered_data[56.2, 51.7, 55.3, 52.5, 47.8]

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 80

Page 82: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 11/12

The comparison operators in and not in check whether a value occurs (does not occur) in asequence. The operators is and is not compare whether two objects are really the same object;this only matters for mutable objects like lists. All comparison operators have the same priority,which is lower than that of all numerical operators.

Comparisons can be chained. For example, a < b == c tests whether a is less than b andmoreover b equals c.

Comparisons may be combined using the Boolean operators and and or, and the outcome of acomparison (or of any other Boolean expression) may be negated with not. These have lowerpriorities than comparison operators; between them, not has the highest priority and or the lowest,so that A and not B or C is equivalent to (A and (not B)) or C. As always, parentheses can beused to express the desired composition.

The Boolean operators and and or are so-called short-circuit operators: their arguments areevaluated from left to right, and evaluation stops as soon as the outcome is determined. Forexample, if A and C are true but B is false, A and B and C does not evaluate the expression C. Whenused as a general value and not as a Boolean, the return value of a short-circuit operator is the lastevaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. Forexample,

Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers maygrumble about this, but it avoids a common class of problems encountered in C programs: typing =in an expression when == was intended.

5.8. Comparing Sequences and Other Types

Sequence objects may be compared to other objects with the same sequence type. Thecomparison uses lexicographical ordering: first the first two items are compared, and if they differthis determines the outcome of the comparison; if they are equal, the next two items are compared,and so on, until either sequence is exhausted. If two items to be compared are themselvessequences of the same type, the lexicographical comparison is carried out recursively. If all itemsof two sequences compare equal, the sequences are considered equal. If one sequence is aninitial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographicalordering for strings uses the ASCII ordering for individual characters. Some examples ofcomparisons between sequences of the same type:

Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary:the types are ordered by their name. Thus, a list is always smaller than a string, a string is always

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'>>> non_null = string1 or string2 or string3>>> non_null'Trondheim'

>>>

(1, 2, 3) < (1, 2, 4)[1, 2, 3] < [1, 2, 4]'ABC' < 'C' < 'Pascal' < 'Python'(1, 2, 3, 4) < (1, 2, 4)(1, 2) < (1, 2, -1)(1, 2, 3) == (1.0, 2.0, 3.0)(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)

Einstieg in Python – Version vom 19. Juli 2017 Seite 81

Page 83: Willkommen am Institut für Informatik — Institut für

7/14/2017 5. Data Structures — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/datastructures.html 12/12

smaller than a tuple, etc. [1] Mixed numeric types are compared according to their numeric value,so 0 equals 0.0, etc.

Footnotes

[1] The rules for comparing objects of different types should not be relied upon; they may changein a future version of the language.

Einstieg in Python – Version vom 19. Juli 2017 Seite 82

Page 84: Willkommen am Institut für Informatik — Institut für

7/14/2017 7. Input and Output — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/inputoutput.html 1/7

7. Input and OutputThere are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities.

7.1. Fancier Output Formatting

So far we’ve encountered two ways of writing values: expression statements and the printstatement. (A third way is using the write() method of file objects; the standard output file can bereferenced as sys.stdout. See the Library Reference for more information on this.)

Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are two ways to format your output; the first way is to do all the stringhandling yourself; using string slicing and concatenation operations you can create any layout youcan imagine. The string types have some methods that perform useful operations for paddingstrings to a given column width; these will be discussed shortly. The second way is to use thestr.format() method.

The string module contains a Template class which offers yet another way to substitute values intostrings.

One question remains, of course: how do you convert values to strings? Luckily, Python has waysto convert any value to a string: pass it to the repr() or str() functions.

The str() function is meant to return representations of values which are fairly human-readable,while repr() is meant to generate representations which can be read by the interpreter (or willforce a SyntaxError if there is no equivalent syntax). For objects which don’t have a particularrepresentation for human consumption, str() will return the same value as repr(). Many values,such as numbers or structures like lists and dictionaries, have the same representation using eitherfunction. Strings and floating point numbers, in particular, have two distinct representations.

Some examples:

>>> s = 'Hello, world.'>>> str(s)'Hello, world.'>>> repr(s)"'Hello, world.'">>> str(1.0/7.0)'0.142857142857'>>> repr(1.0/7.0)'0.14285714285714285'>>> x = 10 * 3.25>>> y = 200 * 200>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'>>> print sThe value of x is 32.5, and y is 40000...>>> # The repr() of a string adds string quotes and backslashes:... hello = 'hello, world\n'>>> hellos = repr(hello)>>> print hellos'hello, world\n'>>> # The argument to repr() may be any Python object:... repr((x, y, ('spam', 'eggs')))"(32.5, 40000, ('spam', 'eggs'))"

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 83

Page 85: Willkommen am Institut für Informatik — Institut für

7/14/2017 7. Input and Output — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/inputoutput.html 2/7

Here are two ways to write a table of squares and cubes:

(Note that in the first example, one space between each column was added by the way printworks: it always adds spaces between its arguments.)

This example demonstrates the str.rjust() method of string objects, which right-justifies a string ina field of a given width by padding it with spaces on the left. There are similar methods str.ljust()and str.center(). These methods do not write anything, they just return a new string. If the inputstring is too long, they don’t truncate it, but return it unchanged; this will mess up your column lay-outbut that’s usually better than the alternative, which would be lying about a value. (If you really wanttruncation you can always add a slice operation, as in x.ljust(n)[:n].)

There is another method, str.zfill(), which pads a numeric string on the left with zeros. Itunderstands about plus and minus signs:

Basic usage of the str.format() method looks like this:

The brackets and characters within them (called format fields) are replaced with the objectspassed into the str.format() method. A number in the brackets refers to the position of the objectpassed into the str.format() method.

>>> for x in range(1, 11):... print repr(x).rjust(2), repr(x*x).rjust(3),... # Note trailing comma on previous line... print repr(x*x*x).rjust(4)... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 72910 100 1000

>>> for x in range(1,11):... print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 72910 100 1000

>>>

>>> '12'.zfill(5)'00012'>>> '-3.14'.zfill(7)'-003.14'>>> '3.14159265359'.zfill(5)'3.14159265359'

>>>

>>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')We are the knights who say "Ni!"

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 84

Page 86: Willkommen am Institut für Informatik — Institut für

7/14/2017 7. Input and Output — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/inputoutput.html 3/7

If keyword arguments are used in the str.format() method, their values are referred to by using thename of the argument.

Positional and keyword arguments can be arbitrarily combined:

'!s' (apply str()) and '!r' (apply repr()) can be used to convert the value before it is formatted.

An optional ':' and format specifier can follow the field name. This allows greater control over howthe value is formatted. The following example rounds Pi to three places after the decimal.

Passing an integer after the ':' will cause that field to be a minimum number of characters wide.This is useful for making tables pretty.

If you have a really long format string that you don’t want to split up, it would be nice if you couldreference the variables to be formatted by name instead of by position. This can be done by simplypassing the dict and using square brackets '[]' to access the keys

This could also be done by passing the table as keyword arguments with the ‘**’ notation.

>>> print '{0} and {1}'.format('spam', 'eggs')spam and eggs>>> print '{1} and {0}'.format('spam', 'eggs')eggs and spam

>>>

>>> print 'This {food} is {adjective}.'.format(... food='spam', adjective='absolutely horrible')This spam is absolutely horrible.

>>>

>>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',... other='Georg')The story of Bill, Manfred, and Georg.

>>>

>>> import math>>> print 'The value of PI is approximately {}.'.format(math.pi)The value of PI is approximately 3.14159265359.>>> print 'The value of PI is approximately {!r}.'.format(math.pi)The value of PI is approximately 3.141592653589793.

>>>

>>> import math>>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)The value of PI is approximately 3.142.

>>>

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}>>> for name, phone in table.items():... print '{0:10} ==> {1:10d}'.format(name, phone)...Jack ==> 4098Dcab ==> 7678Sjoerd ==> 4127

>>>

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}>>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '... 'Dcab: {0[Dcab]:d}'.format(table))Jack: 4098; Sjoerd: 4127; Dcab: 8637678

>>>

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}>>> print 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)Jack: 4098; Sjoerd: 4127; Dcab: 8637678

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 85

Page 87: Willkommen am Institut für Informatik — Institut für

7/14/2017 7. Input and Output — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/inputoutput.html 4/7

This is particularly useful in combination with the built-in function vars(), which returns a dictionarycontaining all local variables.

For a complete overview of string formatting with str.format(), see Format String Syntax.

7.1.1. Old string formatting

The % operator can also be used for string formatting. It interprets the left argument much like asprintf()-style format string to be applied to the right argument, and returns the string resultingfrom this formatting operation. For example:

More information can be found in the String Formatting Operations section.

7.2. Reading and Writing Files

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

The first argument is a string containing the filename. The second argument is another stringcontaining a few characters describing the way in which the file will be used. mode can be 'r'when the file will only be read, 'w' for only writing (an existing file with the same name will beerased), and 'a' opens the file for appending; any data written to the file is automatically added tothe end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' willbe assumed if it’s omitted.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modeslike 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files;the end-of-line characters in text files are automatically altered slightly when data is read or written.This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binarydata like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing suchfiles. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independentlyfor all binary files.

7.2.1. Methods of File Objects

The rest of the examples in this section will assume that a file object called f has already beencreated.

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as astring. size is an optional numeric argument. When size is omitted or negative, the entire contentsof the file will be read and returned; it’s your problem if the file is twice as large as your machine’smemory. Otherwise, at most size bytes are read and returned. If the end of the file has beenreached, f.read() will return an empty string ("").

>>> import math>>> print 'The value of PI is approximately %5.3f.' % math.piThe value of PI is approximately 3.142.

>>>

>>> f = open('workfile', 'w')>>> print f<open file 'workfile', mode 'w' at 80a0960>

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 86

Page 88: Willkommen am Institut für Informatik — Institut für

7/14/2017 7. Input and Output — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/inputoutput.html 5/7

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string,and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes thereturn value unambiguous; if f.readline() returns an empty string, the end of the file has beenreached, while a blank line is represented by '\n', a string containing only a single newline.

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, andleads to simple code:

If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

f.write(string) writes the contents of string to the file, returning None.

To write something other than a string, it needs to be converted to a string first:

f.tell() returns an integer giving the file object’s current position in the file, measured in bytesfrom the beginning of the file. To change the file object’s position, use f.seek(offset, from_what).The position is computed from adding offset to a reference point; the reference point is selected bythe from_what argument. A from_what value of 0 measures from the beginning of the file, 1 usesthe current file position, and 2 uses the end of the file as the reference point. from_what can beomitted and defaults to 0, using the beginning of the file as the reference point.

When you’re done with a file, call f.close() to close it and free up any system resources taken upby the open file. After calling f.close(), attempts to use the file object will automatically fail.

>>> f.read()'This is the entire file.\n'>>> f.read()''

>>>

>>> f.readline()'This is the first line of the file.\n'>>> f.readline()'Second line of the file\n'>>> f.readline()''

>>>

>>> for line in f: print line,

This is the first line of the file.Second line of the file

>>>

>>> f.write('This is a test\n') >>>

>>> value = ('the answer', 42)>>> s = str(value)>>> f.write(s)

>>>

>>> f = open('workfile', 'r+')>>> f.write('0123456789abcdef')>>> f.seek(5) # Go to the 6th byte in the file>>> f.read(1)'5'>>> f.seek(-3, 2) # Go to the 3rd byte before the end>>> f.read(1)'d'

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 87

Page 89: Willkommen am Institut für Informatik — Institut für

7/14/2017 7. Input and Output — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/inputoutput.html 6/7

It is good practice to use the with keyword when dealing with file objects. This has the advantagethat the file is properly closed after its suite finishes, even if an exception is raised on the way. It isalso much shorter than writing equivalent try-finally blocks:

File objects have some additional methods, such as isatty() and truncate() which are lessfrequently used; consult the Library Reference for a complete guide to file objects.

7.2.2. Saving structured data with json

Strings can easily be written to and read from a file. Numbers take a bit more effort, since theread() method only returns strings, which will have to be passed to a function like int(), whichtakes a string like '123' and returns its numeric value 123. When you want to save more complexdata types like nested lists and dictionaries, parsing and serializing by hand becomescomplicated.

Rather than having users constantly writing and debugging code to save complicated data types tofiles, Python allows you to use the popular data interchange format called JSON (JavaScript ObjectNotation). The standard module called json can take Python data hierarchies, and convert them tostring representations; this process is called serializing. Reconstructing the data from the stringrepresentation is called deserializing. Between serializing and deserializing, the stringrepresenting the object may have been stored in a file or data, or sent over a network connection tosome distant machine.

Note: The JSON format is commonly used by modern applications to allow for data exchange.Many programmers are already familiar with it, which makes it a good choice for interoperability.

If you have an object x, you can view its JSON string representation with a simple line of code:

Another variant of the dumps() function, called dump(), simply serializes the object to a file. So if f isa file object opened for writing, we can do this:

To decode the object again, if f is a file object which has been opened for reading:

>>> f.close()>>> f.read()Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: I/O operation on closed file

>>>

>>> with open('workfile', 'r') as f:... read_data = f.read()>>> f.closedTrue

>>>

>>> import json>>> json.dumps([1, 'simple', 'list'])'[1, "simple", "list"]'

>>>

json.dump(x, f)

x = json.load(f)

Einstieg in Python – Version vom 19. Juli 2017 Seite 88

Page 90: Willkommen am Institut für Informatik — Institut für

7/14/2017 7. Input and Output — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/inputoutput.html 7/7

This simple serialization technique can handle lists and dictionaries, but serializing arbitrary classinstances in JSON requires a bit of extra effort. The reference for the json module contains anexplanation of this.

See also: pickle - the pickle module

Contrary to JSON, pickle is a protocol which allows the serialization of arbitrarily complex Pythonobjects. As such, it is specific to Python and cannot be used to communicate with applicationswritten in other languages. It is also insecure by default: deserializing pickle data coming from anuntrusted source can execute arbitrary code, if the data was crafted by a skilled attacker.

Einstieg in Python – Version vom 19. Juli 2017 Seite 89

Page 91: Willkommen am Institut für Informatik — Institut für

7/14/2017 8. Errors and Exceptions — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/errors.html 1/7

8. Errors and ExceptionsUntil now error messages haven’t been more than mentioned, but if you have tried out theexamples you have probably seen some. There are (at least) two distinguishable kinds of errors:syntax errors and exceptions.

8.1. Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint youget while you are still learning Python:

The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in theline where the error was detected. The error is caused by (or at least detected at) the tokenpreceding the arrow: in the example, the error is detected at the keyword print, since a colon (':')is missing before it. File name and line number are printed so you know where to look in case theinput came from a script.

8.2. Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt ismade to execute it. Errors detected during execution are called exceptions and are notunconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptionsare not handled by programs, however, and result in error messages as shown here:

The last line of the error message indicates what happened. Exceptions come in different types,and the type is printed as part of the message: the types in the example are ZeroDivisionError,NameError and TypeError. The string printed as the exception type is the name of the built-inexception that occurred. This is true for all built-in exceptions, but need not be true for user-definedexceptions (although it is a useful convention). Standard exception names are built-in identifiers(not reserved keywords).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception happened, in theform of a stack traceback. In general it contains a stack traceback listing source lines; however, it

>>> while True print 'Hello world' File "<stdin>", line 1 while True print 'Hello world' ^SyntaxError: invalid syntax

>>>

>>> 10 * (1/0)Traceback (most recent call last): File "<stdin>", line 1, in <module>ZeroDivisionError: integer division or modulo by zero>>> 4 + spam*3Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'spam' is not defined>>> '2' + 2Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: cannot concatenate 'str' and 'int' objects

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 90

Page 92: Willkommen am Institut für Informatik — Institut für

7/14/2017 8. Errors and Exceptions — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/errors.html 2/7

will not display lines read from standard input.

Built-in Exceptions lists the built-in exceptions and their meanings.

8.3. Handling Exceptions

It is possible to write programs that handle selected exceptions. Look at the following example,which asks the user for input until a valid integer has been entered, but allows the user to interruptthe program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

The try statement works as follows.

First, the try clause (the statement(s) between the try and except keywords) is executed.If no exception occurs, the except clause is skipped and execution of the try statement isfinished.If an exception occurs during execution of the try clause, the rest of the clause is skipped.Then if its type matches the exception named after the except keyword, the except clause isexecuted, and then execution continues after the try statement.If an exception occurs which does not match the exception named in the except clause, it ispassed on to outer try statements; if no handler is found, it is an unhandled exception andexecution stops with a message as shown above.

A try statement may have more than one except clause, to specify handlers for differentexceptions. At most one handler will be executed. Handlers only handle exceptions that occur in thecorresponding try clause, not in other handlers of the same try statement. An except clause mayname multiple exceptions as a parenthesized tuple, for example:

Note that the parentheses around this tuple are required, because except ValueError, e: was thesyntax used for what is normally written as except ValueError as e: in modern Python (describedbelow). The old syntax is still supported for backwards compatibility. This means exceptRuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but to exceptRuntimeError as TypeError: which is not what you want.

The last except clause may omit the exception name(s), to serve as a wildcard. Use this withextreme caution, since it is easy to mask a real programming error in this way! It can also be usedto print an error message and then re-raise the exception (allowing a caller to handle the exceptionas well):

>>> while True:... try:... x = int(raw_input("Please enter a number: "))... break... except ValueError:... print "Oops! That was no valid number. Try again..."...

>>>

... except (RuntimeError, TypeError, NameError):

... pass

import sys

try: f = open('myfile.txt')

Einstieg in Python – Version vom 19. Juli 2017 Seite 91

Page 93: Willkommen am Institut für Informatik — Institut für

7/14/2017 8. Errors and Exceptions — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/errors.html 3/7

The try ... except statement has an optional else clause, which, when present, must follow allexcept clauses. It is useful for code that must be executed if the try clause does not raise anexception. For example:

The use of the else clause is better than adding additional code to the try clause because itavoids accidentally catching an exception that wasn’t raised by the code being protected by thetry ... except statement.

When an exception occurs, it may have an associated value, also known as the exception’sargument. The presence and type of the argument depend on the exception type.

The except clause may specify a variable after the exception name (or tuple). The variable isbound to an exception instance with the arguments stored in instance.args. For convenience, theexception instance defines __str__() so the arguments can be printed directly without having toreference .args.

One may also instantiate an exception first before raising it and add any attributes to it as desired.

If an exception has an argument, it is printed as the last part (‘detail’) of the message for unhandledexceptions.

Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but alsoif they occur inside functions that are called (even indirectly) in the try clause. For example:

s = f.readline() i = int(s.strip())except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror)except ValueError: print "Could not convert data to an integer."except: print "Unexpected error:", sys.exc_info()[0] raise

for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close()

>>> try:... raise Exception('spam', 'eggs')... except Exception as inst:... print type(inst) # the exception instance... print inst.args # arguments stored in .args... print inst # __str__ allows args to be printed directly... x, y = inst.args... print 'x =', x... print 'y =', y...<type 'exceptions.Exception'>('spam', 'eggs')('spam', 'eggs')x = spamy = eggs

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 92

Page 94: Willkommen am Institut für Informatik — Institut für

7/14/2017 8. Errors and Exceptions — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/errors.html 4/7

8.4. Raising Exceptions

The raise statement allows the programmer to force a specified exception to occur. For example:

The sole argument to raise indicates the exception to be raised. This must be either an exceptioninstance or an exception class (a class that derives from Exception).

If you need to determine whether an exception was raised but don’t intend to handle it, a simplerform of the raise statement allows you to re-raise the exception:

8.5. User-defined Exceptions

Programs may name their own exceptions by creating a new exception class (see Classes formore about Python classes). Exceptions should typically be derived from the Exception class,either directly or indirectly. For example:

>>> def this_fails():... x = 1/0...>>> try:... this_fails()... except ZeroDivisionError as detail:... print 'Handling run-time error:', detail...Handling run-time error: integer division or modulo by zero

>>>

>>> raise NameError('HiThere')Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: HiThere

>>>

>>> try:... raise NameError('HiThere')... except NameError:... print 'An exception flew by!'... raise...An exception flew by!Traceback (most recent call last): File "<stdin>", line 2, in <module>NameError: HiThere

>>>

>>> class MyError(Exception):... def __init__(self, value):... self.value = value... def __str__(self):... return repr(self.value)...>>> try:... raise MyError(2*2)... except MyError as e:... print 'My exception occurred, value:', e.value...My exception occurred, value: 4>>> raise MyError('oops!')Traceback (most recent call last): File "<stdin>", line 1, in <module>__main__.MyError: 'oops!'

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 93

Page 95: Willkommen am Institut für Informatik — Institut für

7/14/2017 8. Errors and Exceptions — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/errors.html 5/7

In this example, the default __init__() of Exception has been overridden. The new behavior simplycreates the value attribute. This replaces the default behavior of creating the args attribute.

Exception classes can be defined which do anything any other class can do, but are usually keptsimple, often only offering a number of attributes that allow information about the error to beextracted by handlers for the exception. When creating a module that can raise several distincterrors, a common practice is to create a base class for exceptions defined by that module, andsubclass that to create specific exception classes for different error conditions:

Most exceptions are defined with names that end in “Error,” similar to the naming of the standardexceptions.

Many standard modules define their own exceptions to report errors that may occur in functionsthey define. More information on classes is presented in chapter Classes.

8.6. Defining Clean-up Actions

The try statement has another optional clause which is intended to define clean-up actions thatmust be executed under all circumstances. For example:

class Error(Exception): """Base class for exceptions in this module.""" pass

class InputError(Error): """Exception raised for errors in the input.

Attributes: expr -- input expression in which the error occurred msg -- explanation of the error """

def __init__(self, expr, msg): self.expr = expr self.msg = msg

class TransitionError(Error): """Raised when an operation attempts a state transition that's not allowed.

Attributes: prev -- state at beginning of transition next -- attempted new state msg -- explanation of why the specific transition is not allowed """

def __init__(self, prev, next, msg): self.prev = prev self.next = next self.msg = msg

>>> try:... raise KeyboardInterrupt... finally:... print 'Goodbye, world!'...Goodbye, world!KeyboardInterruptTraceback (most recent call last): File "<stdin>", line 2, in <module>

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 94

Page 96: Willkommen am Institut für Informatik — Institut für

7/14/2017 8. Errors and Exceptions — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/errors.html 6/7

A finally clause is always executed before leaving the try statement, whether an exception hasoccurred or not. When an exception has occurred in the try clause and has not been handled byan except clause (or it has occurred in an except or else clause), it is re-raised after the finallyclause has been executed. The finally clause is also executed “on the way out” when any otherclause of the try statement is left via a break, continue or return statement. A more complicatedexample (having except and finally clauses in the same try statement works as of Python 2.5):

As you can see, the finally clause is executed in any event. The TypeError raised by dividing twostrings is not handled by the except clause and therefore re-raised after the finally clause hasbeen executed.

In real world applications, the finally clause is useful for releasing external resources (such asfiles or network connections), regardless of whether the use of the resource was successful.

8.7. Predefined Clean-up Actions

Some objects define standard clean-up actions to be undertaken when the object is no longerneeded, regardless of whether or not the operation using the object succeeded or failed. Look atthe following example, which tries to open a file and print its contents to the screen.

The problem with this code is that it leaves the file open for an indeterminate amount of time afterthe code has finished executing. This is not an issue in simple scripts, but can be a problem forlarger applications. The with statement allows objects like files to be used in a way that ensuresthey are always cleaned up promptly and correctly.

After the statement is executed, the file f is always closed, even if a problem was encounteredwhile processing the lines. Other objects which provide predefined clean-up actions will indicate

>>> def divide(x, y):... try:... result = x / y... except ZeroDivisionError:... print "division by zero!"... else:... print "result is", result... finally:... print "executing finally clause"...>>> divide(2, 1)result is 2executing finally clause>>> divide(2, 0)division by zero!executing finally clause>>> divide("2", "1")executing finally clauseTraceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in divideTypeError: unsupported operand type(s) for /: 'str' and 'str'

>>>

for line in open("myfile.txt"): print line,

with open("myfile.txt") as f: for line in f: print line,

Einstieg in Python – Version vom 19. Juli 2017 Seite 95

Page 97: Willkommen am Institut für Informatik — Institut für

7/14/2017 8. Errors and Exceptions — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/errors.html 7/7

this in their documentation.

Einstieg in Python – Version vom 19. Juli 2017 Seite 96

Page 98: Willkommen am Institut für Informatik — Institut für

7/14/2017 10. Brief Tour of the Standard Library — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/stdlib.html 1/5

10. Brief Tour of the Standard Library

10.1. Operating System Interface

The os module provides dozens of functions for interacting with the operating system:

Be sure to use the import os style instead of from os import *. This will keep os.open() fromshadowing the built-in open() function which operates much differently.

The built-in dir() and help() functions are useful as interactive aids for working with large moduleslike os:

For daily file and directory management tasks, the shutil module provides a higher level interfacethat is easier to use:

10.2. File Wildcards

The glob module provides a function for making file lists from directory wildcard searches:

10.3. Command Line Arguments

Common utility scripts often need to process command line arguments. These arguments arestored in the sys module’s argv attribute as a list. For instance the following output results fromrunning python demo.py one two three at the command line:

The getopt module processes sys.argv using the conventions of the Unix getopt() function. Morepowerful and flexible command line processing is provided by the argparse module.

>>> import os>>> os.getcwd() # Return the current working directory'C:\\Python26'>>> os.chdir('/server/accesslogs') # Change current working directory>>> os.system('mkdir today') # Run the command mkdir in the system shell0

>>>

>>> import os>>> dir(os)<returns a list of all module functions>>>> help(os)<returns an extensive manual page created from the module's docstrings>

>>>

>>> import shutil>>> shutil.copyfile('data.db', 'archive.db')>>> shutil.move('/build/executables', 'installdir')

>>>

>>> import glob>>> glob.glob('*.py')['primes.py', 'random.py', 'quote.py']

>>>

>>> import sys>>> print sys.argv['demo.py', 'one', 'two', 'three']

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 97

Page 99: Willkommen am Institut für Informatik — Institut für

7/14/2017 10. Brief Tour of the Standard Library — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/stdlib.html 2/5

10.4. Error Output Redirection and Program Termination

The sys module also has attributes for stdin, stdout, and stderr. The latter is useful for emittingwarnings and error messages to make them visible even when stdout has been redirected:

The most direct way to terminate a script is to use sys.exit().

10.5. String Pattern Matching

The re module provides regular expression tools for advanced string processing. For complexmatching and manipulation, regular expressions offer succinct, optimized solutions:

When only simple capabilities are needed, string methods are preferred because they are easierto read and debug:

10.6. Mathematics

The math module gives access to the underlying C library functions for floating point math:

The random module provides tools for making random selections:

10.7. Internet Access

There are a number of modules for accessing the internet and processing internet protocols. Twoof the simplest are urllib2 for retrieving data from URLs and smtplib for sending mail:

>>> sys.stderr.write('Warning, log file not found starting a new one\n')Warning, log file not found starting a new one

>>>

>>> import re>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')['foot', 'fell', 'fastest']>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')'cat in the hat'

>>>

>>> 'tea for too'.replace('too', 'two')'tea for two'

>>>

>>> import math>>> math.cos(math.pi / 4.0)0.70710678118654757>>> math.log(1024, 2)10.0

>>>

>>> import random>>> random.choice(['apple', 'pear', 'banana'])'apple'>>> random.sample(xrange(100), 10) # sampling without replacement[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]>>> random.random() # random float0.17970987693706186>>> random.randrange(6) # random integer chosen from range(6)4

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 98

Page 100: Willkommen am Institut für Informatik — Institut für

7/14/2017 10. Brief Tour of the Standard Library — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/stdlib.html 3/5

(Note that the second example needs a mailserver running on localhost.)

10.8. Dates and Times

The datetime module supplies classes for manipulating dates and times in both simple andcomplex ways. While date and time arithmetic is supported, the focus of the implementation is onefficient member extraction for output formatting and manipulation. The module also supportsobjects that are timezone aware.

10.9. Data Compression

Common data archiving and compression formats are directly supported by modules including:zlib, gzip, bz2, zipfile and tarfile.

10.10. Performance Measurement

>>> import urllib2>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):... if 'EST' in line or 'EDT' in line: # look for Eastern Time... print line

<BR>Nov. 25, 09:43:32 PM EST

>>> import smtplib>>> server = smtplib.SMTP('localhost')>>> server.sendmail('[email protected]', '[email protected]',... """To: [email protected]... From: [email protected]...... Beware the Ides of March.... """)>>> server.quit()

>>>

>>> # dates are easily constructed and formatted>>> from datetime import date>>> now = date.today()>>> nowdatetime.date(2003, 12, 2)>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # dates support calendar arithmetic>>> birthday = date(1964, 7, 31)>>> age = now - birthday>>> age.days14368

>>>

>>> import zlib>>> s = 'witch which has which witches wrist watch'>>> len(s)41>>> t = zlib.compress(s)>>> len(t)37>>> zlib.decompress(t)'witch which has which witches wrist watch'>>> zlib.crc32(s)226805979

>>>

Einstieg in Python – Version vom 19. Juli 2017 Seite 99

Page 101: Willkommen am Institut für Informatik — Institut für

7/14/2017 10. Brief Tour of the Standard Library — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/stdlib.html 4/5

Some Python users develop a deep interest in knowing the relative performance of differentapproaches to the same problem. Python provides a measurement tool that answers thosequestions immediately.

For example, it may be tempting to use the tuple packing and unpacking feature instead of thetraditional approach to swapping arguments. The timeit module quickly demonstrates a modestperformance advantage:

In contrast to timeit‘s fine level of granularity, the profile and pstats modules provide tools foridentifying time critical sections in larger blocks of code.

10.11. Quality Control

One approach for developing high quality software is to write tests for each function as it isdeveloped and to run those tests frequently during the development process.

The doctest module provides a tool for scanning a module and validating tests embedded in aprogram’s docstrings. Test construction is as simple as cutting-and-pasting a typical call along withits results into the docstring. This improves the documentation by providing the user with anexample and it allows the doctest module to make sure the code remains true to thedocumentation:

The unittest module is not as effortless as the doctest module, but it allows a morecomprehensive set of tests to be maintained in a separate file:

10.12. Batteries Included

>>> from timeit import Timer>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()0.57535828626024577>>> Timer('a,b = b,a', 'a=1; b=2').timeit()0.54962537085770791

>>>

def average(values): """Computes the arithmetic mean of a list of numbers.

>>> print average([20, 30, 70]) 40.0 """ return sum(values, 0.0) / len(values)

import doctestdoctest.testmod() # automatically validate the embedded tests

import unittest

class TestStatisticalFunctions(unittest.TestCase):

def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70)

unittest.main() # Calling from the command line invokes all tests

Einstieg in Python – Version vom 19. Juli 2017 Seite 100

Page 102: Willkommen am Institut für Informatik — Institut für

7/14/2017 10. Brief Tour of the Standard Library — Python 2.7.13 documentation

https://docs.python.org/2/tutorial/stdlib.html 5/5

Python has a “batteries included” philosophy. This is best seen through the sophisticated androbust capabilities of its larger packages. For example:

The xmlrpclib and SimpleXMLRPCServer modules make implementing remote procedure callsinto an almost trivial task. Despite the modules names, no direct knowledge or handling ofXML is needed.The email package is a library for managing email messages, including MIME and otherRFC 2822-based message documents. Unlike smtplib and poplib which actually send andreceive messages, the email package has a complete toolset for building or decodingcomplex message structures (including attachments) and for implementing internet encodingand header protocols.The xml.dom and xml.sax packages provide robust support for parsing this popular datainterchange format. Likewise, the csv module supports direct reads and writes in a commondatabase format. Together, these modules and packages greatly simplify data interchangebetween Python applications and other tools.Internationalization is supported by a number of modules including gettext, locale, and thecodecs package.

Einstieg in Python – Version vom 19. Juli 2017 Seite 101