summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAdam Bard <github@adambard.com>2020-02-13 22:00:05 -0800
committerGitHub <noreply@github.com>2020-02-13 22:00:05 -0800
commit0a0a40dc2d29ed6ec8305bef5fffa83c14727e4c (patch)
treeaf8de5c938a140d28c9836bd88186eeeae85bc64
parent6078f18d130bc6b609036e7e76b3913c270d8b9c (diff)
parentae848c481fabaca935ffbe33293a43a43434d268 (diff)
Merge pull request #3856 from sshine/make-python3-default
[Python] Make Python 3 default
-rw-r--r--ar-ar/python-ar.html.markdown (renamed from ar-ar/python3-ar.html.markdown)6
-rw-r--r--cs-cz/python.html.markdown (renamed from cs-cz/python3.html.markdown)2
-rw-r--r--de-de/python-de.html.markdown603
-rw-r--r--de-de/python3-de.html.markdown655
-rw-r--r--de-de/pythonlegacy-de.html.markdown766
-rw-r--r--el-gr/python-gr.html.markdown (renamed from el-gr/python3-gr.html.markdown)6
-rw-r--r--es-es/python-es.html.markdown323
-rw-r--r--es-es/pythonlegacy-es.html.markdown (renamed from es-es/python3-es.html.markdown)325
-rw-r--r--fr-fr/python-fr.html.markdown802
-rw-r--r--fr-fr/python3-fr.html.markdown732
-rw-r--r--fr-fr/pythonlegacy-fr.html.markdown488
-rw-r--r--hu-hu/pythonlegacy-hu.html.markdown (renamed from hu-hu/python-hu.html.markdown)6
-rw-r--r--it-it/python-it.html.markdown952
-rw-r--r--it-it/python3-it.html.markdown1016
-rw-r--r--it-it/pythonlegacy-it.html.markdown778
-rw-r--r--ja-jp/python-jp.html.markdown (renamed from ja-jp/python3-jp.html.markdown)6
-rw-r--r--ko-kr/pythonlegacy-kr.html.markdown (renamed from ko-kr/python-kr.html.markdown)4
-rw-r--r--pl-pl/pythonlegacy-pl.html.markdown (renamed from pl-pl/python-pl.html.markdown)4
-rw-r--r--pt-br/python-pt.html.markdown881
-rw-r--r--pt-br/python3-pt.html.markdown746
-rw-r--r--pt-br/pythonlegacy-pt.html.markdown509
-rw-r--r--python.html.markdown969
-rw-r--r--python3.html.markdown1042
-rw-r--r--pythonlegacy.html.markdown827
-rw-r--r--ro-ro/pythonlegacy-ro.html.markdown (renamed from ro-ro/python-ro.html.markdown)4
-rw-r--r--ru-ru/python-ru.html.markdown224
-rw-r--r--ru-ru/pythonlegacy-ru.html.markdown (renamed from ru-ru/python3-ru.html.markdown)226
-rw-r--r--tr-tr/python-tr.html.markdown812
-rw-r--r--tr-tr/python3-tr.html.markdown640
-rw-r--r--tr-tr/pythonlegacy-tr.html.markdown502
-rw-r--r--uk-ua/pythonlegacy-ua.html.markdown (renamed from uk-ua/python-ua.html.markdown)4
-rw-r--r--vi-vn/python-vi.html.markdown (renamed from vi-vn/python3-vi.html.markdown)6
-rw-r--r--zh-cn/python-cn.html.markdown626
-rw-r--r--zh-cn/python3-cn.html.markdown632
-rw-r--r--zh-cn/pythonlegacy-cn.html.markdown476
-rw-r--r--zh-tw/pythonlegacy-tw.html.markdown (renamed from zh-tw/python-tw.html.markdown)6
36 files changed, 8303 insertions, 8303 deletions
diff --git a/ar-ar/python3-ar.html.markdown b/ar-ar/python-ar.html.markdown
index e1a12690..f89c2f25 100644
--- a/ar-ar/python3-ar.html.markdown
+++ b/ar-ar/python-ar.html.markdown
@@ -1,5 +1,5 @@
---
-language: python3
+language: Python
contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
- ["Steven Basart", "http://github.com/xksteven"]
@@ -11,7 +11,7 @@ contributors:
translators:
- ["Ahmad Hegazy", "https://github.com/ahegazy"]
lang: ar-ar
-filename: learnpython3-ar.py
+filename: learnpython-ar.py
---
لقد أُنشئت لغة البايثون بواسطة جايدو ڤان روسم في بداية التسعينات. هي الأن أحد أشهر اللغات الموجودة.
@@ -19,7 +19,7 @@ filename: learnpython3-ar.py
ردود أفعالكم عن المقال مُقدرة بشدة. يمكنكم التواصل مع الكاتب الاساسي من خلال [@louiedinh](http://twitter.com/louiedinh) أو louiedinh [at] [google's email service]
-ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/python/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم
+ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/pythonlegacy/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم
```python
diff --git a/cs-cz/python3.html.markdown b/cs-cz/python.html.markdown
index bd3690a8..7086ec5f 100644
--- a/cs-cz/python3.html.markdown
+++ b/cs-cz/python.html.markdown
@@ -17,7 +17,7 @@ Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustit
Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] anglicky,
autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo ja [at] tbedrich.cz
-Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/).
+Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/pythonlegacy/).
```python
diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown
index ee77683e..9eebff41 100644
--- a/de-de/python-de.html.markdown
+++ b/de-de/python-de.html.markdown
@@ -1,9 +1,10 @@
---
-language: python
+language: Python
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
translators:
- ["kultprok", "http:/www.kulturproktologie.de"]
+ - ["matthiaskern", "https://github.com/matthiaskern"]
filename: learnpython-de.py
lang: de-de
---
@@ -11,13 +12,15 @@ lang: de-de
Anmerkungen des ursprünglichen Autors:
Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode.
-Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]
+Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service].
-Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber auf Python 2.x anwendbar sein. Haltet Ausschau nach einem Rundgang durch Python 3, der bald erscheinen soll.
+Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/pythonlegacy/) weiter.
```python
+
# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz)
-""" Mehrzeilige Strings werden mit
+
+""" Mehrzeilige Strings werden mit
drei '-Zeichen geschrieben und werden
oft als Kommentare genutzt.
"""
@@ -33,15 +36,24 @@ Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber au
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
-35 / 5 #=> 7
-# Division ist ein wenig kniffliger. Ganze Zahlen werden ohne Rest dividiert
-# und das Ergebnis wird automatisch abgerundet.
-5 / 2 #=> 2
+# Außer Division, welche automatisch Gleitkommazahlen zurückgibt
+35 / 5 # => 7.0
+
+# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden.
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche
+3 * 2.0 # => 6.0
-# Um das zu ändern, müssen wir Gleitkommazahlen einführen und benutzen
-2.0 # Das ist eine Gleitkommazahl
-11.0 / 4.0 #=> 2.75 Ahhh...schon besser
+# Der Rest einer Division
+7 % 3 # => 1
+
+# Potenz
+2**4 # => 16
# Rangfolge wird mit Klammern erzwungen
(1 + 3) * 2 #=> 8
@@ -54,6 +66,18 @@ False
not True #=> False
not False #=> True
+# Boolesche Operatoren
+# Hinweis: "and" und "or" müssen klein geschrieben werden
+True and False #=> False
+False or True #=> True
+
+# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
# Gleichheit ist ==
1 == 1 #=> True
2 == 1 #=> False
@@ -76,37 +100,45 @@ not False #=> True
"Das ist ein String."
'Das ist auch ein String.'
-# Strings können addiert werden!
-"Hello " + "world!" #=> "Hello world!"
+# Strings können auch addiert werden! Vermeide dies aber lieber.
+"Hallo " + "Welt!" #=> "Hallo Welt!"
+# Strings können ohne "+" addiert werden
+"Hallo " "welt!" # => "Hallo Welt!"
# Ein String kann wie eine Liste von Zeichen verwendet werden
"Das ist ein String"[0] #=> 'D'
-# Mit % können Strings formatiert werden, etwa so:
-"%s können %s werden" % ("Strings", "interpoliert")
+# .format kann Strings formatieren
+"{} können {} werden".format("Strings", "formatiert")
+
+# Schneller geht das mit Wiederholungen
+"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat")
+#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat"
-# Ein modernerer Weg, um Strings zu formatieren, ist die format-Methode.
-# Diese Methode wird bevorzugt
-"{0} können {1} werden".format("Strings", "formatiert")
# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen.
"{name} will {food} essen".format(name="Bob", food="Lasagne")
+#=> "Bob will Lasagne kochen"
+
+#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden:
+"%s können %s werden" % ("Strings", "interpoliert")
+
# None ist ein Objekt
None #=> None
# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen
-# Benutzt stattdessen `is`
+# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität
"etc" is None #=> False
None is None #=> True
-# Der 'is'-Operator testet Objektidentität. Das ist nicht
-# sehr nützlich, wenn wir mit primitiven Datentypen arbeiten, aber
-# sehr nützlich bei Objekten.
+
# None, 0, und leere Strings/Listen werden alle als False bewertet.
# Alle anderen Werte sind True
-0 == False #=> True
-"" == False #=> True
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
####################################################
@@ -114,20 +146,16 @@ None is None #=> True
####################################################
# Textausgabe ist sehr einfach
-print "Ich bin Python. Schön, dich kennenzulernen!"
-
+print("Ich bin Python. Schön, dich kennenzulernen!")
# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren.
some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm
some_var #=> 5
-# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus.
+# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus.
# Unter "Kontrollstruktur" kann noch mehr über
# Ausnahmebehandlung erfahren werden.
-some_other_var # Löst einen NameError aus
-
-# if kann als Ausdruck verwendet werden
-"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+some_unknown_var # Löst einen NameError aus
# Listen speichern Sequenzen
li = []
@@ -150,7 +178,7 @@ li[0] #=> 1
li[-1] #=> 3
# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError
-li[4] # Raises an IndexError
+li[4] # Verursacht einen IndexError
# Wir können uns Ranges mit Slice-Syntax ansehen
li[1:3] #=> [2, 4]
@@ -158,6 +186,12 @@ li[1:3] #=> [2, 4]
li[2:] #=> [4, 3]
# Das Ende auslassen
li[:3] #=> [1, 2, 4]
+# Jeden Zweiten Eintrag auswählen
+li[::2] # =>[1, 4]
+# Eine umgekehrte Kopie zurückgeben
+li[::-1] # => [3, 4, 2, 1]
+# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich
+# li[Start:Ende:Schritt]
# Ein bestimmtes Element mit del aus der Liste entfernen
del li[2] # li ist jetzt [1, 2, 3]
@@ -191,10 +225,10 @@ a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3
# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen
d, e, f = 4, 5, 6
# Es ist kinderleicht zwei Werte zu tauschen
-e, d = d, e # d is now 5 and e is now 4
+e, d = d, e # d ist nun 5 und e ist nun 4
-# Dictionarys (Wörterbucher) speichern Key-Value-Paare
+# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare
empty_dict = {}
# Hier ein gefülltes Wörterbuch
filled_dict = {"one": 1, "two": 2, "three": 3}
@@ -203,15 +237,15 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["one"] #=> 1
# So holen wir alle Keys (Schlüssel) als Liste
-filled_dict.keys() #=> ["three", "two", "one"]
+list(filled_dict.keys()) #=> ["three", "two", "one"]
# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert.
# Einzelne Resultate können anders angeordnet sein.
# Alle Values (Werte) als Liste
-filled_dict.values() #=> [3, 2, 1]
+list(filled_dict.values()) #=> [3, 2, 1]
# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln.
-# Das Vorhandensein eines Schlüssels im Wörterbuch mit in prüfen
+# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen
"one" in filled_dict #=> True
1 in filled_dict #=> False
@@ -229,17 +263,24 @@ filled_dict.get("four", 4) #=> 4
filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt
filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5
+# Einträge zu einem Wörterbuch hinzufügen
+filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen
+
+# Schlüssel von einem Wörterbuch entfernen
+del filled_dict["one"] # Entfert den Schlüssel "one"
+
# Sets speichern Mengen
empty_set = set()
# Initialisieren wir ein Set mit ein paar Werten
-some_set = set([1,2,2,3,4]) # some_set ist jetzt set([1, 2, 3, 4])
+some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4}
-# Seit Python 2.7 kann {} benutzt werden, um ein Set zu erstellen
-filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+# Neue Variablen können einer Menge gleichgesetzt werden
+filled_set = some_set
# Mehr Elemente hinzufügen
-filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5}
# Schnittmengen werden mit & gebildet
other_set = {3, 4, 5, 6}
@@ -257,7 +298,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
####################################################
-## 3. Kontrollstruktur
+## 3. Kontrollstruktur und Iteratoren
####################################################
# Erstellen wir mal eine Variable
@@ -266,11 +307,11 @@ some_var = 5
# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig!
# gibt "some_var ist kleiner als 10" aus
if some_var > 10:
- print "some_var ist viel größer als 10."
+ print("some_var ist viel größer als 10.")
elif some_var < 10: # Dieser elif-Absatz ist optional.
- print "some_var ist kleiner als 10."
+ print("some_var ist kleiner als 10.")
else: # Das hier ist auch optional.
- print "some_var ist tatsächlich 10."
+ print("some_var ist tatsächlich 10.")
"""
@@ -281,9 +322,9 @@ Ausgabe:
maus ist ein Säugetier
"""
for animal in ["hund", "katze", "maus"]:
- # Wir können Strings mit % formatieren
- print "%s ist ein Säugetier" % animal
-
+ # Wir können Strings mit format() formatieren
+ print("{} ist ein Säugetier".format(animal))
+
"""
`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder
Ausgabe:
@@ -293,7 +334,18 @@ Ausgabe:
3
"""
for i in range(4):
- print i
+ print(i)
+
+"""
+"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus
+Ausgabe:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
"""
While-Schleifen laufen, bis eine Bedingung erfüllt ist.
@@ -305,17 +357,59 @@ Ausgabe:
"""
x = 0
while x < 4:
- print x
+ print(x)
x += 1 # Kurzform für x = x + 1
# Ausnahmebehandlung mit einem try/except-Block
-
-# Funktioniert in Python 2.6 und höher:
try:
# Mit raise wird ein Fehler ausgegeben
raise IndexError("Das hier ist ein Index-Fehler")
except IndexError as e:
pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären.
+except (TypeError, NameError):
+ pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich.
+else: # Optional, hinter allen except-Blöcken
+ print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind
+finally: # Wird immer ausgeführt
+ print("Hier können wir Ressourcen aufräumen")
+
+# alternativ zu einem try/finally Block um Aufzuräumen:
+with open("meineDatei.txt") as f:
+ for line in f:
+ print(line)
+
+# Python bietet ein fundamentales Konzept der Iteration.
+# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable".
+# Die range Methode gibt ein solches Objekt aus.
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt.
+
+# Über dieses können wir auch iterieren
+for i in our_iterable:
+ print(i) # Gibt one, two, three aus
+
+# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben
+our_iterable[1] # TypeError
+
+# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft.
+our_iterator = iter(our_iterable)
+
+# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen.
+# Das jeweils nächste Objekt bekommen wir mit "next()"
+next(our_iterator) #=> "one"
+
+# Es hält den vorherigen Status
+next(our_iterator) #=> "two"
+next(our_iterator) #=> "three"
+
+# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück
+next(our_iterator) # Gibt StopIteration aus
+
+# Alle Elemente können mit "list()" ausgegeben werden
+list(filled_dict.keys()) #=> ["one", "two", "three"]
+
####################################################
@@ -324,7 +418,7 @@ except IndexError as e:
# Mit def neue Funktionen erstellen
def add(x, y):
- print "x ist %s und y ist %s" % (x, y)
+ print("x ist %s und y ist %s" % (x, y))
return x + y # Werte werden mit return zurückgegeben
# Funktionen mit Parametern aufrufen
@@ -348,10 +442,10 @@ def keyword_args(**kwargs):
# Rufen wir es mal auf, um zu sehen, was passiert
keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
-# Wir können beides gleichzeitig machem, wenn wir wollen
+# Wir können beides gleichzeitig machen, wenn wir wollen
def all_the_args(*args, **kwargs):
- print args
- print kwargs
+ print(args)
+ print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) Ausgabe:
(1, 2)
@@ -366,6 +460,25 @@ all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4)
all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4)
all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4)
+
+# Anwendungsbereich von Funktionen
+x = 5
+
+def setX(num):
+ # lokale Variable x ist nicht die globale Variable x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # globale Variable x ist jetzt 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
# Python hat First-Class-Funktionen
def create_adder(x):
def adder(y):
@@ -386,72 +499,24 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
-
####################################################
-## 5. Module
+## 5. Klassen
####################################################
-# Wir können Module importieren
-import math
-print math.sqrt(16) #=> 4.0
-
-# Wir können auch nur spezielle Funktionen eines Moduls importieren
-from math import ceil, floor
-print ceil(3.7) #=> 4.0
-print floor(3.7) #=> 3.0
-
-# Wir können auch alle Funktionen eines Moduls importieren
-# Warnung: Dies wird nicht empfohlen
-from math import *
-
-# Wir können Modulnamen abkürzen
-import math as m
-math.sqrt(16) == m.sqrt(16) #=> True
-
-# Module sind in Python nur gewöhnliche Dateien. Wir
-# können unsere eigenen schreiben und importieren. Der Name des
-# Moduls ist der Dateiname.
-
-# Wir können herausfinden, welche Funktionen und Attribute in einem
-# Modul definiert sind.
-import math
-dir(math)
-
-# Wenn Sie ein Python-Skript namens math.py im selben Ordner
-# wie Ihr aktuelles Skript haben, wird die Datei math.py
-# anstelle des integrierten Python-Moduls geladen.
-# Dies geschieht, weil der lokale Ordner Vorrang
-# vor den in Python integrierten Bibliotheken hat.
-
-
-####################################################
-## 6. Klassen
-####################################################
-
-# Wir verwenden das Schlüsselwort "class" um eine Klasse zu erzeugen.
+# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten.
class Human(object):
# Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt
species = "H. sapiens"
- # Ein simpler Konstruktor, wird aufgerufen, wenn diese Klasse instanziiert wird.
- # Beachten Sie, dass die doppelten vorangestellten und nachgestellten
- # Unterstriche Objekte oder Attribute bezeichnen, die von Python verwendet werden,
- # aber in benutzergesteuerten Namespaces leben.
- # Methoden (oder Objekte oder Attribute) wie: __init__, __str__, __repr__ usw.
- # werden als Sondermethoden (oder manchmal als Dundermethoden bezeichnet) bezeichnet.
- # Sie sollten solche Namen nicht selbst erfinden.
+ # Ein simpler Konstruktor
def __init__(self, name):
# Wir weisen das Argument name dem name-Attribut der Instanz zu
self.name = name
- # Eine Instanzmethode. Alle Methoden erhalten "self" als erstes Argument.
+ # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument.
def say(self, msg):
- return "%s: %s" % (self.name, msg)
-
- # Eine weitere Instanzmethode
- def sing(self):
- return 'yo... yo... microphone check... one two... one two...'
+ return "{name}: {message}".format(name=self.name, message=msg)
# Eine Klassenmethode wird von allen Instanzen geteilt.
# Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen
@@ -464,269 +529,89 @@ class Human(object):
def grunt():
return "*grunt*"
- # Eine Eigenschaft (Property) ist wie ein Getter.
-    # Es verwandelt die Methode age() in ein schreibgeschütztes Attribut mit demselben Namen.
-    # Es ist jedoch nicht nötig, triviale Getter und Setter in Python zu schreiben.
- @property
- def age(self):
- return self._age
-
-    # Damit kann die Eigenschaft festgelegt werden
- @age.setter
- def age(self, age):
- self._age = age
-
-    # Damit kann die Eigenschaft gelöscht werden
- @age.deleter
- def age(self):
- del self._age
-
-# Wenn ein Python-Interpreter eine Quelldatei liest, führt er den gesamten Code aus.
-# Diese __name__-Prüfung stellt sicher, dass dieser Codeblock nur ausgeführt wird,
-# wenn dieses Modul das Hauptprogramm ist.
-if __name__ == '__main__':
- # Eine Instanz einer Klasse erstellen
- i = Human(name="Ian")
- i.say("hi") # "Ian: hi"
- j = Human("Joel")
- j.say("hello") # "Joel: hello"
- # i und j sind Instanzen des Typs Mensch, oder anders ausgedrückt: Sie sind Objekte des Menschen
-
- # Rufen wir unsere Klassenmethode auf
- i.say(i.get_species()) # "Ian: H. sapiens"
-
- # Ändern wir das gemeinsame Attribut
- Human.species = "H. neanderthalensis"
- i.say(i.get_species()) # => "Ian: H. neanderthalensis"
- j.say(j.get_species()) # => "Joel: H. neanderthalensis"
-
- # Aufruf der statischen Methode
- print(Human.grunt()) # => "*grunt*"
-
- # Kann keine statische Methode mit Instanz des Objekts aufrufen,
- # da i.grunt () automatisch "self" (das Objekt i) als Argument verwendet
- print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
-
- # Die Eigenschaft für diese Instanz aktualisieren
- i.age = 42
- # die Eigenschaft auslesen
- i.say(i.age) # => "Ian: 42"
- j.say(j.age) # => "Joel: 0"
- # die Eigenschaft löschen
- del i.age
- # i.age # => würde einen AttributeError werfen
-
-####################################################
-## 6.1 Inheritance
-####################################################
-
-# Vererbung ermöglicht die Definition neuer untergeordneter Klassen,
-# die Methoden und Variablen von ihrer übergeordneten Klasse erben.
-
-# Wenn Sie die oben definierte Human-Klasse als Basis- oder Elternklasse verwenden,
-# können Sie eine untergeordnete Klasse, Superhero, definieren, die die Klassenvariablen
-# wie "species", "name" und "age" sowie Methoden wie "sing" und "grunzen" aus der Klasse Human erbt.
-# Die Untergeordnete Klasse kann aber auch eigene Eigenschaften haben.
-
-# Um von der Modularisierung per Datei zu profitieren, können Sie die Klassen
-# in ihren eigenen Dateien platzieren, z. B. human.py
-
-# Um Funktionen aus anderen Dateien zu importieren, verwenden Sie das folgende Format
-# from "Dateiname-ohne-Erweiterung" impotr "Funktion-oder-Klasse"
-
-from human import Human
-
-# Geben Sie die übergeordnete(n) Klasse(n) als Parameter für die Klassendefinition an
-class Superhero(Human):
-
- # Wenn die untergeordnete Klasse alle Definitionen des übergeordneten Elements
- # ohne Änderungen erben soll, können Sie einfach das Schlüsselwort "pass"
- # (und nichts anderes) verwenden. In diesem Fall wird jedoch auskommentiert,
- # um eine eindeutige untergeordnete Klasse zuzulassen:
- # pass
-
- # Kindklassen können die Attribute ihrer Eltern überschreiben
- species = 'Superhuman'
-
- # Kinder erben automatisch den Konstruktor ihrer übergeordneten Klasse
- # einschließlich ihrer Argumente, können aber auch zusätzliche Argumente oder
- # Definitionen definieren und ihre Methoden zB den Klassenkonstruktor überschreiben.
- # Dieser Konstruktor erbt das Argument "name" von der Klasse "Human" und
- # fügt die Argumente "superpowers" und "movie" hinzu:
- def __init__(self, name, movie=False,
- superpowers=["super strength", "bulletproofing"]):
-
- # zusätzliche Klassenattribute hinzufügen:
- self.fictional = True
- self.movie = movie
- # Beachten Sie die veränderlichen Standardwerte, da die Standardwerte gemeinsam genutzt werden
- self.superpowers = superpowers
-
- # Mit der Funktion "super" können Sie auf die Methoden der übergeordneten Klasse
- # zugreifen, die vom untergeordneten Objekt überschrieben werden,
- # in diesem Fall die Methode __init__.
-        # Dies ruft den Konstruktor der übergeordneten Klasse auf:
- super().__init__(name)
-
- # überschreiben der "sing" Methode
- def sing(self):
- return 'Dun, dun, DUN!'
-
- # eine zusätzliche Instanzmethode hinzufügen
- def boast(self):
- for power in self.superpowers:
- print("I wield the power of {pow}!".format(pow=power))
-
-if __name__ == '__main__':
- sup = Superhero(name="Tick")
-
- # Instanztypprüfungen
- if isinstance(sup, Human):
- print('I am human')
- if type(sup) is Superhero:
- print('I am a superhero')
-
- # Die Reihenfolge der Methodenauflösung (MRO = Method Resolution Order) anzeigen, die sowohl von getattr() als auch von super() verwendet wird.
-    # Dieses Attribut ist dynamisch und kann aktualisiert werden.
- print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
- # => <class 'human.Human'>, <class 'object'>)
-
- # Ruft die übergeordnete Methode auf, verwendet jedoch das eigene Klassenattribut
- print(sup.get_species()) # => Superhuman
-
- # Ruft die überschriebene Methode auf
- print(sup.sing()) # => Dun, dun, DUN!
-
- # Ruft die Methode von Human auf
- sup.say('Spoon') # => Tick: Spoon
-
- # Aufruf einer Methode, die nur in Superhero existiert
- sup.boast() # => I wield the power of super strength!
- # => I wield the power of bulletproofing!
-
- # Vererbtes Klassenattribut
- sup.age = 31
- print(sup.age) # => 31
-
- # Attribut, das nur in Superhero existiert
- print('Am I Oscar eligible? ' + str(sup.movie))
+
+# Eine Instanz einer Klasse erstellen
+i = Human(name="Ian")
+print(i.say("hi")) # gibt "Ian: hi" aus
+
+j = Human("Joel")
+print(j.say("hello")) #gibt "Joel: hello" aus
+
+# Rufen wir mal unsere Klassenmethode auf
+i.get_species() #=> "H. sapiens"
+
+# Ändern wir mal das gemeinsame Attribut
+Human.species = "H. neanderthalensis"
+i.get_species() #=> "H. neanderthalensis"
+j.get_species() #=> "H. neanderthalensis"
+
+# Aufruf der statischen Methode
+Human.grunt() #=> "*grunt*"
+
####################################################
-## 6.2 Multiple Inheritance
+## 6. Module
####################################################
-# Eine weitere Klassendefinition
-# bat.py
+# Wir können Module importieren
+import math
+print(math.sqrt(16)) #=> 4.0
-class Bat:
+# Wir können auch nur spezielle Funktionen eines Moduls importieren
+from math import ceil, floor
+print(ceil(3.7)) #=> 4.0
+print(floor(3.7)) #=> 3.0
- species = 'Baty'
+# Wir können auch alle Funktionen eines Moduls importieren
+# Warnung: Dies wird nicht empfohlen
+from math import *
- def __init__(self, can_fly=True):
- self.fly = can_fly
+# Wir können Modulnamen abkürzen
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Module sind in Python nur gewöhnliche Dateien. Wir
+# können unsere eigenen schreiben und importieren. Der Name des
+# Moduls ist der Dateiname.
+
+# Wir können auch die Funktionen und Attribute eines
+# Moduls herausfinden.
+import math
+dir(math)
- # This class also has a say method
- def say(self, msg):
- msg = '... ... ...'
- return msg
- # And its own method as well
- def sonar(self):
- return '))) ... ((('
-
-if __name__ == '__main__':
- b = Bat()
- print(b.say('hello'))
- print(b.fly)
-
-# Und noch eine andere Klassendefinition, die von Superhero und Bat erbt
-# superhero.py
-from superhero import Superhero
-from bat import Bat
-
-# Definieren Sie Batman als eine Kindklasse, das von Superheld und Bat erbt
-class Batman(Superhero, Bat):
-
- def __init__(self, *args, **kwargs):
- # In der Regel müssen Sie super aufrufen, um Attribute zu erben:
- # super (Batman, selbst) .__ init__ (* args, ** kwargs)
- # Allerdings handelt es sich hier um Mehrfachvererbung, und super()
- # funktioniert nur mit der nächsten Basisklasse in der MRO-Liste.
- # Stattdessen rufen wir explizit __init__ für alle Vorfahren auf.
- # Die Verwendung von *args und **kwargs ermöglicht die saubere Übergabe von
- # Argumenten, wobei jedes übergeordnete Element eine Schicht der Zwiebel "abschält".
- Superhero.__init__(self, 'anonymous', movie=True,
- superpowers=['Wealthy'], *args, **kwargs)
- Bat.__init__(self, *args, can_fly=False, **kwargs)
- # überschreibt den Wert für das Namensattribut
- self.name = 'Sad Affleck'
-
- def sing(self):
- return 'nan nan nan nan nan batman!'
-
-if __name__ == '__main__':
- sup = Batman()
-
- # Die Reihenfolge der Methodenauflösung (MRO = Method Resolution Order) anzeigen,
- # die sowohl von getattr() als auch von super() verwendet wird.
- # Dieses Attribut ist dynamisch und kann aktualisiert werden.
- print(Batman.__mro__) # => (<class '__main__.Batman'>,
- # => <class 'superhero.Superhero'>,
- # => <class 'human.Human'>,
- # => <class 'bat.Bat'>, <class 'object'>)
-
- # Ruft die übergeordnete Methode auf, verwendet jedoch das eigene Klassenattribut
- print(sup.get_species()) # => Superhuman
-
- # Ruft die überschriebene Methode auf
- print(sup.sing()) # => nan nan nan nan nan batman!
-
- # Ruft die Methode von Human auf, weil die Reihenfolge der Vererbung wichtig ist
- sup.say('I agree') # => Sad Affleck: I agree
-
- # Aufrufmethode, die nur im 2. Vorfahren existiert
- print(sup.sonar()) # => ))) ... (((
-
- # Vererbtes Klassenattribut
- sup.age = 100
- print(sup.age) # => 100
-
- # Vererbtes Attribut vom 2. Vorfahren, dessen Standardwert überschrieben wurde.
- print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
-
-
####################################################
-## 7. Fortgeschrittenes
-####################################################
-
-# Generatoren helfen Ihnen, lazy Code zu erstellen.
+## 7. Fortgeschritten
+####################################################
+
+# Generatoren helfen um Code schnell und einfach zu schreiben
def double_numbers(iterable):
for i in iterable:
yield i + i
-
-# Generatoren sind speichereffizient, da sie nur die Daten laden,
-# die zur Verarbeitung des nächsten Werts in der iterierbaren Komponente
-# erforderlich sind. Dadurch können sie ansonsten unzulässig große Wertebereiche ausführen.
-# HINWEIS: `range` ersetzt` xrange` in Python 3.
-for i in double_numbers(range(1, 900000000)): # `range` ist ein Generator.
+
+# Ein Generator erschafft Werte spontan
+# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen.
+# iteration. Das heißt, Werte größer als 15 werden nicht behandelt.
+# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000
+# würde das sehr viel Zeit in Anspruch nehmen.
+# Wenn wir eine variable mit einem Namen erschaffen wollen, das
+# normalerweise mit einem Python - Schlüsselwort kollidieren würde,
+# benutzen wir einen Unterstrich nach dem Wort.
+range_ = range(1, 900000000)
+# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt
+for i in double_numbers(range_):
print(i)
if i >= 30:
break
-# Genauso wie Sie ein 'list comprehension' (Listen Abstraktion) erstellen können, können Sie auch 'generator comprehension' (Generator Abstraktion) erstellen.
-values = (-x for x in [1,2,3,4,5])
-for x in values:
- print(x) # prints -1 -2 -3 -4 -5 to console/terminal
-
-# Sie können eine Generator Abstraktion auch direkt in eine Liste umwandeln (casten).
-values = (-x for x in [1,2,3,4,5])
-gen_to_list = list(values)
-print(gen_to_list) # => [-1, -2, -3, -4, -5]
-
-# Decorators
-# In diesem Beispiel umschliesst "beg" "say". Wenn say_please True ist, wird die zurückgegebene Nachricht geändert.
+
+# Dekoratoren
+# In diesem Beispiel die Methode beg umwickelt say
+# Beim Aufruf von beg, say wird aufgerufen
+# Falls say_please true ist, ändert sich die ausgegebene Nachricht
from functools import wraps
+
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
@@ -737,13 +622,14 @@ def beg(target_function):
return wrapper
+
@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please
-print(say()) # Can you buy me a beer?
+print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
@@ -752,15 +638,18 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
### Kostenlos online (Englisch)
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2.6/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [Python Course](http://www.python-course.eu/index.php)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
### Totholz (Englisch)
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
-
diff --git a/de-de/python3-de.html.markdown b/de-de/python3-de.html.markdown
deleted file mode 100644
index 4ef997a1..00000000
--- a/de-de/python3-de.html.markdown
+++ /dev/null
@@ -1,655 +0,0 @@
----
-language: python3
-contributors:
- - ["Louie Dinh", "http://ldinh.ca"]
-translators:
- - ["kultprok", "http:/www.kulturproktologie.de"]
- - ["matthiaskern", "https://github.com/matthiaskern"]
-filename: learnpython3-de.py
-lang: de-de
----
-
-Anmerkungen des ursprünglichen Autors:
-Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode.
-
-Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service].
-
-Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter.
-
-```python
-
-# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz)
-
-""" Mehrzeilige Strings werden mit
- drei '-Zeichen geschrieben und werden
- oft als Kommentare genutzt.
-"""
-
-####################################################
-## 1. Primitive Datentypen und Operatoren
-####################################################
-
-# Die Zahlen
-3 #=> 3
-
-# Mathematik funktioniert so, wie man das erwartet
-1 + 1 #=> 2
-8 - 1 #=> 7
-10 * 2 #=> 20
-
-# Außer Division, welche automatisch Gleitkommazahlen zurückgibt
-35 / 5 # => 7.0
-
-# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden.
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # works on floats too
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
-
-# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche
-3 * 2.0 # => 6.0
-
-# Der Rest einer Division
-7 % 3 # => 1
-
-# Potenz
-2**4 # => 16
-
-# Rangfolge wird mit Klammern erzwungen
-(1 + 3) * 2 #=> 8
-
-# Boolesche Ausdrücke sind primitive Datentypen
-True
-False
-
-# Mit not wird negiert
-not True #=> False
-not False #=> True
-
-# Boolesche Operatoren
-# Hinweis: "and" und "or" müssen klein geschrieben werden
-True and False #=> False
-False or True #=> True
-
-# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
-
-# Gleichheit ist ==
-1 == 1 #=> True
-2 == 1 #=> False
-
-# Ungleichheit ist !=
-1 != 1 #=> False
-2 != 1 #=> True
-
-# Ein paar weitere Vergleiche
-1 < 10 #=> True
-1 > 10 #=> False
-2 <= 2 #=> True
-2 >= 2 #=> True
-
-# Vergleiche können verknüpft werden!
-1 < 2 < 3 #=> True
-2 < 3 < 2 #=> False
-
-# Strings werden mit " oder ' gebildet
-"Das ist ein String."
-'Das ist auch ein String.'
-
-# Strings können auch addiert werden! Vermeide dies aber lieber.
-"Hallo " + "Welt!" #=> "Hallo Welt!"
-# Strings können ohne "+" addiert werden
-"Hallo " "welt!" # => "Hallo Welt!"
-
-# Ein String kann wie eine Liste von Zeichen verwendet werden
-"Das ist ein String"[0] #=> 'D'
-
-# .format kann Strings formatieren
-"{} können {} werden".format("Strings", "formatiert")
-
-# Schneller geht das mit Wiederholungen
-"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat")
-#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat"
-
-# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen.
-"{name} will {food} essen".format(name="Bob", food="Lasagne")
-#=> "Bob will Lasagne kochen"
-
-#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden:
-"%s können %s werden" % ("Strings", "interpoliert")
-
-
-# None ist ein Objekt
-None #=> None
-
-# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen
-# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität
-"etc" is None #=> False
-None is None #=> True
-
-
-
-# None, 0, und leere Strings/Listen werden alle als False bewertet.
-# Alle anderen Werte sind True
-bool(0) # => False
-bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
-
-
-####################################################
-## 2. Variablen und Collections
-####################################################
-
-# Textausgabe ist sehr einfach
-print("Ich bin Python. Schön, dich kennenzulernen!")
-
-# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren.
-some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm
-some_var #=> 5
-
-# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus.
-# Unter "Kontrollstruktur" kann noch mehr über
-# Ausnahmebehandlung erfahren werden.
-some_unknown_var # Löst einen NameError aus
-
-# Listen speichern Sequenzen
-li = []
-# Wir können mit einer bereits gefüllten Liste anfangen
-other_li = [4, 5, 6]
-
-# append fügt Daten am Ende der Liste ein
-li.append(1) #li ist jetzt [1]
-li.append(2) #li ist jetzt [1, 2]
-li.append(4) #li ist jetzt [1, 2, 4]
-li.append(3) #li ist jetzt [1, 2, 4, 3]
-# Vom Ende der Liste mit pop entfernen
-li.pop() #=> 3 und li ist jetzt [1, 2, 4]
-# und dann wieder hinzufügen
-li.append(3) # li ist jetzt wieder [1, 2, 4, 3].
-
-# Greife auf Listen wie auf Arrays zu
-li[0] #=> 1
-# Das letzte Element ansehen
-li[-1] #=> 3
-
-# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError
-li[4] # Verursacht einen IndexError
-
-# Wir können uns Ranges mit Slice-Syntax ansehen
-li[1:3] #=> [2, 4]
-# Den Anfang auslassen
-li[2:] #=> [4, 3]
-# Das Ende auslassen
-li[:3] #=> [1, 2, 4]
-# Jeden Zweiten Eintrag auswählen
-li[::2] # =>[1, 4]
-# Eine umgekehrte Kopie zurückgeben
-li[::-1] # => [3, 4, 2, 1]
-# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich
-# li[Start:Ende:Schritt]
-
-# Ein bestimmtes Element mit del aus der Liste entfernen
-del li[2] # li ist jetzt [1, 2, 3]
-
-# Listen können addiert werden
-li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen
-
-# Listen mit extend verknüpfen
-li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6]
-
-# Mit in auf Existenz eines Elements prüfen
-1 in li #=> True
-
-# Die Länge der Liste mit len ermitteln
-len(li) #=> 6
-
-
-# Tupel sind wie Listen, nur unveränderlich.
-tup = (1, 2, 3)
-tup[0] #=> 1
-tup[0] = 3 # Löst einen TypeError aus
-
-# Wir können all diese Listen-Dinge auch mit Tupeln anstellen
-len(tup) #=> 3
-tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
-tup[:2] #=> (1, 2)
-2 in tup #=> True
-
-# Wir können Tupel (oder Listen) in Variablen entpacken
-a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3
-# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen
-d, e, f = 4, 5, 6
-# Es ist kinderleicht zwei Werte zu tauschen
-e, d = d, e # d ist nun 5 und e ist nun 4
-
-
-# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare
-empty_dict = {}
-# Hier ein gefülltes Wörterbuch
-filled_dict = {"one": 1, "two": 2, "three": 3}
-
-# Wir können Einträge mit [] nachschlagen
-filled_dict["one"] #=> 1
-
-# So holen wir alle Keys (Schlüssel) als Liste
-list(filled_dict.keys()) #=> ["three", "two", "one"]
-# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert.
-# Einzelne Resultate können anders angeordnet sein.
-
-# Alle Values (Werte) als Liste
-list(filled_dict.values()) #=> [3, 2, 1]
-# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln.
-
-# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen
-"one" in filled_dict #=> True
-1 in filled_dict #=> False
-
-# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus
-filled_dict["four"] # KeyError
-
-# Mit der get-Methode verhindern wir das
-filled_dict.get("one") #=> 1
-filled_dict.get("four") #=> None
-# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt
-filled_dict.get("one", 4) #=> 1
-filled_dict.get("four", 4) #=> 4
-
-# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen
-filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt
-filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5
-
-# Einträge zu einem Wörterbuch hinzufügen
-filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
-#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen
-
-# Schlüssel von einem Wörterbuch entfernen
-del filled_dict["one"] # Entfert den Schlüssel "one"
-
-
-# Sets speichern Mengen
-empty_set = set()
-# Initialisieren wir ein Set mit ein paar Werten
-some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4}
-
-# Neue Variablen können einer Menge gleichgesetzt werden
-filled_set = some_set
-
-# Mehr Elemente hinzufügen
-filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5}
-
-# Schnittmengen werden mit & gebildet
-other_set = {3, 4, 5, 6}
-filled_set & other_set #=> {3, 4, 5}
-
-# Mengen werden mit | vereinigt
-filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
-
-# Die Differenz einer Menge mit - bilden
-{1,2,3,4} - {2,3,5} #=> {1, 4}
-
-# Auf Vorhandensein von Elementen mit in prüfen
-2 in filled_set #=> True
-10 in filled_set #=> False
-
-
-####################################################
-## 3. Kontrollstruktur und Iteratoren
-####################################################
-
-# Erstellen wir mal eine Variable
-some_var = 5
-
-# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig!
-# gibt "some_var ist kleiner als 10" aus
-if some_var > 10:
- print("some_var ist viel größer als 10.")
-elif some_var < 10: # Dieser elif-Absatz ist optional.
- print("some_var ist kleiner als 10.")
-else: # Das hier ist auch optional.
- print("some_var ist tatsächlich 10.")
-
-
-"""
-For-Schleifen iterieren über Listen
-Ausgabe:
- hund ist ein Säugetier
- katze ist ein Säugetier
- maus ist ein Säugetier
-"""
-for animal in ["hund", "katze", "maus"]:
- # Wir können Strings mit format() formatieren
- print("{} ist ein Säugetier".format(animal))
-
-"""
-`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder
-Ausgabe:
- 0
- 1
- 2
- 3
-"""
-for i in range(4):
- print(i)
-
-"""
-"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus
-Ausgabe:
- 4
- 5
- 6
- 7
-"""
-for i in range(4, 8):
- print(i)
-
-"""
-While-Schleifen laufen, bis eine Bedingung erfüllt ist.
-Ausgabe:
- 0
- 1
- 2
- 3
-"""
-x = 0
-while x < 4:
- print(x)
- x += 1 # Kurzform für x = x + 1
-
-# Ausnahmebehandlung mit einem try/except-Block
-try:
- # Mit raise wird ein Fehler ausgegeben
- raise IndexError("Das hier ist ein Index-Fehler")
-except IndexError as e:
- pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären.
-except (TypeError, NameError):
- pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich.
-else: # Optional, hinter allen except-Blöcken
- print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind
-finally: # Wird immer ausgeführt
- print("Hier können wir Ressourcen aufräumen")
-
-# alternativ zu einem try/finally Block um Aufzuräumen:
-with open("meineDatei.txt") as f:
- for line in f:
- print(line)
-
-# Python bietet ein fundamentales Konzept der Iteration.
-# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable".
-# Die range Methode gibt ein solches Objekt aus.
-
-filled_dict = {"one": 1, "two": 2, "three": 3}
-our_iterable = filled_dict.keys()
-print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt.
-
-# Über dieses können wir auch iterieren
-for i in our_iterable:
- print(i) # Gibt one, two, three aus
-
-# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben
-our_iterable[1] # TypeError
-
-# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft.
-our_iterator = iter(our_iterable)
-
-# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen.
-# Das jeweils nächste Objekt bekommen wir mit "next()"
-next(our_iterator) #=> "one"
-
-# Es hält den vorherigen Status
-next(our_iterator) #=> "two"
-next(our_iterator) #=> "three"
-
-# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück
-next(our_iterator) # Gibt StopIteration aus
-
-# Alle Elemente können mit "list()" ausgegeben werden
-list(filled_dict.keys()) #=> ["one", "two", "three"]
-
-
-
-####################################################
-## 4. Funktionen
-####################################################
-
-# Mit def neue Funktionen erstellen
-def add(x, y):
- print("x ist %s und y ist %s" % (x, y))
- return x + y # Werte werden mit return zurückgegeben
-
-# Funktionen mit Parametern aufrufen
-add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück
-
-# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente
-add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden.
-
-# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren
-def varargs(*args):
- return args
-
-varargs(1, 2, 3) #=> (1,2,3)
-
-
-# Wir können auch Funktionen mit beliebiger Anzahl
-# Schlüsselwort-Argumenten definieren
-def keyword_args(**kwargs):
- return kwargs
-
-# Rufen wir es mal auf, um zu sehen, was passiert
-keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
-
-# Wir können beides gleichzeitig machen, wenn wir wollen
-def all_the_args(*args, **kwargs):
- print(args)
- print(kwargs)
-"""
-all_the_args(1, 2, a=3, b=4) Ausgabe:
- (1, 2)
- {"a": 3, "b": 4}
-"""
-
-# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen!
-# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs.
-args = (1, 2, 3, 4)
-kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4)
-all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4)
-all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4)
-
-
-# Anwendungsbereich von Funktionen
-x = 5
-
-def setX(num):
- # lokale Variable x ist nicht die globale Variable x
- x = num # => 43
- print (x) # => 43
-
-def setGlobalX(num):
- global x
- print (x) # => 5
- x = num # globale Variable x ist jetzt 6
- print (x) # => 6
-
-setX(43)
-setGlobalX(6)
-
-
-# Python hat First-Class-Funktionen
-def create_adder(x):
- def adder(y):
- return x + y
- return adder
-
-add_10 = create_adder(10)
-add_10(3) #=> 13
-
-# Es gibt auch anonyme Funktionen
-(lambda x: x > 2)(3) #=> True
-
-# Es gibt auch Funktionen höherer Ordnung als Built-Ins
-map(add_10, [1,2,3]) #=> [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
-
-# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen
-[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
-
-####################################################
-## 5. Klassen
-####################################################
-
-# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten.
-class Human(object):
-
- # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt
- species = "H. sapiens"
-
- # Ein simpler Konstruktor
- def __init__(self, name):
- # Wir weisen das Argument name dem name-Attribut der Instanz zu
- self.name = name
-
- # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument.
- def say(self, msg):
- return "{name}: {message}".format(name=self.name, message=msg)
-
- # Eine Klassenmethode wird von allen Instanzen geteilt.
- # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen
- @classmethod
- def get_species(cls):
- return cls.species
-
- # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen
- @staticmethod
- def grunt():
- return "*grunt*"
-
-
-# Eine Instanz einer Klasse erstellen
-i = Human(name="Ian")
-print(i.say("hi")) # gibt "Ian: hi" aus
-
-j = Human("Joel")
-print(j.say("hello")) #gibt "Joel: hello" aus
-
-# Rufen wir mal unsere Klassenmethode auf
-i.get_species() #=> "H. sapiens"
-
-# Ändern wir mal das gemeinsame Attribut
-Human.species = "H. neanderthalensis"
-i.get_species() #=> "H. neanderthalensis"
-j.get_species() #=> "H. neanderthalensis"
-
-# Aufruf der statischen Methode
-Human.grunt() #=> "*grunt*"
-
-
-####################################################
-## 6. Module
-####################################################
-
-# Wir können Module importieren
-import math
-print(math.sqrt(16)) #=> 4.0
-
-# Wir können auch nur spezielle Funktionen eines Moduls importieren
-from math import ceil, floor
-print(ceil(3.7)) #=> 4.0
-print(floor(3.7)) #=> 3.0
-
-# Wir können auch alle Funktionen eines Moduls importieren
-# Warnung: Dies wird nicht empfohlen
-from math import *
-
-# Wir können Modulnamen abkürzen
-import math as m
-math.sqrt(16) == m.sqrt(16) #=> True
-
-# Module sind in Python nur gewöhnliche Dateien. Wir
-# können unsere eigenen schreiben und importieren. Der Name des
-# Moduls ist der Dateiname.
-
-# Wir können auch die Funktionen und Attribute eines
-# Moduls herausfinden.
-import math
-dir(math)
-
-
-####################################################
-## 7. Fortgeschritten
-####################################################
-
-# Generatoren helfen um Code schnell und einfach zu schreiben
-def double_numbers(iterable):
- for i in iterable:
- yield i + i
-
-# Ein Generator erschafft Werte spontan
-# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen.
-# iteration. Das heißt, Werte größer als 15 werden nicht behandelt.
-# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000
-# würde das sehr viel Zeit in Anspruch nehmen.
-# Wenn wir eine variable mit einem Namen erschaffen wollen, das
-# normalerweise mit einem Python - Schlüsselwort kollidieren würde,
-# benutzen wir einen Unterstrich nach dem Wort.
-range_ = range(1, 900000000)
-# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt
-for i in double_numbers(range_):
- print(i)
- if i >= 30:
- break
-
-
-# Dekoratoren
-# In diesem Beispiel die Methode beg umwickelt say
-# Beim Aufruf von beg, say wird aufgerufen
-# Falls say_please true ist, ändert sich die ausgegebene Nachricht
-from functools import wraps
-
-
-def beg(target_function):
- @wraps(target_function)
- def wrapper(*args, **kwargs):
- msg, say_please = target_function(*args, **kwargs)
- if say_please:
- return "{} {}".format(msg, "Please! I am poor :(")
- return msg
-
- return wrapper
-
-
-@beg
-def say(say_please=False):
- msg = "Can you buy me a beer?"
- return msg, say_please
-
-
-print(say()) # Can you buy me a beer?
-print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
-
-```
-
-## Lust auf mehr?
-
-### Kostenlos online (Englisch)
-
-* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
-* [Python Course](http://www.python-course.eu/index.php)
-* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
-
-### Totholz (Englisch)
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/de-de/pythonlegacy-de.html.markdown b/de-de/pythonlegacy-de.html.markdown
new file mode 100644
index 00000000..d66a8551
--- /dev/null
+++ b/de-de/pythonlegacy-de.html.markdown
@@ -0,0 +1,766 @@
+---
+language: Python 2 (legacy)
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+translators:
+ - ["kultprok", "http:/www.kulturproktologie.de"]
+filename: learnpythonlegacy-de.py
+lang: de-de
+---
+
+Anmerkungen des ursprünglichen Autors:
+Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode.
+
+Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]
+
+Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber auf Python 2.x anwendbar sein. Haltet Ausschau nach einem Rundgang durch Python 3, der bald erscheinen soll.
+
+```python
+# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz)
+""" Mehrzeilige Strings werden mit
+ drei '-Zeichen geschrieben und werden
+ oft als Kommentare genutzt.
+"""
+
+####################################################
+## 1. Primitive Datentypen und Operatoren
+####################################################
+
+# Die Zahlen
+3 #=> 3
+
+# Mathematik funktioniert so, wie man das erwartet
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# Division ist ein wenig kniffliger. Ganze Zahlen werden ohne Rest dividiert
+# und das Ergebnis wird automatisch abgerundet.
+5 / 2 #=> 2
+
+# Um das zu ändern, müssen wir Gleitkommazahlen einführen und benutzen
+2.0 # Das ist eine Gleitkommazahl
+11.0 / 4.0 #=> 2.75 Ahhh...schon besser
+
+# Rangfolge wird mit Klammern erzwungen
+(1 + 3) * 2 #=> 8
+
+# Boolesche Ausdrücke sind primitive Datentypen
+True
+False
+
+# Mit not wird negiert
+not True #=> False
+not False #=> True
+
+# Gleichheit ist ==
+1 == 1 #=> True
+2 == 1 #=> False
+
+# Ungleichheit ist !=
+1 != 1 #=> False
+2 != 1 #=> True
+
+# Ein paar weitere Vergleiche
+1 < 10 #=> True
+1 > 10 #=> False
+2 <= 2 #=> True
+2 >= 2 #=> True
+
+# Vergleiche können verknüpft werden!
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
+
+# Strings werden mit " oder ' gebildet
+"Das ist ein String."
+'Das ist auch ein String.'
+
+# Strings können addiert werden!
+"Hello " + "world!" #=> "Hello world!"
+
+# Ein String kann wie eine Liste von Zeichen verwendet werden
+"Das ist ein String"[0] #=> 'D'
+
+# Mit % können Strings formatiert werden, etwa so:
+"%s können %s werden" % ("Strings", "interpoliert")
+
+# Ein modernerer Weg, um Strings zu formatieren, ist die format-Methode.
+# Diese Methode wird bevorzugt
+"{0} können {1} werden".format("Strings", "formatiert")
+# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen.
+"{name} will {food} essen".format(name="Bob", food="Lasagne")
+
+# None ist ein Objekt
+None #=> None
+
+# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen
+# Benutzt stattdessen `is`
+"etc" is None #=> False
+None is None #=> True
+
+# Der 'is'-Operator testet Objektidentität. Das ist nicht
+# sehr nützlich, wenn wir mit primitiven Datentypen arbeiten, aber
+# sehr nützlich bei Objekten.
+
+# None, 0, und leere Strings/Listen werden alle als False bewertet.
+# Alle anderen Werte sind True
+0 == False #=> True
+"" == False #=> True
+
+
+####################################################
+## 2. Variablen und Collections
+####################################################
+
+# Textausgabe ist sehr einfach
+print "Ich bin Python. Schön, dich kennenzulernen!"
+
+
+# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren.
+some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm
+some_var #=> 5
+
+# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus.
+# Unter "Kontrollstruktur" kann noch mehr über
+# Ausnahmebehandlung erfahren werden.
+some_other_var # Löst einen NameError aus
+
+# if kann als Ausdruck verwendet werden
+"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+
+# Listen speichern Sequenzen
+li = []
+# Wir können mit einer bereits gefüllten Liste anfangen
+other_li = [4, 5, 6]
+
+# append fügt Daten am Ende der Liste ein
+li.append(1) #li ist jetzt [1]
+li.append(2) #li ist jetzt [1, 2]
+li.append(4) #li ist jetzt [1, 2, 4]
+li.append(3) #li ist jetzt [1, 2, 4, 3]
+# Vom Ende der Liste mit pop entfernen
+li.pop() #=> 3 und li ist jetzt [1, 2, 4]
+# und dann wieder hinzufügen
+li.append(3) # li ist jetzt wieder [1, 2, 4, 3].
+
+# Greife auf Listen wie auf Arrays zu
+li[0] #=> 1
+# Das letzte Element ansehen
+li[-1] #=> 3
+
+# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError
+li[4] # Raises an IndexError
+
+# Wir können uns Ranges mit Slice-Syntax ansehen
+li[1:3] #=> [2, 4]
+# Den Anfang auslassen
+li[2:] #=> [4, 3]
+# Das Ende auslassen
+li[:3] #=> [1, 2, 4]
+
+# Ein bestimmtes Element mit del aus der Liste entfernen
+del li[2] # li ist jetzt [1, 2, 3]
+
+# Listen können addiert werden
+li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen
+
+# Listen mit extend verknüpfen
+li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6]
+
+# Mit in auf Existenz eines Elements prüfen
+1 in li #=> True
+
+# Die Länge der Liste mit len ermitteln
+len(li) #=> 6
+
+
+# Tupel sind wie Listen, nur unveränderlich.
+tup = (1, 2, 3)
+tup[0] #=> 1
+tup[0] = 3 # Löst einen TypeError aus
+
+# Wir können all diese Listen-Dinge auch mit Tupeln anstellen
+len(tup) #=> 3
+tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
+tup[:2] #=> (1, 2)
+2 in tup #=> True
+
+# Wir können Tupel (oder Listen) in Variablen entpacken
+a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3
+# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen
+d, e, f = 4, 5, 6
+# Es ist kinderleicht zwei Werte zu tauschen
+e, d = d, e # d is now 5 and e is now 4
+
+
+# Dictionarys (Wörterbucher) speichern Key-Value-Paare
+empty_dict = {}
+# Hier ein gefülltes Wörterbuch
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Wir können Einträge mit [] nachschlagen
+filled_dict["one"] #=> 1
+
+# So holen wir alle Keys (Schlüssel) als Liste
+filled_dict.keys() #=> ["three", "two", "one"]
+# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert.
+# Einzelne Resultate können anders angeordnet sein.
+
+# Alle Values (Werte) als Liste
+filled_dict.values() #=> [3, 2, 1]
+# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln.
+
+# Das Vorhandensein eines Schlüssels im Wörterbuch mit in prüfen
+"one" in filled_dict #=> True
+1 in filled_dict #=> False
+
+# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus
+filled_dict["four"] # KeyError
+
+# Mit der get-Methode verhindern wir das
+filled_dict.get("one") #=> 1
+filled_dict.get("four") #=> None
+# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt
+filled_dict.get("one", 4) #=> 1
+filled_dict.get("four", 4) #=> 4
+
+# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen
+filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt
+filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5
+
+
+# Sets speichern Mengen
+empty_set = set()
+# Initialisieren wir ein Set mit ein paar Werten
+some_set = set([1,2,2,3,4]) # some_set ist jetzt set([1, 2, 3, 4])
+
+# Seit Python 2.7 kann {} benutzt werden, um ein Set zu erstellen
+filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+
+# Mehr Elemente hinzufügen
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+
+# Schnittmengen werden mit & gebildet
+other_set = {3, 4, 5, 6}
+filled_set & other_set #=> {3, 4, 5}
+
+# Mengen werden mit | vereinigt
+filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+
+# Die Differenz einer Menge mit - bilden
+{1,2,3,4} - {2,3,5} #=> {1, 4}
+
+# Auf Vorhandensein von Elementen mit in prüfen
+2 in filled_set #=> True
+10 in filled_set #=> False
+
+
+####################################################
+## 3. Kontrollstruktur
+####################################################
+
+# Erstellen wir mal eine Variable
+some_var = 5
+
+# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig!
+# gibt "some_var ist kleiner als 10" aus
+if some_var > 10:
+ print "some_var ist viel größer als 10."
+elif some_var < 10: # Dieser elif-Absatz ist optional.
+ print "some_var ist kleiner als 10."
+else: # Das hier ist auch optional.
+ print "some_var ist tatsächlich 10."
+
+
+"""
+For-Schleifen iterieren über Listen
+Ausgabe:
+ hund ist ein Säugetier
+ katze ist ein Säugetier
+ maus ist ein Säugetier
+"""
+for animal in ["hund", "katze", "maus"]:
+ # Wir können Strings mit % formatieren
+ print "%s ist ein Säugetier" % animal
+
+"""
+`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder
+Ausgabe:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+While-Schleifen laufen, bis eine Bedingung erfüllt ist.
+Ausgabe:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Kurzform für x = x + 1
+
+# Ausnahmebehandlung mit einem try/except-Block
+
+# Funktioniert in Python 2.6 und höher:
+try:
+ # Mit raise wird ein Fehler ausgegeben
+ raise IndexError("Das hier ist ein Index-Fehler")
+except IndexError as e:
+ pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären.
+
+
+####################################################
+## 4. Funktionen
+####################################################
+
+# Mit def neue Funktionen erstellen
+def add(x, y):
+ print "x ist %s und y ist %s" % (x, y)
+ return x + y # Werte werden mit return zurückgegeben
+
+# Funktionen mit Parametern aufrufen
+add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück
+
+# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente
+add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden.
+
+# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) #=> (1,2,3)
+
+
+# Wir können auch Funktionen mit beliebiger Anzahl
+# Schlüsselwort-Argumenten definieren
+def keyword_args(**kwargs):
+ return kwargs
+
+# Rufen wir es mal auf, um zu sehen, was passiert
+keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+
+# Wir können beides gleichzeitig machem, wenn wir wollen
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) Ausgabe:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen!
+# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4)
+all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4)
+all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4)
+
+# Python hat First-Class-Funktionen
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) #=> 13
+
+# Es gibt auch anonyme Funktionen
+(lambda x: x > 2)(3) #=> True
+
+# Es gibt auch Funktionen höherer Ordnung als Built-Ins
+map(add_10, [1,2,3]) #=> [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+
+# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen
+[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+
+
+####################################################
+## 5. Module
+####################################################
+
+# Wir können Module importieren
+import math
+print math.sqrt(16) #=> 4.0
+
+# Wir können auch nur spezielle Funktionen eines Moduls importieren
+from math import ceil, floor
+print ceil(3.7) #=> 4.0
+print floor(3.7) #=> 3.0
+
+# Wir können auch alle Funktionen eines Moduls importieren
+# Warnung: Dies wird nicht empfohlen
+from math import *
+
+# Wir können Modulnamen abkürzen
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Module sind in Python nur gewöhnliche Dateien. Wir
+# können unsere eigenen schreiben und importieren. Der Name des
+# Moduls ist der Dateiname.
+
+# Wir können herausfinden, welche Funktionen und Attribute in einem
+# Modul definiert sind.
+import math
+dir(math)
+
+# Wenn Sie ein Python-Skript namens math.py im selben Ordner
+# wie Ihr aktuelles Skript haben, wird die Datei math.py
+# anstelle des integrierten Python-Moduls geladen.
+# Dies geschieht, weil der lokale Ordner Vorrang
+# vor den in Python integrierten Bibliotheken hat.
+
+
+####################################################
+## 6. Klassen
+####################################################
+
+# Wir verwenden das Schlüsselwort "class" um eine Klasse zu erzeugen.
+class Human(object):
+
+ # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt
+ species = "H. sapiens"
+
+ # Ein simpler Konstruktor, wird aufgerufen, wenn diese Klasse instanziiert wird.
+ # Beachten Sie, dass die doppelten vorangestellten und nachgestellten
+ # Unterstriche Objekte oder Attribute bezeichnen, die von Python verwendet werden,
+ # aber in benutzergesteuerten Namespaces leben.
+ # Methoden (oder Objekte oder Attribute) wie: __init__, __str__, __repr__ usw.
+ # werden als Sondermethoden (oder manchmal als Dundermethoden bezeichnet) bezeichnet.
+ # Sie sollten solche Namen nicht selbst erfinden.
+ def __init__(self, name):
+ # Wir weisen das Argument name dem name-Attribut der Instanz zu
+ self.name = name
+
+ # Eine Instanzmethode. Alle Methoden erhalten "self" als erstes Argument.
+ def say(self, msg):
+ return "%s: %s" % (self.name, msg)
+
+ # Eine weitere Instanzmethode
+ def sing(self):
+ return 'yo... yo... microphone check... one two... one two...'
+
+ # Eine Klassenmethode wird von allen Instanzen geteilt.
+ # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # Eine Eigenschaft (Property) ist wie ein Getter.
+    # Es verwandelt die Methode age() in ein schreibgeschütztes Attribut mit demselben Namen.
+    # Es ist jedoch nicht nötig, triviale Getter und Setter in Python zu schreiben.
+ @property
+ def age(self):
+ return self._age
+
+    # Damit kann die Eigenschaft festgelegt werden
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+    # Damit kann die Eigenschaft gelöscht werden
+ @age.deleter
+ def age(self):
+ del self._age
+
+# Wenn ein Python-Interpreter eine Quelldatei liest, führt er den gesamten Code aus.
+# Diese __name__-Prüfung stellt sicher, dass dieser Codeblock nur ausgeführt wird,
+# wenn dieses Modul das Hauptprogramm ist.
+if __name__ == '__main__':
+ # Eine Instanz einer Klasse erstellen
+ i = Human(name="Ian")
+ i.say("hi") # "Ian: hi"
+ j = Human("Joel")
+ j.say("hello") # "Joel: hello"
+ # i und j sind Instanzen des Typs Mensch, oder anders ausgedrückt: Sie sind Objekte des Menschen
+
+ # Rufen wir unsere Klassenmethode auf
+ i.say(i.get_species()) # "Ian: H. sapiens"
+
+ # Ändern wir das gemeinsame Attribut
+ Human.species = "H. neanderthalensis"
+ i.say(i.get_species()) # => "Ian: H. neanderthalensis"
+ j.say(j.get_species()) # => "Joel: H. neanderthalensis"
+
+ # Aufruf der statischen Methode
+ print(Human.grunt()) # => "*grunt*"
+
+ # Kann keine statische Methode mit Instanz des Objekts aufrufen,
+ # da i.grunt () automatisch "self" (das Objekt i) als Argument verwendet
+ print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
+
+ # Die Eigenschaft für diese Instanz aktualisieren
+ i.age = 42
+ # die Eigenschaft auslesen
+ i.say(i.age) # => "Ian: 42"
+ j.say(j.age) # => "Joel: 0"
+ # die Eigenschaft löschen
+ del i.age
+ # i.age # => würde einen AttributeError werfen
+
+####################################################
+## 6.1 Inheritance
+####################################################
+
+# Vererbung ermöglicht die Definition neuer untergeordneter Klassen,
+# die Methoden und Variablen von ihrer übergeordneten Klasse erben.
+
+# Wenn Sie die oben definierte Human-Klasse als Basis- oder Elternklasse verwenden,
+# können Sie eine untergeordnete Klasse, Superhero, definieren, die die Klassenvariablen
+# wie "species", "name" und "age" sowie Methoden wie "sing" und "grunzen" aus der Klasse Human erbt.
+# Die Untergeordnete Klasse kann aber auch eigene Eigenschaften haben.
+
+# Um von der Modularisierung per Datei zu profitieren, können Sie die Klassen
+# in ihren eigenen Dateien platzieren, z. B. human.py
+
+# Um Funktionen aus anderen Dateien zu importieren, verwenden Sie das folgende Format
+# from "Dateiname-ohne-Erweiterung" impotr "Funktion-oder-Klasse"
+
+from human import Human
+
+# Geben Sie die übergeordnete(n) Klasse(n) als Parameter für die Klassendefinition an
+class Superhero(Human):
+
+ # Wenn die untergeordnete Klasse alle Definitionen des übergeordneten Elements
+ # ohne Änderungen erben soll, können Sie einfach das Schlüsselwort "pass"
+ # (und nichts anderes) verwenden. In diesem Fall wird jedoch auskommentiert,
+ # um eine eindeutige untergeordnete Klasse zuzulassen:
+ # pass
+
+ # Kindklassen können die Attribute ihrer Eltern überschreiben
+ species = 'Superhuman'
+
+ # Kinder erben automatisch den Konstruktor ihrer übergeordneten Klasse
+ # einschließlich ihrer Argumente, können aber auch zusätzliche Argumente oder
+ # Definitionen definieren und ihre Methoden zB den Klassenkonstruktor überschreiben.
+ # Dieser Konstruktor erbt das Argument "name" von der Klasse "Human" und
+ # fügt die Argumente "superpowers" und "movie" hinzu:
+ def __init__(self, name, movie=False,
+ superpowers=["super strength", "bulletproofing"]):
+
+ # zusätzliche Klassenattribute hinzufügen:
+ self.fictional = True
+ self.movie = movie
+ # Beachten Sie die veränderlichen Standardwerte, da die Standardwerte gemeinsam genutzt werden
+ self.superpowers = superpowers
+
+ # Mit der Funktion "super" können Sie auf die Methoden der übergeordneten Klasse
+ # zugreifen, die vom untergeordneten Objekt überschrieben werden,
+ # in diesem Fall die Methode __init__.
+        # Dies ruft den Konstruktor der übergeordneten Klasse auf:
+ super().__init__(name)
+
+ # überschreiben der "sing" Methode
+ def sing(self):
+ return 'Dun, dun, DUN!'
+
+ # eine zusätzliche Instanzmethode hinzufügen
+ def boast(self):
+ for power in self.superpowers:
+ print("I wield the power of {pow}!".format(pow=power))
+
+if __name__ == '__main__':
+ sup = Superhero(name="Tick")
+
+ # Instanztypprüfungen
+ if isinstance(sup, Human):
+ print('I am human')
+ if type(sup) is Superhero:
+ print('I am a superhero')
+
+ # Die Reihenfolge der Methodenauflösung (MRO = Method Resolution Order) anzeigen, die sowohl von getattr() als auch von super() verwendet wird.
+    # Dieses Attribut ist dynamisch und kann aktualisiert werden.
+ print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
+ # => <class 'human.Human'>, <class 'object'>)
+
+ # Ruft die übergeordnete Methode auf, verwendet jedoch das eigene Klassenattribut
+ print(sup.get_species()) # => Superhuman
+
+ # Ruft die überschriebene Methode auf
+ print(sup.sing()) # => Dun, dun, DUN!
+
+ # Ruft die Methode von Human auf
+ sup.say('Spoon') # => Tick: Spoon
+
+ # Aufruf einer Methode, die nur in Superhero existiert
+ sup.boast() # => I wield the power of super strength!
+ # => I wield the power of bulletproofing!
+
+ # Vererbtes Klassenattribut
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Attribut, das nur in Superhero existiert
+ print('Am I Oscar eligible? ' + str(sup.movie))
+
+####################################################
+## 6.2 Multiple Inheritance
+####################################################
+
+# Eine weitere Klassendefinition
+# bat.py
+
+class Bat:
+
+ species = 'Baty'
+
+ def __init__(self, can_fly=True):
+ self.fly = can_fly
+
+ # This class also has a say method
+ def say(self, msg):
+ msg = '... ... ...'
+ return msg
+
+ # And its own method as well
+ def sonar(self):
+ return '))) ... ((('
+
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('hello'))
+ print(b.fly)
+
+# Und noch eine andere Klassendefinition, die von Superhero und Bat erbt
+# superhero.py
+from superhero import Superhero
+from bat import Bat
+
+# Definieren Sie Batman als eine Kindklasse, das von Superheld und Bat erbt
+class Batman(Superhero, Bat):
+
+ def __init__(self, *args, **kwargs):
+ # In der Regel müssen Sie super aufrufen, um Attribute zu erben:
+ # super (Batman, selbst) .__ init__ (* args, ** kwargs)
+ # Allerdings handelt es sich hier um Mehrfachvererbung, und super()
+ # funktioniert nur mit der nächsten Basisklasse in der MRO-Liste.
+ # Stattdessen rufen wir explizit __init__ für alle Vorfahren auf.
+ # Die Verwendung von *args und **kwargs ermöglicht die saubere Übergabe von
+ # Argumenten, wobei jedes übergeordnete Element eine Schicht der Zwiebel "abschält".
+ Superhero.__init__(self, 'anonymous', movie=True,
+ superpowers=['Wealthy'], *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # überschreibt den Wert für das Namensattribut
+ self.name = 'Sad Affleck'
+
+ def sing(self):
+ return 'nan nan nan nan nan batman!'
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # Die Reihenfolge der Methodenauflösung (MRO = Method Resolution Order) anzeigen,
+ # die sowohl von getattr() als auch von super() verwendet wird.
+ # Dieses Attribut ist dynamisch und kann aktualisiert werden.
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
+ # => <class 'bat.Bat'>, <class 'object'>)
+
+ # Ruft die übergeordnete Methode auf, verwendet jedoch das eigene Klassenattribut
+ print(sup.get_species()) # => Superhuman
+
+ # Ruft die überschriebene Methode auf
+ print(sup.sing()) # => nan nan nan nan nan batman!
+
+ # Ruft die Methode von Human auf, weil die Reihenfolge der Vererbung wichtig ist
+ sup.say('I agree') # => Sad Affleck: I agree
+
+ # Aufrufmethode, die nur im 2. Vorfahren existiert
+ print(sup.sonar()) # => ))) ... (((
+
+ # Vererbtes Klassenattribut
+ sup.age = 100
+ print(sup.age) # => 100
+
+ # Vererbtes Attribut vom 2. Vorfahren, dessen Standardwert überschrieben wurde.
+ print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
+
+
+####################################################
+## 7. Fortgeschrittenes
+####################################################
+
+# Generatoren helfen Ihnen, lazy Code zu erstellen.
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Generatoren sind speichereffizient, da sie nur die Daten laden,
+# die zur Verarbeitung des nächsten Werts in der iterierbaren Komponente
+# erforderlich sind. Dadurch können sie ansonsten unzulässig große Wertebereiche ausführen.
+# HINWEIS: `range` ersetzt` xrange` in Python 3.
+for i in double_numbers(range(1, 900000000)): # `range` ist ein Generator.
+ print(i)
+ if i >= 30:
+ break
+
+# Genauso wie Sie ein 'list comprehension' (Listen Abstraktion) erstellen können, können Sie auch 'generator comprehension' (Generator Abstraktion) erstellen.
+values = (-x for x in [1,2,3,4,5])
+for x in values:
+ print(x) # prints -1 -2 -3 -4 -5 to console/terminal
+
+# Sie können eine Generator Abstraktion auch direkt in eine Liste umwandeln (casten).
+values = (-x for x in [1,2,3,4,5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
+# Decorators
+# In diesem Beispiel umschliesst "beg" "say". Wenn say_please True ist, wird die zurückgegebene Nachricht geändert.
+from functools import wraps
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print(say()) # Can you buy me a beer?
+print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
+
+```
+
+## Lust auf mehr?
+
+### Kostenlos online (Englisch)
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+
+### Totholz (Englisch)
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/el-gr/python3-gr.html.markdown b/el-gr/python-gr.html.markdown
index 445b85ba..203c6e78 100644
--- a/el-gr/python3-gr.html.markdown
+++ b/el-gr/python-gr.html.markdown
@@ -1,5 +1,5 @@
---
-language: python3
+language: Python
contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
- ["Steven Basart", "http://github.com/xksteven"]
@@ -8,7 +8,7 @@ contributors:
- ["evuez", "http://github.com/evuez"]
- ["Rommel Martinez", "https://ebzzry.io"]
- ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"]
-filename: learnpython3-gr.py
+filename: learnpython-gr.py
lang: el-gr
---
@@ -20,7 +20,7 @@ lang: el-gr
ή τον αρχικό συγγραφέα στο [@louiedinh](http://twitter.com/louiedinh) ή στο
louiedinh [at] [google's email service]
-Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/python/) αν θέλετε να μάθετε την παλιά Python 2.7
+Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/pythonlegacy/) αν θέλετε να μάθετε την παλιά Python 2.7
```python
diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown
index 2b8f498a..7deec286 100644
--- a/es-es/python-es.html.markdown
+++ b/es-es/python-es.html.markdown
@@ -1,26 +1,25 @@
---
-language: python
+language: Python
contributors:
- - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
translators:
- - ["Camilo Garrido", "http://www.twitter.com/hirohope"]
- - ["Fabio Souto", "http://fabiosouto.me"]
+ - ["Camilo Garrido", "http://twitter.com/hirohope"]
lang: es-es
filename: learnpython-es.py
---
-Python fue creado por Guido Van Rossum en el principio de los 90. Ahora es uno
-de los lenguajes más populares que existen. Me enamoré de Python por su claridad sintáctica.
+Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno
+de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica.
Es básicamente pseudocódigo ejecutable.
¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google]
-Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3!
-
```python
+
# Comentarios de una línea comienzan con una almohadilla (o signo gato)
-""" Strings multilínea pueden escribirse
- usando tres "'s, y comúnmente son usados
+
+""" Strings multilinea pueden escribirse
+ usando tres "'s, y comunmente son usados
como comentarios.
"""
@@ -31,69 +30,49 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl
# Tienes números
3 #=> 3
-# Evidentemente puedes realizar operaciones matemáticas
-1 + 1 #=> 2
-8 - 1 #=> 7
-10 * 2 #=> 20
-35 / 5 #=> 7
-
-# La división es un poco complicada. Es división entera y toma la parte entera
-# de los resultados automáticamente.
-5 / 2 #=> 2
+# Matemática es lo que esperarías
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
-# Para arreglar la división necesitamos aprender sobre 'floats'
-# (números de coma flotante).
-2.0 # Esto es un 'float'
-11.0 / 4.0 #=> 2.75 ahhh...mucho mejor
+# Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante)
+35 / 5 # => 7.0
+# Sin embargo también tienes disponible división entera
+34 // 5 # => 6
-# Resultado de la división de enteros truncada para positivos y negativos
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # funciona con números de coma flotante
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
-
-# El operador módulo devuelve el resto de una división entre enteros
-7 % 3 # => 1
-
-# Exponenciación (x elevado a y)
-2**4 # => 16
+# Cuando usas un float, los resultados son floats
+3 * 2.0 # => 6.0
# Refuerza la precedencia con paréntesis
-(1 + 3) * 2 #=> 8
+(1 + 3) * 2 # => 8
-# Operadores booleanos
-# Nota: "and" y "or" son sensibles a mayúsculas
-True and False #=> False
-False or True #=> True
-# Podemos usar operadores booleanos con números enteros
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
+# Valores 'boolean' (booleanos) son primitivos
+True
+False
# Niega con 'not'
-not True #=> False
-not False #=> True
+not True # => False
+not False # => True
+
# Igualdad es ==
-1 == 1 #=> True
-2 == 1 #=> False
+1 == 1 # => True
+2 == 1 # => False
# Desigualdad es !=
-1 != 1 #=> False
-2 != 1 #=> True
+1 != 1 # => False
+2 != 1 # => True
# Más comparaciones
-1 < 10 #=> True
-1 > 10 #=> False
-2 <= 2 #=> True
-2 >= 2 #=> True
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
# ¡Las comparaciones pueden ser concatenadas!
-1 < 2 < 3 #=> True
-2 < 3 < 2 #=> False
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
# Strings se crean con " o '
"Esto es un string."
@@ -105,40 +84,41 @@ not False #=> True
# Un string puede ser tratado como una lista de caracteres
"Esto es un string"[0] #=> 'E'
-# % pueden ser usados para formatear strings, como esto:
-"%s pueden ser %s" % ("strings", "interpolados")
+# .format puede ser usaro para darle formato a los strings, así:
+"{} pueden ser {}".format("strings", "interpolados")
-# Una forma más reciente de formatear strings es el método 'format'.
-# Este método es la forma preferida
-"{0} pueden ser {1}".format("strings", "formateados")
-# Puedes usar palabras clave si no quieres contar.
-"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña")
+# Puedes reutilizar los argumentos de formato si estos se repiten.
+"{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela"
+# Puedes usar palabras claves si no quieres contar.
+"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña"
+# También puedes interpolar cadenas usando variables en el contexto
+nombre = 'Bob'
+comida = 'Lasaña'
+f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña"
# None es un objeto
-None #=> None
+None # => None
# No uses el símbolo de igualdad `==` para comparar objetos con None
-# Usa `is` en lugar de
+# Usa `is` en su lugar
"etc" is None #=> False
None is None #=> True
-# El operador 'is' prueba la identidad del objeto. Esto no es
-# muy útil cuando se trata de datos primitivos, pero es
-# muy útil cuando se trata de objetos.
-
-# None, 0, y strings/listas vacíos(as) todas se evalúan como False.
+# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False.
# Todos los otros valores son True
-bool(0) #=> False
-bool("") #=> False
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
+bool(set()) #=> False
####################################################
## 2. Variables y Colecciones
####################################################
-# Imprimir es muy fácil
-print "Soy Python. ¡Encantado de conocerte!"
-
+# Python tiene una función para imprimir
+print("Soy Python. Encantado de conocerte")
# No hay necesidad de declarar las variables antes de asignarlas.
una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas
@@ -148,19 +128,16 @@ una_variable #=> 5
# Ve Control de Flujo para aprender más sobre el manejo de excepciones.
otra_variable # Levanta un error de nombre
-# 'if' puede ser usado como una expresión
-"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
-
-# Las listas almacenan secuencias
+# Listas almacena secuencias
lista = []
# Puedes empezar con una lista prellenada
otra_lista = [4, 5, 6]
# Añadir cosas al final de una lista con 'append'
-lista.append(1) # lista ahora es [1]
-lista.append(2) # lista ahora es [1, 2]
-lista.append(4) # lista ahora es [1, 2, 4]
-lista.append(3) # lista ahora es [1, 2, 4, 3]
+lista.append(1) #lista ahora es [1]
+lista.append(2) #lista ahora es [1, 2]
+lista.append(4) #lista ahora es [1, 2, 4]
+lista.append(3) #lista ahora es [1, 2, 4, 3]
# Remueve del final de la lista con 'pop'
lista.pop() #=> 3 y lista ahora es [1, 2, 4]
# Pongámoslo de vuelta
@@ -181,6 +158,12 @@ lista[1:3] #=> [2, 4]
lista[2:] #=> [4, 3]
# Omite el final
lista[:3] #=> [1, 2, 4]
+# Selecciona cada dos elementos
+lista[::2] # =>[1, 4]
+# Invierte la lista
+lista[::-1] # => [3, 4, 2, 1]
+# Usa cualquier combinación de estos para crear trozos avanzados
+# lista[inicio:final:pasos]
# Remueve elementos arbitrarios de una lista con 'del'
del lista[2] # lista ahora es [1, 2, 3]
@@ -191,14 +174,14 @@ lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan
# Concatenar listas con 'extend'
lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6]
-# Chequea la existencia en una lista con
+# Verifica la existencia en una lista con 'in'
1 in lista #=> True
-# Examina el tamaño de una lista con 'len'
+# Examina el largo de una lista con 'len'
len(lista) #=> 6
-# Las tuplas son como las listas, pero son inmutables.
+# Tuplas son como listas pero son inmutables.
tupla = (1, 2, 3)
tupla[0] #=> 1
tupla[0] = 3 # Levanta un error TypeError
@@ -217,7 +200,7 @@ d, e, f = 4, 5, 6
e, d = d, e # d ahora es 5 y e ahora es 4
-# Diccionarios almacenan mapeos
+# Diccionarios relacionan llaves y valores
dicc_vacio = {}
# Aquí está un diccionario prellenado
dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
@@ -225,16 +208,16 @@ dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
# Busca valores con []
dicc_lleno["uno"] #=> 1
-# Obtén todas las llaves como una lista
-dicc_lleno.keys() #=> ["tres", "dos", "uno"]
+# Obtén todas las llaves como una lista con 'keys()'. Necesitamos envolver la llamada en 'list()' porque obtenemos un iterable. Hablaremos de eso luego.
+list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"]
# Nota - El orden de las llaves del diccionario no está garantizada.
# Tus resultados podrían no ser los mismos del ejemplo.
-# Obtén todos los valores como una lista
-dicc_lleno.values() #=> [3, 2, 1]
+# Obtén todos los valores como una lista. Nuevamente necesitamos envolverlas en una lista para sacarlas del iterable.
+list(dicc_lleno.values()) #=> [3, 2, 1]
# Nota - Lo mismo que con las llaves, no se garantiza el orden.
-# Chequea la existencia de una llave en el diccionario con 'in'
+# Verifica la existencia de una llave en el diccionario con 'in'
"uno" in dicc_lleno #=> True
1 in dicc_lleno #=> False
@@ -248,19 +231,18 @@ dicc_lleno.get("cuatro") #=> None
dicc_lleno.get("uno", 4) #=> 1
dicc_lleno.get("cuatro", 4) #=> 4
-# El método 'setdefault' es una manera segura de añadir nuevos pares
-# llave-valor en un diccionario
+# El método 'setdefault' inserta en un diccionario solo si la llave no está presente
dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5
dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5
+# Remueve llaves de un diccionario con 'del'
+del dicc_lleno['uno'] # Remueve la llave 'uno' de dicc_lleno
+
# Sets (conjuntos) almacenan ... bueno, conjuntos
conjunto_vacio = set()
-# Inicializar un conjunto con montón de valores
-un_conjunto = set([1,2,2,3,4]) # un_conjunto ahora es set([1, 2, 3, 4])
-
-# Desde Python 2.7, {} puede ser usado para declarar un conjunto
-conjunto_lleno = {1, 2, 2, 3, 4} # => {1 2 3 4}
+# Inicializar un conjunto con montón de valores. Yeah, se ve un poco como un diccionario. Lo siento.
+un_conjunto = {1,2,2,3,4} # un_conjunto ahora es {1, 2, 3, 4}
# Añade más valores a un conjunto
conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5}
@@ -275,7 +257,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6}
# Haz diferencia de conjuntos con -
{1,2,3,4} - {2,3,5} #=> {1, 4}
-# Chequea la existencia en un conjunto con 'in'
+# Verifica la existencia en un conjunto con 'in'
2 in conjunto_lleno #=> True
10 in conjunto_lleno #=> False
@@ -284,32 +266,30 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6}
## 3. Control de Flujo
####################################################
-# Hagamos sólo una variable
-una_variable = 5
+# Creemos una variable para experimentar
+some_var = 5
-# Aquí está una declaración de un 'if'. ¡La indentación es importante en Python!
+# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python!
# imprime "una_variable es menor que 10"
if una_variable > 10:
- print "una_variable es completamente mas grande que 10."
+ print("una_variable es completamente mas grande que 10.")
elif una_variable < 10: # Este condición 'elif' es opcional.
- print "una_variable es mas chica que 10."
+ print("una_variable es mas chica que 10.")
else: # Esto también es opcional.
- print "una_variable es de hecho 10."
-
+ print("una_variable es de hecho 10.")
"""
-For itera sobre listas
+For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...)
imprime:
perro es un mamifero
gato es un mamifero
raton es un mamifero
"""
for animal in ["perro", "gato", "raton"]:
- # Puedes usar % para interpolar strings formateados
- print "%s es un mamifero" % animal
+ print("{} es un mamifero".format(animal))
"""
-`range(número)` retorna una lista de números
+`range(número)` retorna un generador de números
desde cero hasta el número dado
imprime:
0
@@ -318,7 +298,7 @@ imprime:
3
"""
for i in range(4):
- print i
+ print(i)
"""
While itera hasta que una condición no se cumple.
@@ -330,18 +310,49 @@ imprime:
"""
x = 0
while x < 4:
- print x
+ print(x)
x += 1 # versión corta de x = x + 1
# Maneja excepciones con un bloque try/except
-
-# Funciona desde Python 2.6 en adelante:
try:
# Usa raise para levantar un error
raise IndexError("Este es un error de indice")
except IndexError as e:
pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui.
+# Python oferce una abstracción fundamental llamada Iterable.
+# Un iterable es un objeto que puede ser tratado como una sequencia.
+# El objeto es retornado por la función 'range' es un iterable.
+
+dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
+nuestro_iterable = dicc_lleno.keys()
+print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable
+
+Podemos recorrerla.
+for i in nuestro_iterable:
+ print(i) # Imprime uno, dos, tres
+
+# Aunque no podemos selecionar un elemento por su índice.
+nuestro_iterable[1] # Genera un TypeError
+
+# Un iterable es un objeto que sabe como crear un iterador.
+nuestro_iterator = iter(nuestro_iterable)
+
+# Nuestro iterador es un objeto que puede recordar el estado mientras lo recorremos.
+# Obtenemos el siguiente objeto llamando la función __next__.
+nuestro_iterator.__next__() #=> "uno"
+
+# Mantiene el estado mientras llamamos __next__.
+nuestro_iterator.__next__() #=> "dos"
+nuestro_iterator.__next__() #=> "tres"
+
+# Después que el iterador ha retornado todos sus datos, da una excepción StopIterator.
+nuestro_iterator.__next__() # Genera StopIteration
+
+# Puedes obtener todos los elementos de un iterador llamando a list() en el.
+list(dicc_lleno.keys()) #=> Retorna ["uno", "dos", "tres"]
+
+
####################################################
## 4. Funciones
@@ -349,7 +360,7 @@ except IndexError as e:
# Usa 'def' para crear nuevas funciones
def add(x, y):
- print "x es %s y y es %s" % (x, y)
+ print("x es {} y y es {}".format(x, y))
return x + y # Retorna valores con una la declaración return
# Llamando funciones con parámetros
@@ -358,6 +369,7 @@ add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11
# Otra forma de llamar funciones es con argumentos de palabras claves
add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden.
+
# Puedes definir funciones que tomen un número variable de argumentos
def varargs(*args):
return args
@@ -373,6 +385,7 @@ def keyword_args(**kwargs):
# Llamémosla para ver que sucede
keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
+
# Puedes hacer ambas a la vez si quieres
def todos_los_argumentos(*args, **kwargs):
print args
@@ -410,23 +423,28 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
# Podemos usar listas por comprensión para mapeos y filtros agradables
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+# también hay diccionarios
+{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4}
+# y conjuntos por comprensión
+{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'}
####################################################
-## 5. Clases
+## 5. Classes
####################################################
+
# Heredamos de object para obtener una clase.
class Humano(object):
# Un atributo de clase es compartido por todas las instancias de esta clase
especie = "H. sapiens"
- # Constructor básico, se llama al instanciar la clase.
+ # Constructor basico
def __init__(self, nombre):
# Asigna el argumento al atributo nombre de la instancia
self.nombre = nombre
- # Un método de instancia. Todos los metodos toman self como primer argumento
+ # Un metodo de instancia. Todos los metodos toman self como primer argumento
def decir(self, msg):
return "%s: %s" % (self.nombre, msg)
@@ -436,7 +454,7 @@ class Humano(object):
def get_especie(cls):
return cls.especie
- # Un metodo estático es llamado sin la clase o instancia como referencia
+ # Un metodo estatico es llamado sin la clase o instancia como referencia
@staticmethod
def roncar():
return "*roncar*"
@@ -467,12 +485,12 @@ Humano.roncar() #=> "*roncar*"
# Puedes importar módulos
import math
-print math.sqrt(16) #=> 4.0
+print(math.sqrt(16)) #=> 4.0
# Puedes obtener funciones específicas desde un módulo
from math import ceil, floor
-print ceil(3.7) #=> 4.0
-print floor(3.7) #=> 3.0
+print(ceil(3.7)) #=> 4.0
+print(floor(3.7))#=> 3.0
# Puedes importar todas las funciones de un módulo
# Precaución: Esto no es recomendable
@@ -495,52 +513,48 @@ dir(math)
## 7. Avanzado
####################################################
-# Los generadores permiten evaluación perezosa
+# Los generadores te ayudan a hacer un código perezoso (lazy)
def duplicar_numeros(iterable):
for i in iterable:
yield i + i
-# Un generador crea valores sobre la marcha
-# En vez de generar y devolver todos los valores de una vez, crea un valor
-# en cada iteración. En este ejemplo los valores mayores que 15 no serán
-# procesados en duplicar_numeros.
-# Nota: xrange es un generador que hace lo mismo que range.
-# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio.
-# xrange crea un generador, mientras que range crea toda la lista.
-# Añadimos un guión bajo a los nombres de variable que coinciden con palabras
-# reservadas de python.
-xrange_ = xrange(1, 900000000)
-
-# duplica todos los números hasta que encuentra un resultado >= 30
-for i in duplicar_numeros(xrange_):
- print i
+# Un generador crea valores sobre la marcha.
+# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración.
+# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'.
+# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse.
+_rango = range(1, 900000000)
+# Duplicará todos los números hasta que un resultado >= se encuentre.
+for i in duplicar_numeros(_rango):
+ print(i)
if i >= 30:
break
+
# Decoradores
-# en este ejemplo pedir rodea a hablar
-# Si por_favor es True se cambiará el mensaje.
+# en este ejemplo 'pedir' envuelve a 'decir'
+# Pedir llamará a 'decir'. Si decir_por_favor es True entonces cambiará el mensaje a retornar
from functools import wraps
-def pedir(target_function):
- @wraps(target_function)
+def pedir(_decir):
+ @wraps(_decir)
def wrapper(*args, **kwargs):
- msg, por_favor = target_function(*args, **kwargs)
- if por_favor:
- return "{} {}".format(msg, "¡Por favor! Soy pobre :(")
- return msg
+ mensaje, decir_por_favor = _decir(*args, **kwargs)
+ if decir_por_favor:
+ return "{} {}".format(mensaje, "¡Por favor! Soy pobre :(")
+ return mensaje
return wrapper
@pedir
-def hablar(por_favor=False):
- msg = "¿Me puedes comprar una cerveza?"
- return msg, por_favor
+def say(decir_por_favor=False):
+ mensaje = "¿Puedes comprarme una cerveza?"
+ return mensaje, decir_por_favor
+
-print hablar() # ¿Me puedes comprar una cerveza?
-print hablar(por_favor=True) # ¿Me puedes comprar una cerveza? ¡Por favor! Soy pobre :(
+print(decir()) # ¿Puedes comprarme una cerveza?
+print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :()
```
## ¿Listo para más?
@@ -549,9 +563,10 @@ print hablar(por_favor=True) # ¿Me puedes comprar una cerveza? ¡Por favor! So
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2.6/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
+* [Python Module of the Week](http://pymotw.com/3/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
### Encuadernados
diff --git a/es-es/python3-es.html.markdown b/es-es/pythonlegacy-es.html.markdown
index 3236e73a..0a7304e9 100644
--- a/es-es/python3-es.html.markdown
+++ b/es-es/pythonlegacy-es.html.markdown
@@ -1,25 +1,26 @@
---
-language: python3
+language: Python 2 (legacy)
contributors:
- - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Louie Dinh", "http://ldinh.ca"]
translators:
- - ["Camilo Garrido", "http://twitter.com/hirohope"]
+ - ["Camilo Garrido", "http://www.twitter.com/hirohope"]
+ - ["Fabio Souto", "http://fabiosouto.me"]
lang: es-es
-filename: learnpython3-es.py
+filename: learnpythonlegacy-es.py
---
-Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno
-de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica.
+Python fue creado por Guido Van Rossum en el principio de los 90. Ahora es uno
+de los lenguajes más populares que existen. Me enamoré de Python por su claridad sintáctica.
Es básicamente pseudocódigo ejecutable.
¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google]
-```python
+Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3!
+```python
# Comentarios de una línea comienzan con una almohadilla (o signo gato)
-
-""" Strings multilinea pueden escribirse
- usando tres "'s, y comunmente son usados
+""" Strings multilínea pueden escribirse
+ usando tres "'s, y comúnmente son usados
como comentarios.
"""
@@ -30,49 +31,69 @@ Es básicamente pseudocódigo ejecutable.
# Tienes números
3 #=> 3
-# Matemática es lo que esperarías
-1 + 1 #=> 2
-8 - 1 #=> 7
-10 * 2 #=> 20
+# Evidentemente puedes realizar operaciones matemáticas
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# La división es un poco complicada. Es división entera y toma la parte entera
+# de los resultados automáticamente.
+5 / 2 #=> 2
-# Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante)
-35 / 5 # => 7.0
-# Sin embargo también tienes disponible división entera
-34 // 5 # => 6
+# Para arreglar la división necesitamos aprender sobre 'floats'
+# (números de coma flotante).
+2.0 # Esto es un 'float'
+11.0 / 4.0 #=> 2.75 ahhh...mucho mejor
-# Cuando usas un float, los resultados son floats
-3 * 2.0 # => 6.0
+# Resultado de la división de enteros truncada para positivos y negativos
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # funciona con números de coma flotante
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# El operador módulo devuelve el resto de una división entre enteros
+7 % 3 # => 1
+
+# Exponenciación (x elevado a y)
+2**4 # => 16
# Refuerza la precedencia con paréntesis
-(1 + 3) * 2 # => 8
+(1 + 3) * 2 #=> 8
+# Operadores booleanos
+# Nota: "and" y "or" son sensibles a mayúsculas
+True and False #=> False
+False or True #=> True
-# Valores 'boolean' (booleanos) son primitivos
-True
-False
+# Podemos usar operadores booleanos con números enteros
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
# Niega con 'not'
-not True # => False
-not False # => True
-
+not True #=> False
+not False #=> True
# Igualdad es ==
-1 == 1 # => True
-2 == 1 # => False
+1 == 1 #=> True
+2 == 1 #=> False
# Desigualdad es !=
-1 != 1 # => False
-2 != 1 # => True
+1 != 1 #=> False
+2 != 1 #=> True
# Más comparaciones
-1 < 10 # => True
-1 > 10 # => False
-2 <= 2 # => True
-2 >= 2 # => True
+1 < 10 #=> True
+1 > 10 #=> False
+2 <= 2 #=> True
+2 >= 2 #=> True
# ¡Las comparaciones pueden ser concatenadas!
-1 < 2 < 3 # => True
-2 < 3 < 2 # => False
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
# Strings se crean con " o '
"Esto es un string."
@@ -84,41 +105,40 @@ not False # => True
# Un string puede ser tratado como una lista de caracteres
"Esto es un string"[0] #=> 'E'
-# .format puede ser usaro para darle formato a los strings, así:
-"{} pueden ser {}".format("strings", "interpolados")
+# % pueden ser usados para formatear strings, como esto:
+"%s pueden ser %s" % ("strings", "interpolados")
-# Puedes reutilizar los argumentos de formato si estos se repiten.
-"{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela"
-# Puedes usar palabras claves si no quieres contar.
-"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña"
-# También puedes interpolar cadenas usando variables en el contexto
-nombre = 'Bob'
-comida = 'Lasaña'
-f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña"
+# Una forma más reciente de formatear strings es el método 'format'.
+# Este método es la forma preferida
+"{0} pueden ser {1}".format("strings", "formateados")
+# Puedes usar palabras clave si no quieres contar.
+"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña")
# None es un objeto
-None # => None
+None #=> None
# No uses el símbolo de igualdad `==` para comparar objetos con None
-# Usa `is` en su lugar
+# Usa `is` en lugar de
"etc" is None #=> False
None is None #=> True
-# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False.
+# El operador 'is' prueba la identidad del objeto. Esto no es
+# muy útil cuando se trata de datos primitivos, pero es
+# muy útil cuando se trata de objetos.
+
+# None, 0, y strings/listas vacíos(as) todas se evalúan como False.
# Todos los otros valores son True
-bool(0) # => False
-bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
-bool(set()) #=> False
+bool(0) #=> False
+bool("") #=> False
####################################################
## 2. Variables y Colecciones
####################################################
-# Python tiene una función para imprimir
-print("Soy Python. Encantado de conocerte")
+# Imprimir es muy fácil
+print "Soy Python. ¡Encantado de conocerte!"
+
# No hay necesidad de declarar las variables antes de asignarlas.
una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas
@@ -128,16 +148,19 @@ una_variable #=> 5
# Ve Control de Flujo para aprender más sobre el manejo de excepciones.
otra_variable # Levanta un error de nombre
-# Listas almacena secuencias
+# 'if' puede ser usado como una expresión
+"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+
+# Las listas almacenan secuencias
lista = []
# Puedes empezar con una lista prellenada
otra_lista = [4, 5, 6]
# Añadir cosas al final de una lista con 'append'
-lista.append(1) #lista ahora es [1]
-lista.append(2) #lista ahora es [1, 2]
-lista.append(4) #lista ahora es [1, 2, 4]
-lista.append(3) #lista ahora es [1, 2, 4, 3]
+lista.append(1) # lista ahora es [1]
+lista.append(2) # lista ahora es [1, 2]
+lista.append(4) # lista ahora es [1, 2, 4]
+lista.append(3) # lista ahora es [1, 2, 4, 3]
# Remueve del final de la lista con 'pop'
lista.pop() #=> 3 y lista ahora es [1, 2, 4]
# Pongámoslo de vuelta
@@ -158,12 +181,6 @@ lista[1:3] #=> [2, 4]
lista[2:] #=> [4, 3]
# Omite el final
lista[:3] #=> [1, 2, 4]
-# Selecciona cada dos elementos
-lista[::2] # =>[1, 4]
-# Invierte la lista
-lista[::-1] # => [3, 4, 2, 1]
-# Usa cualquier combinación de estos para crear trozos avanzados
-# lista[inicio:final:pasos]
# Remueve elementos arbitrarios de una lista con 'del'
del lista[2] # lista ahora es [1, 2, 3]
@@ -174,14 +191,14 @@ lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan
# Concatenar listas con 'extend'
lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6]
-# Verifica la existencia en una lista con 'in'
+# Chequea la existencia en una lista con
1 in lista #=> True
-# Examina el largo de una lista con 'len'
+# Examina el tamaño de una lista con 'len'
len(lista) #=> 6
-# Tuplas son como listas pero son inmutables.
+# Las tuplas son como las listas, pero son inmutables.
tupla = (1, 2, 3)
tupla[0] #=> 1
tupla[0] = 3 # Levanta un error TypeError
@@ -200,7 +217,7 @@ d, e, f = 4, 5, 6
e, d = d, e # d ahora es 5 y e ahora es 4
-# Diccionarios relacionan llaves y valores
+# Diccionarios almacenan mapeos
dicc_vacio = {}
# Aquí está un diccionario prellenado
dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
@@ -208,16 +225,16 @@ dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
# Busca valores con []
dicc_lleno["uno"] #=> 1
-# Obtén todas las llaves como una lista con 'keys()'. Necesitamos envolver la llamada en 'list()' porque obtenemos un iterable. Hablaremos de eso luego.
-list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"]
+# Obtén todas las llaves como una lista
+dicc_lleno.keys() #=> ["tres", "dos", "uno"]
# Nota - El orden de las llaves del diccionario no está garantizada.
# Tus resultados podrían no ser los mismos del ejemplo.
-# Obtén todos los valores como una lista. Nuevamente necesitamos envolverlas en una lista para sacarlas del iterable.
-list(dicc_lleno.values()) #=> [3, 2, 1]
+# Obtén todos los valores como una lista
+dicc_lleno.values() #=> [3, 2, 1]
# Nota - Lo mismo que con las llaves, no se garantiza el orden.
-# Verifica la existencia de una llave en el diccionario con 'in'
+# Chequea la existencia de una llave en el diccionario con 'in'
"uno" in dicc_lleno #=> True
1 in dicc_lleno #=> False
@@ -231,18 +248,19 @@ dicc_lleno.get("cuatro") #=> None
dicc_lleno.get("uno", 4) #=> 1
dicc_lleno.get("cuatro", 4) #=> 4
-# El método 'setdefault' inserta en un diccionario solo si la llave no está presente
+# El método 'setdefault' es una manera segura de añadir nuevos pares
+# llave-valor en un diccionario
dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5
dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5
-# Remueve llaves de un diccionario con 'del'
-del dicc_lleno['uno'] # Remueve la llave 'uno' de dicc_lleno
-
# Sets (conjuntos) almacenan ... bueno, conjuntos
conjunto_vacio = set()
-# Inicializar un conjunto con montón de valores. Yeah, se ve un poco como un diccionario. Lo siento.
-un_conjunto = {1,2,2,3,4} # un_conjunto ahora es {1, 2, 3, 4}
+# Inicializar un conjunto con montón de valores
+un_conjunto = set([1,2,2,3,4]) # un_conjunto ahora es set([1, 2, 3, 4])
+
+# Desde Python 2.7, {} puede ser usado para declarar un conjunto
+conjunto_lleno = {1, 2, 2, 3, 4} # => {1 2 3 4}
# Añade más valores a un conjunto
conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5}
@@ -257,7 +275,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6}
# Haz diferencia de conjuntos con -
{1,2,3,4} - {2,3,5} #=> {1, 4}
-# Verifica la existencia en un conjunto con 'in'
+# Chequea la existencia en un conjunto con 'in'
2 in conjunto_lleno #=> True
10 in conjunto_lleno #=> False
@@ -266,30 +284,32 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6}
## 3. Control de Flujo
####################################################
-# Creemos una variable para experimentar
-some_var = 5
+# Hagamos sólo una variable
+una_variable = 5
-# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python!
+# Aquí está una declaración de un 'if'. ¡La indentación es importante en Python!
# imprime "una_variable es menor que 10"
if una_variable > 10:
- print("una_variable es completamente mas grande que 10.")
+ print "una_variable es completamente mas grande que 10."
elif una_variable < 10: # Este condición 'elif' es opcional.
- print("una_variable es mas chica que 10.")
+ print "una_variable es mas chica que 10."
else: # Esto también es opcional.
- print("una_variable es de hecho 10.")
+ print "una_variable es de hecho 10."
+
"""
-For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...)
+For itera sobre listas
imprime:
perro es un mamifero
gato es un mamifero
raton es un mamifero
"""
for animal in ["perro", "gato", "raton"]:
- print("{} es un mamifero".format(animal))
+ # Puedes usar % para interpolar strings formateados
+ print "%s es un mamifero" % animal
"""
-`range(número)` retorna un generador de números
+`range(número)` retorna una lista de números
desde cero hasta el número dado
imprime:
0
@@ -298,7 +318,7 @@ imprime:
3
"""
for i in range(4):
- print(i)
+ print i
"""
While itera hasta que una condición no se cumple.
@@ -310,49 +330,18 @@ imprime:
"""
x = 0
while x < 4:
- print(x)
+ print x
x += 1 # versión corta de x = x + 1
# Maneja excepciones con un bloque try/except
+
+# Funciona desde Python 2.6 en adelante:
try:
# Usa raise para levantar un error
raise IndexError("Este es un error de indice")
except IndexError as e:
pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui.
-# Python oferce una abstracción fundamental llamada Iterable.
-# Un iterable es un objeto que puede ser tratado como una sequencia.
-# El objeto es retornado por la función 'range' es un iterable.
-
-dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
-nuestro_iterable = dicc_lleno.keys()
-print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable
-
-Podemos recorrerla.
-for i in nuestro_iterable:
- print(i) # Imprime uno, dos, tres
-
-# Aunque no podemos selecionar un elemento por su índice.
-nuestro_iterable[1] # Genera un TypeError
-
-# Un iterable es un objeto que sabe como crear un iterador.
-nuestro_iterator = iter(nuestro_iterable)
-
-# Nuestro iterador es un objeto que puede recordar el estado mientras lo recorremos.
-# Obtenemos el siguiente objeto llamando la función __next__.
-nuestro_iterator.__next__() #=> "uno"
-
-# Mantiene el estado mientras llamamos __next__.
-nuestro_iterator.__next__() #=> "dos"
-nuestro_iterator.__next__() #=> "tres"
-
-# Después que el iterador ha retornado todos sus datos, da una excepción StopIterator.
-nuestro_iterator.__next__() # Genera StopIteration
-
-# Puedes obtener todos los elementos de un iterador llamando a list() en el.
-list(dicc_lleno.keys()) #=> Retorna ["uno", "dos", "tres"]
-
-
####################################################
## 4. Funciones
@@ -360,7 +349,7 @@ list(dicc_lleno.keys()) #=> Retorna ["uno", "dos", "tres"]
# Usa 'def' para crear nuevas funciones
def add(x, y):
- print("x es {} y y es {}".format(x, y))
+ print "x es %s y y es %s" % (x, y)
return x + y # Retorna valores con una la declaración return
# Llamando funciones con parámetros
@@ -369,7 +358,6 @@ add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11
# Otra forma de llamar funciones es con argumentos de palabras claves
add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden.
-
# Puedes definir funciones que tomen un número variable de argumentos
def varargs(*args):
return args
@@ -385,7 +373,6 @@ def keyword_args(**kwargs):
# Llamémosla para ver que sucede
keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
-
# Puedes hacer ambas a la vez si quieres
def todos_los_argumentos(*args, **kwargs):
print args
@@ -423,28 +410,23 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
# Podemos usar listas por comprensión para mapeos y filtros agradables
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
-# también hay diccionarios
-{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4}
-# y conjuntos por comprensión
-{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'}
####################################################
-## 5. Classes
+## 5. Clases
####################################################
-
# Heredamos de object para obtener una clase.
class Humano(object):
# Un atributo de clase es compartido por todas las instancias de esta clase
especie = "H. sapiens"
- # Constructor basico
+ # Constructor básico, se llama al instanciar la clase.
def __init__(self, nombre):
# Asigna el argumento al atributo nombre de la instancia
self.nombre = nombre
- # Un metodo de instancia. Todos los metodos toman self como primer argumento
+ # Un método de instancia. Todos los metodos toman self como primer argumento
def decir(self, msg):
return "%s: %s" % (self.nombre, msg)
@@ -454,7 +436,7 @@ class Humano(object):
def get_especie(cls):
return cls.especie
- # Un metodo estatico es llamado sin la clase o instancia como referencia
+ # Un metodo estático es llamado sin la clase o instancia como referencia
@staticmethod
def roncar():
return "*roncar*"
@@ -485,12 +467,12 @@ Humano.roncar() #=> "*roncar*"
# Puedes importar módulos
import math
-print(math.sqrt(16)) #=> 4.0
+print math.sqrt(16) #=> 4.0
# Puedes obtener funciones específicas desde un módulo
from math import ceil, floor
-print(ceil(3.7)) #=> 4.0
-print(floor(3.7))#=> 3.0
+print ceil(3.7) #=> 4.0
+print floor(3.7) #=> 3.0
# Puedes importar todas las funciones de un módulo
# Precaución: Esto no es recomendable
@@ -513,48 +495,52 @@ dir(math)
## 7. Avanzado
####################################################
-# Los generadores te ayudan a hacer un código perezoso (lazy)
+# Los generadores permiten evaluación perezosa
def duplicar_numeros(iterable):
for i in iterable:
yield i + i
-# Un generador crea valores sobre la marcha.
-# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración.
-# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'.
-# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse.
-_rango = range(1, 900000000)
-# Duplicará todos los números hasta que un resultado >= se encuentre.
-for i in duplicar_numeros(_rango):
- print(i)
+# Un generador crea valores sobre la marcha
+# En vez de generar y devolver todos los valores de una vez, crea un valor
+# en cada iteración. En este ejemplo los valores mayores que 15 no serán
+# procesados en duplicar_numeros.
+# Nota: xrange es un generador que hace lo mismo que range.
+# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio.
+# xrange crea un generador, mientras que range crea toda la lista.
+# Añadimos un guión bajo a los nombres de variable que coinciden con palabras
+# reservadas de python.
+xrange_ = xrange(1, 900000000)
+
+# duplica todos los números hasta que encuentra un resultado >= 30
+for i in duplicar_numeros(xrange_):
+ print i
if i >= 30:
break
-
# Decoradores
-# en este ejemplo 'pedir' envuelve a 'decir'
-# Pedir llamará a 'decir'. Si decir_por_favor es True entonces cambiará el mensaje a retornar
+# en este ejemplo pedir rodea a hablar
+# Si por_favor es True se cambiará el mensaje.
from functools import wraps
-def pedir(_decir):
- @wraps(_decir)
+def pedir(target_function):
+ @wraps(target_function)
def wrapper(*args, **kwargs):
- mensaje, decir_por_favor = _decir(*args, **kwargs)
- if decir_por_favor:
- return "{} {}".format(mensaje, "¡Por favor! Soy pobre :(")
- return mensaje
+ msg, por_favor = target_function(*args, **kwargs)
+ if por_favor:
+ return "{} {}".format(msg, "¡Por favor! Soy pobre :(")
+ return msg
return wrapper
@pedir
-def say(decir_por_favor=False):
- mensaje = "¿Puedes comprarme una cerveza?"
- return mensaje, decir_por_favor
-
+def hablar(por_favor=False):
+ msg = "¿Me puedes comprar una cerveza?"
+ return msg, por_favor
-print(decir()) # ¿Puedes comprarme una cerveza?
-print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :()
+print hablar() # ¿Me puedes comprar una cerveza?
+print hablar(por_favor=True) # ¿Me puedes comprar una cerveza? ¡Por favor! Soy pobre :(
```
## ¿Listo para más?
@@ -563,10 +549,9 @@ print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favo
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [The Official Docs](http://docs.python.org/3/)
+* [The Official Docs](http://docs.python.org/2.6/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/3/)
+* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
### Encuadernados
diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown
index 0ae410de..ca510d66 100644
--- a/fr-fr/python-fr.html.markdown
+++ b/fr-fr/python-fr.html.markdown
@@ -1,293 +1,377 @@
---
-language: python
-filename: learnpython-fr.py
+language: Python
contributors:
- - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
translators:
- - ["Sylvain Zyssman", "https://github.com/sylzys"]
- - ["Nami-Doc", "https://github.com/Nami-Doc"]
+ - ["Gnomino", "https://github.com/Gnomino"]
+ - ["Julien M'Poy", "http://github.com/groovytron"]
+filename: learnpython-fr.py
lang: fr-fr
---
-Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de programmation les plus populaires.
-Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiquement du pseudo-code exécutable.
+Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des
+langages les plus populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe.
+C'est tout simplement du pseudo-code exécutable.
-Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service]
+L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service]
-N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/).
+Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7
```python
-# Une ligne simple de commentaire commence par un dièse
-""" Les lignes de commentaires multipes peuvent être écrites
- en utilisant 3 guillemets ("), et sont souvent utilisées
- pour les commentaires
+
+# Un commentaire d'une ligne commence par un dièse
+
+""" Les chaînes de caractères peuvent être écrites
+ avec 3 guillemets doubles ("), et sont souvent
+ utilisées comme des commentaires.
"""
####################################################
-## 1. Types Primaires et Opérateurs
+## 1. Types de données primaires et opérateurs
####################################################
-# Les nombres
-3 #=> 3
-
-# Les calculs produisent les résultats mathématiques escomptés
-1 + 1 #=> 2
-8 - 1 #=> 7
-10 * 2 #=> 20
-35 / 5 #=> 7
+# On a des nombres
+3 # => 3
-# La division est un peu spéciale. C'est une division d'entiers, et Python arrondi le résultat par défaut automatiquement.
-5 / 2 #=> 2
-
-# Pour corriger ce problème, on utilise les float.
-2.0 # Voici un float
-11.0 / 4.0 #=> 2.75 ahhh... beaucoup mieux
-
-# Forcer la priorité avec les parenthèses
-(1 + 3) * 2 #=> 8
-
-# Les valeurs booléenes sont de type primitif
-True
-False
+# Les calculs sont ce à quoi on s'attend
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
-# Pour la négation, on utilise "not"
-not True #=> False
-not False #=> True
+# Sauf pour la division qui retourne un float (nombre à virgule flottante)
+35 / 5 # => 7.0
-# Pour l'égalité, ==
-1 == 1 #=> True
-2 == 1 #=> False
+# Résultats de divisions entières tronqués pour les nombres positifs et négatifs
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
-# L'inégalité est symbolisée par !=
-1 != 1 #=> False
-2 != 1 #=> True
+# Quand on utilise un float, le résultat est un float
+3 * 2.0 # => 6.0
-# D'autres comparateurs
-1 < 10 #=> True
-1 > 10 #=> False
-2 <= 2 #=> True
-2 >= 2 #=> True
+# Modulo (reste de la division)
+7 % 3 # => 1
-# On peut enchaîner les comparateurs !
-1 < 2 < 3 #=> True
-2 < 3 < 2 #=> False
+# Exponentiation (x**y, x élevé à la puissance y)
+2**4 # => 16
-# Les chaînes de caractères sont créées avec " ou '
-"C'est une chaîne."
-'C\'est aussi une chaîne.'
+# Forcer la priorité de calcul avec des parenthèses
+(1 + 3) * 2 # => 8
-# On peut aussi les "additioner" !
-"Hello " + "world!" #=> "Hello world!"
-
-# Une chaîne peut être traitée comme une liste de caractères
-"C'est une chaîne"[0] #=> 'C'
+# Les valeurs booléennes sont primitives
+True
+False
-# % peut être utilisé pour formatter des chaîne, comme ceci:
-"%s can be %s" % ("strings", "interpolated")
+# Négation avec not
+not True # => False
+not False # => True
+
+# Opérateurs booléens
+# On note que "and" et "or" sont sensibles à la casse
+True and False #=> False
+False or True #=> True
+
+# Utilisation des opérations booléennes avec des entiers :
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
+# On vérifie une égalité avec ==
+1 == 1 # => True
+2 == 1 # => False
+
+# On vérifie une inégalité avec !=
+1 != 1 # => False
+2 != 1 # => True
+
+# Autres opérateurs de comparaison
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# On peut enchaîner les comparaisons
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie
+# si les objets ont la même valeur.
+a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4]
+b = a # b pointe sur a
+b is a # => True, a et b pointent sur le même objet
+b == a # => True, les objets a et b sont égaux
+b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4]
+b is a # => False, a et b ne pointent pas sur le même objet
+b == a # => True, les objets a et b ne pointent pas sur le même objet
+
+# Les chaînes (ou strings) sont créées avec " ou '
+"Ceci est une chaine"
+'Ceci est une chaine aussi.'
+
+# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire.
+"Hello " + "world!" # => "Hello world!"
+# On peut aussi le faire sans utiliser '+'
+"Hello " "world!" # => "Hello world!"
+
+# On peut traîter une chaîne comme une liste de caractères
+"This is a string"[0] # => 'T'
+
+# .format peut être utilisé pour formatter des chaînes, comme ceci:
+"{} peuvent etre {}".format("Les chaînes", "interpolées")
+
+# On peut aussi réutiliser le même argument pour gagner du temps.
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+
+# On peut aussi utiliser des mots clés pour éviter de devoir compter.
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+
+# Il est également possible d'utiliser les f-strings depuis Python 3.6 (https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals)
+name = "Fred"
+f"Il a dit que son nom est {name}." #=> "Il a dit que son nom est Fred."
+
+# Si votre code doit aussi être compatible avec Python 2.5 et moins,
+# vous pouvez encore utiliser l'ancienne syntaxe :
+"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille")
-# Une autre manière de formatter les chaînes de caractères est d'utiliser la méthode 'format'
-# C'est la méthode à privilégier
-"{0} peut être {1}".format("La chaîne", "formattée")
-# On peut utiliser des mot-clés au lieu des chiffres.
-"{name} veut manger des {food}".format(name="Bob", food="lasagnes")
# None est un objet
-None #=> None
+None # => None
-# Ne pas utiliser le symbole d'inégalité "==" pour comparer des objet à None
-# Il faut utiliser "is"
-"etc" is None #=> False
-None is None #=> True
+# N'utilisez pas "==" pour comparer des objets à None
+# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets.
+"etc" is None # => False
+None is None # => True
-# L'opérateur 'is' teste l'identité de l'objet.
-# Ce n'est pas très utilisé avec les types primitifs, mais cela peut être très utile
-# lorsque l'on utilise des objets.
-
-# None, 0, et les chaînes de caractères vides valent False.
+# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens.
# Toutes les autres valeurs valent True
-0 == False #=> True
-"" == False #=> True
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
####################################################
## 2. Variables et Collections
####################################################
-# Afficher du texte, c'est facile
-print "Je suis Python. Enchanté!"
-
+# Python a une fonction print pour afficher du texte
+print("I'm Python. Nice to meet you!")
-# Il n'y a pas besoin de déclarer les variables avant de les assigner.
-some_var = 5 # La convention veut que l'on utilise des minuscules_avec_underscores
-some_var #=> 5
+# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin.
+# Utilisez l'argument optionnel end pour changer ce caractère de fin.
+print("Hello, World", end="!") # => Hello, World!
-# Accéder à une variable non assignée lève une exception
-# Voyez les structures de contrôle pour en apprendre plus sur la gestion des exceptions.
-some_other_var # Lève une exception
+# Pas besoin de déclarer des variables avant de les définir.
+# La convention est de nommer ses variables avec des minuscules_et_underscores
+some_var = 5
+some_var # => 5
-# 'if' peut être utilisé comme expression
-"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+# Tenter d'accéder à une variable non définie lève une exception.
+# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions.
+une_variable_inconnue # Lève une NameError
-# Listes
+# Les listes permettent de stocker des séquences
li = []
-# On peut remplir liste dès l'instanciation
+# On peut initialiser une liste pré-remplie
other_li = [4, 5, 6]
-# On ajoute des éléments avec 'append'
-li.append(1) #li contient [1]
-li.append(2) #li contient [1, 2]
-li.append(4) #li contient [1, 2, 4]
-li.append(3) #li contient [1, 2, 4, 3]
-
-# Et on les supprime avec 'pop'
-li.pop() #=> 3 et li contient [1, 2, 4]
-# Remettons-le dans la liste
-li.append(3) # li contient [1, 2, 4, 3] de nouveau.
-
-# On accède aux éléments d'une liste comme à ceux un tableau.
-li[0] #=> 1
-# Le dernier élément
-li[-1] #=> 3
-
-# Accèder aux indices hors limite lève une exception
-li[4] # Lève un 'IndexError'
-
-# On peut accèder à des rangs de valeurs avec la syntaxe "slice"
-# (C'est un rang de type 'fermé/ouvert' pour les plus matheux)
-li[1:3] #=> [2, 4]
-# Sans spécifier de fin de rang, on "saute" le début de la liste
-li[2:] #=> [4, 3]
-# Sans spécifier de début de rang, on "saute" la fin de la liste
-li[:3] #=> [1, 2, 4]
-
-# Retirer un élément spécifique dee la liste avec "del"
-del li[2] # li contient [1, 2, 3]
-
-# On peut additionner des listes entre elles
-li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li et other_li existent toujours à part entière
+# On ajoute des objets à la fin d'une liste avec .append
+li.append(1) # li vaut maintenant [1]
+li.append(2) # li vaut maintenant [1, 2]
+li.append(4) # li vaut maintenant [1, 2, 4]
+li.append(3) # li vaut maintenant [1, 2, 4, 3]
+# On enlève le dernier élément avec .pop
+li.pop() # => 3 et li vaut maintenant [1, 2, 4]
+# Et on le remet
+li.append(3) # li vaut de nouveau [1, 2, 4, 3]
+
+# Accès à un élément d'une liste :
+li[0] # => 1
+# Accès au dernier élément :
+li[-1] # => 3
+
+# Accéder à un élément en dehors des limites lève une IndexError
+li[4] # Lève une IndexError
+
+# On peut accéder à une intervalle avec la syntaxe "slice"
+# (c'est un rang du type "fermé/ouvert")
+li[1:3] # => [2, 4]
+# Omettre les deux premiers éléments
+li[2:] # => [4, 3]
+# Prendre les trois premiers
+li[:3] # => [1, 2, 4]
+# Sélectionner un élément sur deux
+li[::2] # =>[1, 4]
+# Avoir une copie de la liste à l'envers
+li[::-1] # => [3, 4, 2, 1]
+# Pour des "slices" plus élaborées :
+# li[debut:fin:pas]
+
+# Faire une copie d'une profondeur de un avec les "slices"
+li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False.
+
+# Enlever des éléments arbitrairement d'une liste
+del li[2] # li is now [1, 2, 3]
+
+# On peut additionner des listes
+# Note: les valeurs de li et other_li ne sont pas modifiées.
+li + other_li # => [1, 2, 3, 4, 5, 6]
# Concaténer des listes avec "extend()"
-li.extend(other_li) # li vaut maintenant [1, 2, 3, 4, 5, 6]
+li.extend(other_li) # Maintenant li contient [1, 2, 3, 4, 5, 6]
-# Vérifier l'existence d'un élément dans une liste avec "in"
-1 in li #=> True
+# Vérifier la présence d'un objet dans une liste avec "in"
+1 in li # => True
-# Récupérer la longueur avec "len()"
-len(li) #=> 6
+# Examiner la longueur avec "len()"
+len(li) # => 6
-# Les "tuples" sont comme des listes, mais sont immuables.
+# Les tuples sont comme des listes mais sont immuables.
tup = (1, 2, 3)
-tup[0] #=> 1
-tup[0] = 3 # Lève un 'TypeError'
-
-# Mais vous pouvez faire tout ceci sur les tuples:
-len(tup) #=> 3
-tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
-tup[:2] #=> (1, 2)
-2 in tup #=> True
-
-# Vous pouvez "dé-packager" les tuples (ou les listes) dans des variables
-a, b, c = (1, 2, 3) # a vaut maintenant 1, b vaut maintenant 2 and c vaut maintenant 3
-# Sans parenthèses, un tuple est créé par défaut
+tup[0] # => 1
+tup[0] = 3 # Lève une TypeError
+
+# Note : un tuple de taille un doit avoir une virgule après le dernier élément,
+# mais ce n'est pas le cas des tuples d'autres tailles, même zéro.
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
+
+# On peut utiliser la plupart des opérations des listes sur des tuples.
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Vous pouvez décomposer des tuples (ou des listes) dans des variables
+a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3
+# Les tuples sont créés par défaut sans parenthèses
d, e, f = 4, 5, 6
-# Voyez maintenant comme il est facile d'inverser 2 valeurs
-e, d = d, e # d is now 5 and e is now 4
+# Voyez comme il est facile d'intervertir deux valeurs :
+e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4
-# Dictionnaires
+# Créer un dictionnaire :
empty_dict = {}
-# Un dictionnaire pré-rempli
+# Un dictionnaire pré-rempli :
filled_dict = {"one": 1, "two": 2, "three": 3}
-# Trouver des valeurs avec []
-filled_dict["one"] #=> 1
+# Note : les clés des dictionnaires doivent être de types immuables.
+# Elles doivent être convertibles en une valeur constante pour une recherche rapide.
+# Les types immuables incluent les ints, floats, strings et tuples.
+invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type.
+
+# On trouve une valeur avec []
+filled_dict["one"] # => 1
+
+# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer
+# de list() pour avoir une liste Note: l'ordre n'est pas garanti.
+list(filled_dict.keys()) # => ["three", "two", "one"]
-# Récupérer toutes les clés sous forme de liste avec "keys()"
-filled_dict.keys() #=> ["three", "two", "one"]
-# Note - l'ordre des clés du dictionnaire n'est pas garanti.
-# Vos résultats peuvent différer de ceux ci-dessus.
-# Récupérer toutes les valeurs sous forme de liste avec "values()"
-filled_dict.values() #=> [3, 2, 1]
-# Note - Même remarque qu'au-dessus concernant l'ordre des valeurs.
+# On obtient toutes les valeurs sous forme d'un itérable avec "values()".
+# Là aussi, il faut utiliser list() pour avoir une liste.
+# Note : l'ordre n'est toujours pas garanti.
+list(filled_dict.values()) # => [3, 2, 1]
-# Vérifier l'existence d'une clé dans le dictionnaire avec "in"
-"one" in filled_dict #=> True
-1 in filled_dict #=> False
-# Chercher une clé non existante lève une 'KeyError'
-filled_dict["four"] # KeyError
+# On vérifie la présence d'une clé dans un dictionnaire avec "in"
+"one" in filled_dict # => True
+1 in filled_dict # => False
-# Utiliser la méthode "get()" pour éviter 'KeyError'
-filled_dict.get("one") #=> 1
-filled_dict.get("four") #=> None
-# La méthode get() prend un argument par défaut quand la valeur est inexistante
-filled_dict.get("one", 4) #=> 1
-filled_dict.get("four", 4) #=> 4
+# L'accès à une clé non-existente lève une KeyError
+filled_dict["four"] # KeyError
-# La méthode "setdefault()" permet d'ajouter de manière sécuris une paire clé-valeur dans le dictionnnaire
-filled_dict.setdefault("five", 5) #filled_dict["five"] vaut 5
-filled_dict.setdefault("five", 6) #filled_dict["five"] is toujours 5
+# On utilise "get()" pour éviter la KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante.
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente.
+filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5
-# Les sets stockent ... des sets
+# Ajouter à un dictionnaire
+filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 # une autre méthode
+
+# Enlever des clés d'un dictionnaire avec del
+del filled_dict["one"] # Enlever la clé "one" de filled_dict.
+
+
+# Les sets stockent des ensembles
empty_set = set()
-# On initialise un "set()" avec tout un tas de valeurs
-some_set = set([1,2,2,3,4]) # some_set vaut maintenant set([1, 2, 3, 4])
+# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé.
+some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4}
+
+# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables.
+invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
-# Depuis Python 2.7, {} peut être utilisé pour déclarer un 'set'
-filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+# On peut changer un set :
+filled_set = some_set
-# Ajouter plus d'éléments au set
-filled_set.add(5) # filled_set contient maintenant {1, 2, 3, 4, 5}
+# Ajouter un objet au set :
+filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5}
-# Intersection de sets avec &
+# Chercher les intersections de deux sets avec &
other_set = {3, 4, 5, 6}
-filled_set & other_set #=> {3, 4, 5}
+filled_set & other_set # => {3, 4, 5}
-# Union de sets avec |
-filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+# On fait l'union de sets avec |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-# Différence de sets avec -
-{1,2,3,4} - {2,3,5} #=> {1, 4}
+# On fait la différence de deux sets avec -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# On vérifie la présence d'un objet dans un set avec in
+2 in filled_set # => True
+10 in filled_set # => False
-# Vérifier l'existence d'une valeur dans un set avec "in"
-2 in filled_set #=> True
-10 in filled_set #=> False
####################################################
-## 3. Structure de contrôle
+## 3. Structures de contrôle et Itérables
####################################################
-# Initialisons une variable
+# On crée juste une variable
some_var = 5
-# Voici une condition 'if'. L'indentation est significative en Python !
-# Affiche "some_var est inférieur à 10"
+# Voici une condition "si". L'indentation est significative en Python!
+# Affiche: "some_var is smaller than 10"
if some_var > 10:
- print "some_var est supérieur à 10."
-elif some_var < 10: # La clause elif est optionnelle
- print "some_var iinférieur à 10."
-else: # La clause else également
- print "some_var vaut 10."
+ print("some_var is totally bigger than 10.")
+elif some_var < 10: # La clause elif ("sinon si") est optionelle
+ print("some_var is smaller than 10.")
+else: # La clause else ("sinon") l'est aussi.
+ print("some_var is indeed 10.")
"""
-Les boucles "for" permettent d'itérer sur les listes
+Les boucles "for" itèrent sur une liste
Affiche:
- chien : mammifère
- chat : mammifère
- souris : mammifère
+ chien est un mammifère
+ chat est un mammifère
+ souris est un mammifère
"""
for animal in ["chien", "chat", "souris"]:
- # On peut utiliser % pour l'interpolation des chaînes formattées
- print "%s : mammifère" % animal
+ # On peut utiliser format() pour interpoler des chaînes formattées
+ print("{} est un mammifère".format(animal))
"""
-"range(number)" retourne une liste de nombres
-de 0 au nombre donné
+"range(nombre)" retourne un itérable de nombres
+de zéro au nombre donné
Affiche:
0
1
@@ -295,10 +379,34 @@ Affiche:
3
"""
for i in range(4):
- print i
+ print(i)
+
+"""
+"range(debut, fin)" retourne un itérable de nombre
+de debut à fin.
+Affiche:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
"""
-Les boucles "while" boucle jusqu'à ce que leur condition ne soit plus vraie
+"range(debut, fin, pas)" retourne un itérable de nombres
+de début à fin en incrémentant de pas.
+Si le pas n'est pas indiqué, la valeur par défaut est 1.
+Affiche:
+ 4
+ 6
+ 8
+"""
+for i in range(4, 8, 2):
+ print(i)
+"""
+
+Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse.
Affiche:
0
1
@@ -307,66 +415,135 @@ Affiche:
"""
x = 0
while x < 4:
- print x
+ print(x)
x += 1 # Raccourci pour x = x + 1
-# Gérer les exceptions avec un bloc try/except
-
-# Fonctionne pour Python 2.6 et ultérieur:
+# On gère les exceptions avec un bloc try/except
try:
- # Utiliser "raise" pour lever une exception
- raise IndexError("This is an index error")
+ # On utilise "raise" pour lever une erreur
+ raise IndexError("Ceci est une erreur d'index")
except IndexError as e:
- pass # Pass ne prend pas d'arguments. Généralement, on gère l'erreur ici.
+ pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici.
+except (TypeError, NameError):
+ pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps.
+else: # Clause optionelle des blocs try/except. Doit être après tous les except.
+ print("Tout va bien!") # Uniquement si aucune exception n'est levée.
+finally: # Éxécuté dans toutes les circonstances.
+ print("On nettoie les ressources ici")
+
+# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# Python offre une abstraction fondamentale : l'Iterable.
+# Un itérable est un objet pouvant être traîté comme une séquence.
+# L'objet retourné par la fonction range() est un itérable.
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable
+
+# On peut boucler dessus
+for i in our_iterable:
+ print(i) # Affiche one, two, three
+
+# Cependant, on ne peut pas accéder aux éléments par leur adresse.
+our_iterable[1] # Lève une TypeError
+
+# Un itérable est un objet qui sait créer un itérateur.
+our_iterator = iter(our_iterable)
+
+# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse.
+# On passe à l'élément suivant avec "next()".
+next(our_iterator) #=> "one"
+
+# Il garde son état quand on itère.
+next(our_iterator) #=> "two"
+next(our_iterator) #=> "three"
+
+# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator
+next(our_iterator) # Lève une StopIteration
+
+# On peut mettre tous les éléments d'un itérateur dans une liste avec list()
+list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
####################################################
## 4. Fonctions
####################################################
-# Utiliser "def" pour créer une nouvelle fonction
+# On utilise "def" pour créer des fonctions
def add(x, y):
- print "x vaut %s et y vaur %s" % (x, y)
- return x + y # Renvoi de valeur avec 'return'
+ print("x est {} et y est {}".format(x, y))
+ return x + y # On retourne une valeur avec return
-# Appeller une fonction avec des paramètres
-add(5, 6) #=> Affichet "x is 5 et y vaut 6" et renvoie 11
+# Appel d'une fonction avec des paramètres :
+add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11
-# Une autre manière d'appeller une fonction, avec les arguments
-add(y=6, x=5) # Les arguments peuvent venir dans n'importe quel ordre.
+# Une autre manière d'appeler une fonction : avec des arguments
+add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre.
-# On peut définir une foncion qui prend un nombre variable de paramètres
+# Définir une fonction qui prend un nombre variable d'arguments
def varargs(*args):
return args
-varargs(1, 2, 3) #=> (1,2,3)
+varargs(1, 2, 3) # => (1, 2, 3)
-
-# On peut également définir une fonction qui prend un nombre
-# variable d'arguments
+# On peut aussi définir une fonction qui prend un nombre variable de paramètres.
def keyword_args(**kwargs):
return kwargs
-# Appelons-là et voyons ce qu'il se passe
-keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+# Appelons la pour voir ce qu'il se passe :
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
-# On peut faire les deux à la fois si on le souhaite
+# On peut aussi faire les deux à la fois :
def all_the_args(*args, **kwargs):
- print args
- print kwargs
+ print(args)
+ print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) affiche:
(1, 2)
{"a": 3, "b": 4}
"""
-# En appellant les fonctions, on peut faire l'inverse des paramètres / arguments !
-# Utiliser * pour développer les paramètres, et ** pour développer les arguments
-params = (1, 2, 3, 4)
-args = {"a": 3, "b": 4}
-all_the_args(*args) # equivaut à foo(1, 2, 3, 4)
-all_the_args(**kwargs) # equivaut à foo(a=3, b=4)
-all_the_args(*args, **kwargs) # equivaut à foo(1, 2, 3, 4, a=3, b=4)
+# En appelant des fonctions, on peut aussi faire l'inverse :
+# utiliser * pour étendre un tuple de paramètres
+# et ** pour étendre un dictionnaire d'arguments.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # équivalent à foo(1, 2, 3, 4)
+all_the_args(**kwargs) # équivalent à foo(a=3, b=4)
+all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4)
+
+# Retourne plusieurs valeurs (avec un tuple)
+def swap(x, y):
+ return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses.
+ # (Note: on peut aussi utiliser des parenthèses)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses
+
+# Portée des fonctions :
+x = 5
+
+def setX(num):
+ # La variable locale x n'est pas la même que la variable globale x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # la variable globale x est maintenant 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
# Python a des fonctions de première classe
def create_adder(x):
@@ -375,67 +552,78 @@ def create_adder(x):
return adder
add_10 = create_adder(10)
-add_10(3) #=> 13
+add_10(3) # => 13
-# Mais également des fonctions anonymes
-(lambda x: x > 2)(3) #=> True
+# Mais aussi des fonctions anonymes
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
-# On trouve aussi des fonctions intégrées plus évoluées
-map(add_10, [1,2,3]) #=> [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+# TODO - Fix for iterables
+# Il y a aussi des fonctions de base
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
-# On peut utiliser la syntaxe des liste pour construire les "maps" et les "filters"
-[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# On peut utiliser les compréhensions de listes pour de jolies maps et filtres.
+# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée.
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Classes
####################################################
-# Une classe est un objet
-class Human(object):
- # Un attribut de classe. Il est partagé par toutes les instances de cette classe.
+# On utilise l'opérateur "class" pour définir une classe
+class Human:
+
+ # Un attribut de la classe. Il est partagé par toutes les instances de la classe.
species = "H. sapiens"
- # Initialiseur basique
+ # L'initialiseur de base. Il est appelé quand la classe est instanciée.
+ # Note : les doubles underscores au début et à la fin sont utilisés pour
+ # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur.
+ # Les méthodes (ou objets ou attributs) comme: __init__, __str__,
+ # __repr__ etc. sont appelés méthodes magiques.
+ # Vous ne devriez pas inventer de noms de ce style.
def __init__(self, name):
- # Assigne le paramètre à l'attribut de l'instance de classe.
+ # Assigner l'argument à l'attribut de l'instance
self.name = name
- # Une méthode de l'instance. Toutes les méthodes prennent "self" comme 1er paramètre.
+ # Une méthode de l'instance. Toutes prennent "self" comme premier argument.
def say(self, msg):
- return "%s: %s" % (self.name, msg)
+ return "{name}: {message}".format(name=self.name, message=msg)
- # Une méthode de classe est partagée par toutes les instances.
- # On les appelle avec le nom de la classe en premier paramètre
+ # Une méthode de classe est partagée avec entre les instances
+ # Ils sont appelés avec la classe comme premier argument
@classmethod
def get_species(cls):
return cls.species
- # Une méthode statique est appellée sans référence à une classe ou à une instance
+ # Une méthode statique est appelée sans référence à une instance ni à une classe.
@staticmethod
def grunt():
return "*grunt*"
-# Instancier une classe
+# Instantier une classe
i = Human(name="Ian")
-print i.say("hi") # Affiche "Ian: hi"
+print(i.say("hi")) # affiche "Ian: hi"
j = Human("Joel")
-print j.say("hello") #Affiche "Joel: hello"
+print(j.say("hello")) # affiche "Joel: hello"
# Appeller notre méthode de classe
-i.get_species() #=> "H. sapiens"
+i.get_species() # => "H. sapiens"
# Changer les attributs partagés
Human.species = "H. neanderthalensis"
-i.get_species() #=> "H. neanderthalensis"
-j.get_species() #=> "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
# Appeller la méthode statique
-Human.grunt() #=> "*grunt*"
+Human.grunt() # => "*grunt*"
####################################################
@@ -444,45 +632,101 @@ Human.grunt() #=> "*grunt*"
# On peut importer des modules
import math
-print math.sqrt(16) #=> 4.0
+print(math.sqrt(16)) # => 4.0
-# Et récupérer des fonctions spécifiques d'un module
+# On peut importer des fonctions spécifiques d'un module
from math import ceil, floor
-print ceil(3.7) #=> 4.0
-print floor(3.7) #=> 3.0
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
-# Récuperer toutes les fonctions d'un module
-# Attention, ce n'est pas recommandé.
+# On peut importer toutes les fonctions d'un module
+# Attention: ce n'est pas recommandé.
from math import *
-# On peut raccourcir le nom d'un module
+# On peut raccourcir un nom de module
import math as m
-math.sqrt(16) == m.sqrt(16) #=> True
+math.sqrt(16) == m.sqrt(16) # => True
-# Les modules Python sont juste des fichiers Python ordinaires.
-# On peut écrire ses propres modules et les importer.
-# Le nom du module doit être le même que le nom du fichier.
+# Les modules Python sont juste des fichiers Python.
+# Vous pouvez écrire les vôtres et les importer. Le nom du module
+# est le nom du fichier.
-# On peut trouver quelle fonction et attributs déterminent un module
+# On peut voir quels fonctions et objets un module définit
import math
dir(math)
+####################################################
+## 7. Avancé
+####################################################
+
+# Les générateurs aident à faire du code paresseux (lazy)
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Un générateur crée des valeurs à la volée.
+# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque
+# itération. Cela signifie que les valeurs supérieures à 30 ne seront pas traîtées par
+# double_numbers.
+# Note : range est un générateur aussi.
+# Créer une liste 1-900000000 prendrait beaucoup de temps
+# On met un underscore à la fin d'un nom de variable normalement réservé par Python.
+range_ = range(1, 900000000)
+# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé
+for i in double_numbers(range_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# Decorateurs
+# Dans cet exemple, beg enveloppe say
+# Beg appellera say. Si say_please vaut True le message retourné sera changé
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print(say()) # affiche Can you buy me a beer?
+print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :(
```
-## Prêt à aller plus loin?
+## Prêt pour encore plus ?
-### En ligne gratuitement
+### En ligne et gratuit (en anglais)
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2.6/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [Python Course](http://www.python-course.eu/index.php)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+
+### En ligne et gratuit (en français)
-### Format papier
+* [Le petit guide des batteries à découvrir](https://he-arc.github.io/livre-python/)
+
+### Livres (en anglais)
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
-
diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown
deleted file mode 100644
index 7112cd90..00000000
--- a/fr-fr/python3-fr.html.markdown
+++ /dev/null
@@ -1,732 +0,0 @@
----
-language: python3
-contributors:
- - ["Louie Dinh", "http://pythonpracticeprojects.com"]
- - ["Steven Basart", "http://github.com/xksteven"]
- - ["Andre Polykanine", "https://github.com/Oire"]
- - ["Zachary Ferguson", "http://github.com/zfergus2"]
-translators:
- - ["Gnomino", "https://github.com/Gnomino"]
- - ["Julien M'Poy", "http://github.com/groovytron"]
-filename: learnpython3-fr.py
-lang: fr-fr
----
-
-Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des
-langages les plus populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe.
-C'est tout simplement du pseudo-code exécutable.
-
-L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service]
-
-Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7
-
-```python
-
-# Un commentaire d'une ligne commence par un dièse
-
-""" Les chaînes de caractères peuvent être écrites
- avec 3 guillemets doubles ("), et sont souvent
- utilisées comme des commentaires.
-"""
-
-####################################################
-## 1. Types de données primaires et opérateurs
-####################################################
-
-# On a des nombres
-3 # => 3
-
-# Les calculs sont ce à quoi on s'attend
-1 + 1 # => 2
-8 - 1 # => 7
-10 * 2 # => 20
-
-# Sauf pour la division qui retourne un float (nombre à virgule flottante)
-35 / 5 # => 7.0
-
-# Résultats de divisions entières tronqués pour les nombres positifs et négatifs
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # works on floats too
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
-
-# Quand on utilise un float, le résultat est un float
-3 * 2.0 # => 6.0
-
-# Modulo (reste de la division)
-7 % 3 # => 1
-
-# Exponentiation (x**y, x élevé à la puissance y)
-2**4 # => 16
-
-# Forcer la priorité de calcul avec des parenthèses
-(1 + 3) * 2 # => 8
-
-# Les valeurs booléennes sont primitives
-True
-False
-
-# Négation avec not
-not True # => False
-not False # => True
-
-# Opérateurs booléens
-# On note que "and" et "or" sont sensibles à la casse
-True and False #=> False
-False or True #=> True
-
-# Utilisation des opérations booléennes avec des entiers :
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
-
-# On vérifie une égalité avec ==
-1 == 1 # => True
-2 == 1 # => False
-
-# On vérifie une inégalité avec !=
-1 != 1 # => False
-2 != 1 # => True
-
-# Autres opérateurs de comparaison
-1 < 10 # => True
-1 > 10 # => False
-2 <= 2 # => True
-2 >= 2 # => True
-
-# On peut enchaîner les comparaisons
-1 < 2 < 3 # => True
-2 < 3 < 2 # => False
-
-# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie
-# si les objets ont la même valeur.
-a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4]
-b = a # b pointe sur a
-b is a # => True, a et b pointent sur le même objet
-b == a # => True, les objets a et b sont égaux
-b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4]
-b is a # => False, a et b ne pointent pas sur le même objet
-b == a # => True, les objets a et b ne pointent pas sur le même objet
-
-# Les chaînes (ou strings) sont créées avec " ou '
-"Ceci est une chaine"
-'Ceci est une chaine aussi.'
-
-# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire.
-"Hello " + "world!" # => "Hello world!"
-# On peut aussi le faire sans utiliser '+'
-"Hello " "world!" # => "Hello world!"
-
-# On peut traîter une chaîne comme une liste de caractères
-"This is a string"[0] # => 'T'
-
-# .format peut être utilisé pour formatter des chaînes, comme ceci:
-"{} peuvent etre {}".format("Les chaînes", "interpolées")
-
-# On peut aussi réutiliser le même argument pour gagner du temps.
-"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
-#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
-
-# On peut aussi utiliser des mots clés pour éviter de devoir compter.
-"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
-
-# Il est également possible d'utiliser les f-strings depuis Python 3.6 (https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals)
-name = "Fred"
-f"Il a dit que son nom est {name}." #=> "Il a dit que son nom est Fred."
-
-# Si votre code doit aussi être compatible avec Python 2.5 et moins,
-# vous pouvez encore utiliser l'ancienne syntaxe :
-"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille")
-
-
-# None est un objet
-None # => None
-
-# N'utilisez pas "==" pour comparer des objets à None
-# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets.
-"etc" is None # => False
-None is None # => True
-
-# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens.
-# Toutes les autres valeurs valent True
-bool(0) # => False
-bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
-
-
-####################################################
-## 2. Variables et Collections
-####################################################
-
-# Python a une fonction print pour afficher du texte
-print("I'm Python. Nice to meet you!")
-
-# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin.
-# Utilisez l'argument optionnel end pour changer ce caractère de fin.
-print("Hello, World", end="!") # => Hello, World!
-
-# Pas besoin de déclarer des variables avant de les définir.
-# La convention est de nommer ses variables avec des minuscules_et_underscores
-some_var = 5
-some_var # => 5
-
-# Tenter d'accéder à une variable non définie lève une exception.
-# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions.
-une_variable_inconnue # Lève une NameError
-
-# Les listes permettent de stocker des séquences
-li = []
-# On peut initialiser une liste pré-remplie
-other_li = [4, 5, 6]
-
-# On ajoute des objets à la fin d'une liste avec .append
-li.append(1) # li vaut maintenant [1]
-li.append(2) # li vaut maintenant [1, 2]
-li.append(4) # li vaut maintenant [1, 2, 4]
-li.append(3) # li vaut maintenant [1, 2, 4, 3]
-# On enlève le dernier élément avec .pop
-li.pop() # => 3 et li vaut maintenant [1, 2, 4]
-# Et on le remet
-li.append(3) # li vaut de nouveau [1, 2, 4, 3]
-
-# Accès à un élément d'une liste :
-li[0] # => 1
-# Accès au dernier élément :
-li[-1] # => 3
-
-# Accéder à un élément en dehors des limites lève une IndexError
-li[4] # Lève une IndexError
-
-# On peut accéder à une intervalle avec la syntaxe "slice"
-# (c'est un rang du type "fermé/ouvert")
-li[1:3] # => [2, 4]
-# Omettre les deux premiers éléments
-li[2:] # => [4, 3]
-# Prendre les trois premiers
-li[:3] # => [1, 2, 4]
-# Sélectionner un élément sur deux
-li[::2] # =>[1, 4]
-# Avoir une copie de la liste à l'envers
-li[::-1] # => [3, 4, 2, 1]
-# Pour des "slices" plus élaborées :
-# li[debut:fin:pas]
-
-# Faire une copie d'une profondeur de un avec les "slices"
-li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False.
-
-# Enlever des éléments arbitrairement d'une liste
-del li[2] # li is now [1, 2, 3]
-
-# On peut additionner des listes
-# Note: les valeurs de li et other_li ne sont pas modifiées.
-li + other_li # => [1, 2, 3, 4, 5, 6]
-
-# Concaténer des listes avec "extend()"
-li.extend(other_li) # Maintenant li contient [1, 2, 3, 4, 5, 6]
-
-# Vérifier la présence d'un objet dans une liste avec "in"
-1 in li # => True
-
-# Examiner la longueur avec "len()"
-len(li) # => 6
-
-
-# Les tuples sont comme des listes mais sont immuables.
-tup = (1, 2, 3)
-tup[0] # => 1
-tup[0] = 3 # Lève une TypeError
-
-# Note : un tuple de taille un doit avoir une virgule après le dernier élément,
-# mais ce n'est pas le cas des tuples d'autres tailles, même zéro.
-type((1)) # => <class 'int'>
-type((1,)) # => <class 'tuple'>
-type(()) # => <class 'tuple'>
-
-# On peut utiliser la plupart des opérations des listes sur des tuples.
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
-
-# Vous pouvez décomposer des tuples (ou des listes) dans des variables
-a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3
-# Les tuples sont créés par défaut sans parenthèses
-d, e, f = 4, 5, 6
-# Voyez comme il est facile d'intervertir deux valeurs :
-e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4
-
-
-# Créer un dictionnaire :
-empty_dict = {}
-# Un dictionnaire pré-rempli :
-filled_dict = {"one": 1, "two": 2, "three": 3}
-
-# Note : les clés des dictionnaires doivent être de types immuables.
-# Elles doivent être convertibles en une valeur constante pour une recherche rapide.
-# Les types immuables incluent les ints, floats, strings et tuples.
-invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list'
-valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type.
-
-# On trouve une valeur avec []
-filled_dict["one"] # => 1
-
-# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer
-# de list() pour avoir une liste Note: l'ordre n'est pas garanti.
-list(filled_dict.keys()) # => ["three", "two", "one"]
-
-
-# On obtient toutes les valeurs sous forme d'un itérable avec "values()".
-# Là aussi, il faut utiliser list() pour avoir une liste.
-# Note : l'ordre n'est toujours pas garanti.
-list(filled_dict.values()) # => [3, 2, 1]
-
-
-# On vérifie la présence d'une clé dans un dictionnaire avec "in"
-"one" in filled_dict # => True
-1 in filled_dict # => False
-
-# L'accès à une clé non-existente lève une KeyError
-filled_dict["four"] # KeyError
-
-# On utilise "get()" pour éviter la KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
-# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante.
-filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
-
-# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente.
-filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5
-filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5
-
-# Ajouter à un dictionnaire
-filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
-#filled_dict["four"] = 4 # une autre méthode
-
-# Enlever des clés d'un dictionnaire avec del
-del filled_dict["one"] # Enlever la clé "one" de filled_dict.
-
-
-# Les sets stockent des ensembles
-empty_set = set()
-# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé.
-some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4}
-
-# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables.
-invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list'
-valid_set = {(1,), 1}
-
-# On peut changer un set :
-filled_set = some_set
-
-# Ajouter un objet au set :
-filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5}
-
-# Chercher les intersections de deux sets avec &
-other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
-
-# On fait l'union de sets avec |
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-
-# On fait la différence de deux sets avec -
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
-
-# On vérifie la présence d'un objet dans un set avec in
-2 in filled_set # => True
-10 in filled_set # => False
-
-
-
-####################################################
-## 3. Structures de contrôle et Itérables
-####################################################
-
-# On crée juste une variable
-some_var = 5
-
-# Voici une condition "si". L'indentation est significative en Python!
-# Affiche: "some_var is smaller than 10"
-if some_var > 10:
- print("some_var is totally bigger than 10.")
-elif some_var < 10: # La clause elif ("sinon si") est optionelle
- print("some_var is smaller than 10.")
-else: # La clause else ("sinon") l'est aussi.
- print("some_var is indeed 10.")
-
-
-"""
-Les boucles "for" itèrent sur une liste
-Affiche:
- chien est un mammifère
- chat est un mammifère
- souris est un mammifère
-"""
-for animal in ["chien", "chat", "souris"]:
- # On peut utiliser format() pour interpoler des chaînes formattées
- print("{} est un mammifère".format(animal))
-
-"""
-"range(nombre)" retourne un itérable de nombres
-de zéro au nombre donné
-Affiche:
- 0
- 1
- 2
- 3
-"""
-for i in range(4):
- print(i)
-
-"""
-"range(debut, fin)" retourne un itérable de nombre
-de debut à fin.
-Affiche:
- 4
- 5
- 6
- 7
-"""
-for i in range(4, 8):
- print(i)
-
-"""
-"range(debut, fin, pas)" retourne un itérable de nombres
-de début à fin en incrémentant de pas.
-Si le pas n'est pas indiqué, la valeur par défaut est 1.
-Affiche:
- 4
- 6
- 8
-"""
-for i in range(4, 8, 2):
- print(i)
-"""
-
-Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse.
-Affiche:
- 0
- 1
- 2
- 3
-"""
-x = 0
-while x < 4:
- print(x)
- x += 1 # Raccourci pour x = x + 1
-
-# On gère les exceptions avec un bloc try/except
-try:
- # On utilise "raise" pour lever une erreur
- raise IndexError("Ceci est une erreur d'index")
-except IndexError as e:
- pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici.
-except (TypeError, NameError):
- pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps.
-else: # Clause optionelle des blocs try/except. Doit être après tous les except.
- print("Tout va bien!") # Uniquement si aucune exception n'est levée.
-finally: # Éxécuté dans toutes les circonstances.
- print("On nettoie les ressources ici")
-
-# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with
-with open("myfile.txt") as f:
- for line in f:
- print(line)
-
-# Python offre une abstraction fondamentale : l'Iterable.
-# Un itérable est un objet pouvant être traîté comme une séquence.
-# L'objet retourné par la fonction range() est un itérable.
-
-filled_dict = {"one": 1, "two": 2, "three": 3}
-our_iterable = filled_dict.keys()
-print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable
-
-# On peut boucler dessus
-for i in our_iterable:
- print(i) # Affiche one, two, three
-
-# Cependant, on ne peut pas accéder aux éléments par leur adresse.
-our_iterable[1] # Lève une TypeError
-
-# Un itérable est un objet qui sait créer un itérateur.
-our_iterator = iter(our_iterable)
-
-# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse.
-# On passe à l'élément suivant avec "next()".
-next(our_iterator) #=> "one"
-
-# Il garde son état quand on itère.
-next(our_iterator) #=> "two"
-next(our_iterator) #=> "three"
-
-# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator
-next(our_iterator) # Lève une StopIteration
-
-# On peut mettre tous les éléments d'un itérateur dans une liste avec list()
-list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
-
-
-####################################################
-## 4. Fonctions
-####################################################
-
-# On utilise "def" pour créer des fonctions
-def add(x, y):
- print("x est {} et y est {}".format(x, y))
- return x + y # On retourne une valeur avec return
-
-# Appel d'une fonction avec des paramètres :
-add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11
-
-# Une autre manière d'appeler une fonction : avec des arguments
-add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre.
-
-# Définir une fonction qui prend un nombre variable d'arguments
-def varargs(*args):
- return args
-
-varargs(1, 2, 3) # => (1, 2, 3)
-
-# On peut aussi définir une fonction qui prend un nombre variable de paramètres.
-def keyword_args(**kwargs):
- return kwargs
-
-# Appelons la pour voir ce qu'il se passe :
-keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
-
-
-# On peut aussi faire les deux à la fois :
-def all_the_args(*args, **kwargs):
- print(args)
- print(kwargs)
-"""
-all_the_args(1, 2, a=3, b=4) affiche:
- (1, 2)
- {"a": 3, "b": 4}
-"""
-
-# En appelant des fonctions, on peut aussi faire l'inverse :
-# utiliser * pour étendre un tuple de paramètres
-# et ** pour étendre un dictionnaire d'arguments.
-args = (1, 2, 3, 4)
-kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # équivalent à foo(1, 2, 3, 4)
-all_the_args(**kwargs) # équivalent à foo(a=3, b=4)
-all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4)
-
-# Retourne plusieurs valeurs (avec un tuple)
-def swap(x, y):
- return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses.
- # (Note: on peut aussi utiliser des parenthèses)
-
-x = 1
-y = 2
-x, y = swap(x, y) # => x = 2, y = 1
-# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses
-
-# Portée des fonctions :
-x = 5
-
-def setX(num):
- # La variable locale x n'est pas la même que la variable globale x
- x = num # => 43
- print (x) # => 43
-
-def setGlobalX(num):
- global x
- print (x) # => 5
- x = num # la variable globale x est maintenant 6
- print (x) # => 6
-
-setX(43)
-setGlobalX(6)
-
-
-# Python a des fonctions de première classe
-def create_adder(x):
- def adder(y):
- return x + y
- return adder
-
-add_10 = create_adder(10)
-add_10(3) # => 13
-
-# Mais aussi des fonctions anonymes
-(lambda x: x > 2)(3) # => True
-(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
-
-# TODO - Fix for iterables
-# Il y a aussi des fonctions de base
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
-
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-
-# On peut utiliser les compréhensions de listes pour de jolies maps et filtres.
-# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée.
-[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
-
-####################################################
-## 5. Classes
-####################################################
-
-
-# On utilise l'opérateur "class" pour définir une classe
-class Human:
-
- # Un attribut de la classe. Il est partagé par toutes les instances de la classe.
- species = "H. sapiens"
-
- # L'initialiseur de base. Il est appelé quand la classe est instanciée.
- # Note : les doubles underscores au début et à la fin sont utilisés pour
- # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur.
- # Les méthodes (ou objets ou attributs) comme: __init__, __str__,
- # __repr__ etc. sont appelés méthodes magiques.
- # Vous ne devriez pas inventer de noms de ce style.
- def __init__(self, name):
- # Assigner l'argument à l'attribut de l'instance
- self.name = name
-
- # Une méthode de l'instance. Toutes prennent "self" comme premier argument.
- def say(self, msg):
- return "{name}: {message}".format(name=self.name, message=msg)
-
- # Une méthode de classe est partagée avec entre les instances
- # Ils sont appelés avec la classe comme premier argument
- @classmethod
- def get_species(cls):
- return cls.species
-
- # Une méthode statique est appelée sans référence à une instance ni à une classe.
- @staticmethod
- def grunt():
- return "*grunt*"
-
-
-# Instantier une classe
-i = Human(name="Ian")
-print(i.say("hi")) # affiche "Ian: hi"
-
-j = Human("Joel")
-print(j.say("hello")) # affiche "Joel: hello"
-
-# Appeller notre méthode de classe
-i.get_species() # => "H. sapiens"
-
-# Changer les attributs partagés
-Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
-
-# Appeller la méthode statique
-Human.grunt() # => "*grunt*"
-
-
-####################################################
-## 6. Modules
-####################################################
-
-# On peut importer des modules
-import math
-print(math.sqrt(16)) # => 4.0
-
-# On peut importer des fonctions spécifiques d'un module
-from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
-
-# On peut importer toutes les fonctions d'un module
-# Attention: ce n'est pas recommandé.
-from math import *
-
-# On peut raccourcir un nom de module
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
-
-# Les modules Python sont juste des fichiers Python.
-# Vous pouvez écrire les vôtres et les importer. Le nom du module
-# est le nom du fichier.
-
-# On peut voir quels fonctions et objets un module définit
-import math
-dir(math)
-
-
-####################################################
-## 7. Avancé
-####################################################
-
-# Les générateurs aident à faire du code paresseux (lazy)
-def double_numbers(iterable):
- for i in iterable:
- yield i + i
-
-# Un générateur crée des valeurs à la volée.
-# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque
-# itération. Cela signifie que les valeurs supérieures à 30 ne seront pas traîtées par
-# double_numbers.
-# Note : range est un générateur aussi.
-# Créer une liste 1-900000000 prendrait beaucoup de temps
-# On met un underscore à la fin d'un nom de variable normalement réservé par Python.
-range_ = range(1, 900000000)
-# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé
-for i in double_numbers(range_):
- print(i)
- if i >= 30:
- break
-
-
-# Decorateurs
-# Dans cet exemple, beg enveloppe say
-# Beg appellera say. Si say_please vaut True le message retourné sera changé
-from functools import wraps
-
-
-def beg(target_function):
- @wraps(target_function)
- def wrapper(*args, **kwargs):
- msg, say_please = target_function(*args, **kwargs)
- if say_please:
- return "{} {}".format(msg, "Please! I am poor :(")
- return msg
-
- return wrapper
-
-
-@beg
-def say(say_please=False):
- msg = "Can you buy me a beer?"
- return msg, say_please
-
-
-print(say()) # affiche Can you buy me a beer?
-print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :(
-```
-
-## Prêt pour encore plus ?
-
-### En ligne et gratuit (en anglais)
-
-* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
-* [Python Course](http://www.python-course.eu/index.php)
-* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
-
-### En ligne et gratuit (en français)
-
-* [Le petit guide des batteries à découvrir](https://he-arc.github.io/livre-python/)
-
-### Livres (en anglais)
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/fr-fr/pythonlegacy-fr.html.markdown b/fr-fr/pythonlegacy-fr.html.markdown
new file mode 100644
index 00000000..10b1a0a6
--- /dev/null
+++ b/fr-fr/pythonlegacy-fr.html.markdown
@@ -0,0 +1,488 @@
+---
+language: Python 2 (legacy)
+filename: learnpythonlegacy-fr.py
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+translators:
+ - ["Sylvain Zyssman", "https://github.com/sylzys"]
+ - ["Nami-Doc", "https://github.com/Nami-Doc"]
+lang: fr-fr
+---
+
+Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de programmation les plus populaires.
+Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiquement du pseudo-code exécutable.
+
+Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service]
+
+N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/).
+
+```python
+# Une ligne simple de commentaire commence par un dièse
+""" Les lignes de commentaires multipes peuvent être écrites
+ en utilisant 3 guillemets ("), et sont souvent utilisées
+ pour les commentaires
+"""
+
+####################################################
+## 1. Types Primaires et Opérateurs
+####################################################
+
+# Les nombres
+3 #=> 3
+
+# Les calculs produisent les résultats mathématiques escomptés
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# La division est un peu spéciale. C'est une division d'entiers, et Python arrondi le résultat par défaut automatiquement.
+5 / 2 #=> 2
+
+# Pour corriger ce problème, on utilise les float.
+2.0 # Voici un float
+11.0 / 4.0 #=> 2.75 ahhh... beaucoup mieux
+
+# Forcer la priorité avec les parenthèses
+(1 + 3) * 2 #=> 8
+
+# Les valeurs booléenes sont de type primitif
+True
+False
+
+# Pour la négation, on utilise "not"
+not True #=> False
+not False #=> True
+
+# Pour l'égalité, ==
+1 == 1 #=> True
+2 == 1 #=> False
+
+# L'inégalité est symbolisée par !=
+1 != 1 #=> False
+2 != 1 #=> True
+
+# D'autres comparateurs
+1 < 10 #=> True
+1 > 10 #=> False
+2 <= 2 #=> True
+2 >= 2 #=> True
+
+# On peut enchaîner les comparateurs !
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
+
+# Les chaînes de caractères sont créées avec " ou '
+"C'est une chaîne."
+'C\'est aussi une chaîne.'
+
+# On peut aussi les "additioner" !
+"Hello " + "world!" #=> "Hello world!"
+
+# Une chaîne peut être traitée comme une liste de caractères
+"C'est une chaîne"[0] #=> 'C'
+
+# % peut être utilisé pour formatter des chaîne, comme ceci:
+"%s can be %s" % ("strings", "interpolated")
+
+# Une autre manière de formatter les chaînes de caractères est d'utiliser la méthode 'format'
+# C'est la méthode à privilégier
+"{0} peut être {1}".format("La chaîne", "formattée")
+# On peut utiliser des mot-clés au lieu des chiffres.
+"{name} veut manger des {food}".format(name="Bob", food="lasagnes")
+
+# None est un objet
+None #=> None
+
+# Ne pas utiliser le symbole d'inégalité "==" pour comparer des objet à None
+# Il faut utiliser "is"
+"etc" is None #=> False
+None is None #=> True
+
+# L'opérateur 'is' teste l'identité de l'objet.
+# Ce n'est pas très utilisé avec les types primitifs, mais cela peut être très utile
+# lorsque l'on utilise des objets.
+
+# None, 0, et les chaînes de caractères vides valent False.
+# Toutes les autres valeurs valent True
+0 == False #=> True
+"" == False #=> True
+
+
+####################################################
+## 2. Variables et Collections
+####################################################
+
+# Afficher du texte, c'est facile
+print "Je suis Python. Enchanté!"
+
+
+# Il n'y a pas besoin de déclarer les variables avant de les assigner.
+some_var = 5 # La convention veut que l'on utilise des minuscules_avec_underscores
+some_var #=> 5
+
+# Accéder à une variable non assignée lève une exception
+# Voyez les structures de contrôle pour en apprendre plus sur la gestion des exceptions.
+some_other_var # Lève une exception
+
+# 'if' peut être utilisé comme expression
+"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+
+# Listes
+li = []
+# On peut remplir liste dès l'instanciation
+other_li = [4, 5, 6]
+
+# On ajoute des éléments avec 'append'
+li.append(1) #li contient [1]
+li.append(2) #li contient [1, 2]
+li.append(4) #li contient [1, 2, 4]
+li.append(3) #li contient [1, 2, 4, 3]
+
+# Et on les supprime avec 'pop'
+li.pop() #=> 3 et li contient [1, 2, 4]
+# Remettons-le dans la liste
+li.append(3) # li contient [1, 2, 4, 3] de nouveau.
+
+# On accède aux éléments d'une liste comme à ceux un tableau.
+li[0] #=> 1
+# Le dernier élément
+li[-1] #=> 3
+
+# Accèder aux indices hors limite lève une exception
+li[4] # Lève un 'IndexError'
+
+# On peut accèder à des rangs de valeurs avec la syntaxe "slice"
+# (C'est un rang de type 'fermé/ouvert' pour les plus matheux)
+li[1:3] #=> [2, 4]
+# Sans spécifier de fin de rang, on "saute" le début de la liste
+li[2:] #=> [4, 3]
+# Sans spécifier de début de rang, on "saute" la fin de la liste
+li[:3] #=> [1, 2, 4]
+
+# Retirer un élément spécifique dee la liste avec "del"
+del li[2] # li contient [1, 2, 3]
+
+# On peut additionner des listes entre elles
+li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li et other_li existent toujours à part entière
+
+# Concaténer des listes avec "extend()"
+li.extend(other_li) # li vaut maintenant [1, 2, 3, 4, 5, 6]
+
+# Vérifier l'existence d'un élément dans une liste avec "in"
+1 in li #=> True
+
+# Récupérer la longueur avec "len()"
+len(li) #=> 6
+
+
+# Les "tuples" sont comme des listes, mais sont immuables.
+tup = (1, 2, 3)
+tup[0] #=> 1
+tup[0] = 3 # Lève un 'TypeError'
+
+# Mais vous pouvez faire tout ceci sur les tuples:
+len(tup) #=> 3
+tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
+tup[:2] #=> (1, 2)
+2 in tup #=> True
+
+# Vous pouvez "dé-packager" les tuples (ou les listes) dans des variables
+a, b, c = (1, 2, 3) # a vaut maintenant 1, b vaut maintenant 2 and c vaut maintenant 3
+# Sans parenthèses, un tuple est créé par défaut
+d, e, f = 4, 5, 6
+# Voyez maintenant comme il est facile d'inverser 2 valeurs
+e, d = d, e # d is now 5 and e is now 4
+
+
+# Dictionnaires
+empty_dict = {}
+# Un dictionnaire pré-rempli
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Trouver des valeurs avec []
+filled_dict["one"] #=> 1
+
+# Récupérer toutes les clés sous forme de liste avec "keys()"
+filled_dict.keys() #=> ["three", "two", "one"]
+# Note - l'ordre des clés du dictionnaire n'est pas garanti.
+# Vos résultats peuvent différer de ceux ci-dessus.
+
+# Récupérer toutes les valeurs sous forme de liste avec "values()"
+filled_dict.values() #=> [3, 2, 1]
+# Note - Même remarque qu'au-dessus concernant l'ordre des valeurs.
+
+# Vérifier l'existence d'une clé dans le dictionnaire avec "in"
+"one" in filled_dict #=> True
+1 in filled_dict #=> False
+
+# Chercher une clé non existante lève une 'KeyError'
+filled_dict["four"] # KeyError
+
+# Utiliser la méthode "get()" pour éviter 'KeyError'
+filled_dict.get("one") #=> 1
+filled_dict.get("four") #=> None
+# La méthode get() prend un argument par défaut quand la valeur est inexistante
+filled_dict.get("one", 4) #=> 1
+filled_dict.get("four", 4) #=> 4
+
+# La méthode "setdefault()" permet d'ajouter de manière sécuris une paire clé-valeur dans le dictionnnaire
+filled_dict.setdefault("five", 5) #filled_dict["five"] vaut 5
+filled_dict.setdefault("five", 6) #filled_dict["five"] is toujours 5
+
+
+# Les sets stockent ... des sets
+empty_set = set()
+# On initialise un "set()" avec tout un tas de valeurs
+some_set = set([1,2,2,3,4]) # some_set vaut maintenant set([1, 2, 3, 4])
+
+# Depuis Python 2.7, {} peut être utilisé pour déclarer un 'set'
+filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+
+# Ajouter plus d'éléments au set
+filled_set.add(5) # filled_set contient maintenant {1, 2, 3, 4, 5}
+
+# Intersection de sets avec &
+other_set = {3, 4, 5, 6}
+filled_set & other_set #=> {3, 4, 5}
+
+# Union de sets avec |
+filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+
+# Différence de sets avec -
+{1,2,3,4} - {2,3,5} #=> {1, 4}
+
+# Vérifier l'existence d'une valeur dans un set avec "in"
+2 in filled_set #=> True
+10 in filled_set #=> False
+
+
+####################################################
+## 3. Structure de contrôle
+####################################################
+
+# Initialisons une variable
+some_var = 5
+
+# Voici une condition 'if'. L'indentation est significative en Python !
+# Affiche "some_var est inférieur à 10"
+if some_var > 10:
+ print "some_var est supérieur à 10."
+elif some_var < 10: # La clause elif est optionnelle
+ print "some_var iinférieur à 10."
+else: # La clause else également
+ print "some_var vaut 10."
+
+
+"""
+Les boucles "for" permettent d'itérer sur les listes
+Affiche:
+ chien : mammifère
+ chat : mammifère
+ souris : mammifère
+"""
+for animal in ["chien", "chat", "souris"]:
+ # On peut utiliser % pour l'interpolation des chaînes formattées
+ print "%s : mammifère" % animal
+
+"""
+"range(number)" retourne une liste de nombres
+de 0 au nombre donné
+Affiche:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+Les boucles "while" boucle jusqu'à ce que leur condition ne soit plus vraie
+Affiche:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Raccourci pour x = x + 1
+
+# Gérer les exceptions avec un bloc try/except
+
+# Fonctionne pour Python 2.6 et ultérieur:
+try:
+ # Utiliser "raise" pour lever une exception
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # Pass ne prend pas d'arguments. Généralement, on gère l'erreur ici.
+
+
+####################################################
+## 4. Fonctions
+####################################################
+
+# Utiliser "def" pour créer une nouvelle fonction
+def add(x, y):
+ print "x vaut %s et y vaur %s" % (x, y)
+ return x + y # Renvoi de valeur avec 'return'
+
+# Appeller une fonction avec des paramètres
+add(5, 6) #=> Affichet "x is 5 et y vaut 6" et renvoie 11
+
+# Une autre manière d'appeller une fonction, avec les arguments
+add(y=6, x=5) # Les arguments peuvent venir dans n'importe quel ordre.
+
+# On peut définir une foncion qui prend un nombre variable de paramètres
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) #=> (1,2,3)
+
+
+# On peut également définir une fonction qui prend un nombre
+# variable d'arguments
+def keyword_args(**kwargs):
+ return kwargs
+
+# Appelons-là et voyons ce qu'il se passe
+keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+
+# On peut faire les deux à la fois si on le souhaite
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) affiche:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# En appellant les fonctions, on peut faire l'inverse des paramètres / arguments !
+# Utiliser * pour développer les paramètres, et ** pour développer les arguments
+params = (1, 2, 3, 4)
+args = {"a": 3, "b": 4}
+all_the_args(*args) # equivaut à foo(1, 2, 3, 4)
+all_the_args(**kwargs) # equivaut à foo(a=3, b=4)
+all_the_args(*args, **kwargs) # equivaut à foo(1, 2, 3, 4, a=3, b=4)
+
+# Python a des fonctions de première classe
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) #=> 13
+
+# Mais également des fonctions anonymes
+(lambda x: x > 2)(3) #=> True
+
+# On trouve aussi des fonctions intégrées plus évoluées
+map(add_10, [1,2,3]) #=> [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+
+# On peut utiliser la syntaxe des liste pour construire les "maps" et les "filters"
+[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+
+####################################################
+## 5. Classes
+####################################################
+
+# Une classe est un objet
+class Human(object):
+
+ # Un attribut de classe. Il est partagé par toutes les instances de cette classe.
+ species = "H. sapiens"
+
+ # Initialiseur basique
+ def __init__(self, name):
+ # Assigne le paramètre à l'attribut de l'instance de classe.
+ self.name = name
+
+ # Une méthode de l'instance. Toutes les méthodes prennent "self" comme 1er paramètre.
+ def say(self, msg):
+ return "%s: %s" % (self.name, msg)
+
+ # Une méthode de classe est partagée par toutes les instances.
+ # On les appelle avec le nom de la classe en premier paramètre
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Une méthode statique est appellée sans référence à une classe ou à une instance
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# Instancier une classe
+i = Human(name="Ian")
+print i.say("hi") # Affiche "Ian: hi"
+
+j = Human("Joel")
+print j.say("hello") #Affiche "Joel: hello"
+
+# Appeller notre méthode de classe
+i.get_species() #=> "H. sapiens"
+
+# Changer les attributs partagés
+Human.species = "H. neanderthalensis"
+i.get_species() #=> "H. neanderthalensis"
+j.get_species() #=> "H. neanderthalensis"
+
+# Appeller la méthode statique
+Human.grunt() #=> "*grunt*"
+
+
+####################################################
+## 6. Modules
+####################################################
+
+# On peut importer des modules
+import math
+print math.sqrt(16) #=> 4.0
+
+# Et récupérer des fonctions spécifiques d'un module
+from math import ceil, floor
+print ceil(3.7) #=> 4.0
+print floor(3.7) #=> 3.0
+
+# Récuperer toutes les fonctions d'un module
+# Attention, ce n'est pas recommandé.
+from math import *
+
+# On peut raccourcir le nom d'un module
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Les modules Python sont juste des fichiers Python ordinaires.
+# On peut écrire ses propres modules et les importer.
+# Le nom du module doit être le même que le nom du fichier.
+
+# On peut trouver quelle fonction et attributs déterminent un module
+import math
+dir(math)
+
+
+```
+
+## Prêt à aller plus loin?
+
+### En ligne gratuitement
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+
+### Format papier
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/hu-hu/python-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown
index 01f1c414..b5922766 100644
--- a/hu-hu/python-hu.html.markdown
+++ b/hu-hu/pythonlegacy-hu.html.markdown
@@ -1,5 +1,5 @@
---
-language: python
+language: Python 2 (legacy)
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "https://aminb.org"]
@@ -9,7 +9,7 @@ contributors:
- ["habi", "http://github.com/habi"]
translators:
- ["Tamás Diószegi", "https://github.com/ditam"]
-filename: learnpython-hu.py
+filename: learnpythonlegacy-hu.py
lang: hu-hu
---
@@ -23,7 +23,7 @@ vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen.
Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve
általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz
támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az
-ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/)
+ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python/)
ajánlott.
Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x
diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown
index 794e7a70..de7bb0ed 100644
--- a/it-it/python-it.html.markdown
+++ b/it-it/python-it.html.markdown
@@ -1,98 +1,89 @@
---
-language: python
+language: Python
filename: learnpython-it.py
contributors:
- - ["Louie Dinh", "http://ldinh.ca"]
- - ["Amin Bandali", "http://aminbandali.com"]
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
- ["evuez", "http://github.com/evuez"]
+ - ["Rommel Martinez", "https://ebzzry.io"]
translators:
+ - ["Draio", "http://github.com/Draio/"]
- ["Ale46", "http://github.com/Ale46/"]
- ["Tommaso Pifferi", "http://github.com/neslinesli93/"]
-lang: it-it
+lang: it-it
---
-Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari
-linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente
-pseudocodice eseguibile.
-Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service]
+Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente pseudocodice eseguibile.
-Nota: questo articolo è riferito a Python 2.7 in modo specifico, ma dovrebbe andar
-bene anche per Python 2.x. Python 2.7 sta raggiungendo il "fine vita", ovvero non sarà
-più supportato nel 2020. Quindi è consigliato imparare Python utilizzando Python 3.
-Per maggiori informazioni su Python 3.x, dai un'occhiata al [tutorial di Python 3](http://learnxinyminutes.com/docs/python3/).
+Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service]
-E' possibile anche scrivere codice compatibile sia con Python 2.7 che con Python 3.x,
-utilizzando [il modulo `__future__`](https://docs.python.org/2/library/__future__.html) di Python.
-Il modulo `__future__` permette di scrivere codice in Python 3, che può essere eseguito
-utilizzando Python 2: cosa aspetti a vedere il tutorial di Python 3?
+Nota: Questo articolo è riferito a Python 3 in modo specifico. Se volete avete la necessità di utilizzare Python 2.7 potete consultarla [qui](https://learnxinyminutes.com/docs/it-it/python-it/)
```python
# I commenti su una sola linea iniziano con un cancelletto
+
""" Più stringhe possono essere scritte
usando tre ", e sono spesso usate
- come commenti
+ come documentazione
"""
####################################################
## 1. Tipi di dati primitivi ed Operatori
####################################################
-# Hai i numeri
+# Ci sono i numeri
3 # => 3
# La matematica è quello che vi aspettereste
-1 + 1 # => 2
-8 - 1 # => 7
+1 + 1 # => 2
+8 - 1 # => 7
10 * 2 # => 20
-35 / 5 # => 7
-
-# La divisione è un po' complicata. E' una divisione fra interi in cui viene
-# restituito in automatico il risultato intero.
-5 / 2 # => 2
-
-# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats.
-2.0 # Questo è un float
-11.0 / 4.0 # => 2.75 ahhh...molto meglio
+35 / 5 # => 7.0
-# Il risultato di una divisione fra interi troncati positivi e negativi
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # funziona anche per i floats
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
+# Risultato della divisione intera troncata sia in positivo che in negativo
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
-# E' possibile importare il modulo "division" (vedi la sezione 6 di questa guida, Moduli)
-# per effettuare la divisione normale usando solo '/'.
-from __future__ import division
-11/4 # => 2.75 ...divisione normale
-11//4 # => 2 ...divisione troncata
+# Il risultato di una divisione è sempre un numero decimale (float)
+10.0 / 3 # => 3.3333333333333335
# Operazione Modulo
-7 % 3 # => 1
+7 % 3 # => 1
# Elevamento a potenza (x alla y-esima potenza)
-2**4 # => 16
+2**3 # => 8
# Forzare le precedenze con le parentesi
(1 + 3) * 2 # => 8
+# I valori booleani sono primitive del linguaggio (nota la maiuscola)
+True
+False
+
+# nega con not
+not True # => False
+not False # => True
+
# Operatori Booleani
# Nota "and" e "or" sono case-sensitive
-True and False #=> False
-False or True #=> True
+True and False # => False
+False or True # => True
# Note sull'uso di operatori Bool con interi
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
-
-# nega con not
-not True # => False
-not False # => True
+# False è 0 e True è 1
+# Non confonderti tra bool(ints) e le operazioni bitwise and/or (&,|)
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
+-5 != False != True #=> True
# Uguaglianza è ==
1 == 1 # => True
@@ -112,37 +103,46 @@ not False # => True
1 < 2 < 3 # => True
2 < 3 < 2 # => False
+# ('is' vs. '==')
+# 'is' controlla se due variabili si riferiscono allo stesso oggetto
+# '==' controlla se gli oggetti puntati hanno lo stesso valore.
+a = [1, 2, 3, 4] # a punta ad una nuova lista [1, 2, 3, 4]
+b = a # b punta a ciò a cui punta a
+b is a # => True, a e b puntano allo stesso oggeto
+b == a # => True, gli oggetti di a e b sono uguali
+b = [1, 2, 3, 4] # b punta ad una nuova lista [1, 2, 3, 4]
+b is a # => False, a e b non puntano allo stesso oggetto
+b == a # => True, gli oggetti di a e b sono uguali
+
# Le stringhe sono create con " o '
"Questa è una stringa."
'Anche questa è una stringa.'
-# Anche le stringhe possono essere sommate!
-"Ciao " + "mondo!" # => Ciao mondo!"
-# Le stringhe possono essere sommate anche senza '+'
-"Ciao " "mondo!" # => Ciao mondo!"
-
-# ... oppure moltiplicate
-"Hello" * 3 # => "HelloHelloHello"
+# Anche le stringhe possono essere sommate! Ma cerca di non farlo.
+"Hello " + "world!" # => "Hello world!"
+# Le stringhe (ma non le variabili contenenti stringhe) possono essere
+# sommate anche senza '+'
+"Hello " "world!" # => "Hello world!"
# Una stringa può essere considerata come una lista di caratteri
"Questa è una stringa"[0] # => 'Q'
-# Per sapere la lunghezza di una stringa
+# Puoi conoscere la lunghezza di una stringa
len("Questa è una stringa") # => 20
-# Formattazione delle stringhe con %
-# Anche se l'operatore % per le stringe sarà deprecato con Python 3.1, e verrà rimosso
-# successivamente, può comunque essere utile sapere come funziona
-x = 'mela'
-y = 'limone'
-z = "La cesta contiene una %s e un %s" % (x,y)
+# .format può essere usato per formattare le stringhe, in questo modo:
+"{} possono essere {}".format("Le stringhe", "interpolate") # => "Le stringhe possono essere interpolate"
+
+# Puoi ripetere gli argomenti di formattazione per risparmiare un po' di codice
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
-# Un nuovo modo per fomattare le stringhe è il metodo format.
-# Questo metodo è quello consigliato
-"{} è un {}".format("Questo", "test")
-"{0} possono essere {1}".format("le stringhe", "formattate")
-# Puoi usare delle parole chiave se non vuoi contare
-"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna")
+# Puoi usare dei nomi se non vuoi contare gli argomenti
+"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="le lasagne") # => "Bob vuole mangiare le lasagne"
+
+# Se il tuo codice Python 3 necessita di eseguire codice Python 2.x puoi ancora
+# utilizzare il vecchio stile di formattazione:
+"%s possono essere %s nel %s modo" % ("Le stringhe", "interpolate", "vecchio") # => "Le stringhe possono essere interpolate nel vecchio modo"
# None è un oggetto
None # => None
@@ -150,57 +150,54 @@ None # => None
# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None
# Usa "is" invece
"etc" is None # => False
-None is None # => True
-
-# L'operatore 'is' testa l'identità di un oggetto. Questo non è
-# molto utile quando non hai a che fare con valori primitivi, ma lo è
-# quando hai a che fare con oggetti.
-
-# Qualunque oggetto può essere usato nei test booleani
-# I seguenti valori sono considerati falsi:
-# - None
-# - Lo zero, come qualunque tipo numerico (quindi 0, 0L, 0.0, 0.j)
-# - Sequenze vuote (come '', (), [])
-# - Contenitori vuoti (tipo {}, set())
-# - Istanze di classi definite dall'utente, che soddisfano certi criteri
-# vedi: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
-#
-# Tutti gli altri valori sono considerati veri: la funzione bool() usata su di loro, ritorna True.
-bool(0) # => False
-bool("") # => False
+None is None # => True
+# None, 0, e stringhe/liste/dizionari/tuple vuoti vengono considerati
+# falsi (False). Tutti gli altri valori sono considerati veri (True).
+bool(0) # => False
+bool("") # => False
+bool([]) # => False
+bool({}) # => False
+bool(()) # => False
####################################################
## 2. Variabili e Collections
####################################################
-# Python ha una funzione di stampa
-print "Sono Python. Piacere di conoscerti!" # => Sono Python. Piacere di conoscerti!
+# Python ha una funzione per scrivere (sul tuo schermo)
+print("Sono Python. Piacere di conoscerti!") # => Sono Python. Piacere di conoscerti!
+
+# Di default la funzione print() scrive e va a capo aggiungendo un carattere
+# newline alla fine della stringa. È possibile utilizzare l'argomento opzionale
+# end per cambiare quest'ultimo carattere aggiunto.
+print("Hello, World", end="!") # => Hello, World!
# Un modo semplice per ricevere dati in input dalla riga di comando
-variabile_stringa_input = raw_input("Inserisci del testo: ") # Ritorna i dati letti come stringa
-variabile_input = input("Inserisci del testo: ") # Interpreta i dati letti come codice python
-# Attenzione: bisogna stare attenti quando si usa input()
-# Nota: In python 3, input() è deprecato, e raw_input() si chiama input()
+variabile_stringa_input = input("Inserisci del testo: ") # Restituisce i dati letti come stringa
+# Nota: Nelle precedenti vesioni di Python, il metodo input()
+# era chiamato raw_input()
# Non c'è bisogno di dichiarare una variabile per assegnarle un valore
-una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores
-una_variabile # => 5
+# Come convenzione, per i nomi delle variabili, si utilizzano i caratteri
+# minuscoli separati, se necessario, da underscore
+some_var = 5
+some_var # => 5
# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione.
-# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni.
-un_altra_variabile # Genera un errore di nome
+# Dai un'occhiata al Control Flow per imparare di più su come gestire
+# le eccezioni.
+some_unknown_var # Genera un errore di nome
# if può essere usato come un'espressione
-# E' l'equivalente dell'operatore ternario in C
+# È l'equivalente dell'operatore ternario in C
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
-# Liste immagazzinano sequenze
+# Le liste immagazzinano sequenze
li = []
# Puoi partire con una lista pre-riempita
-altra_li = [4, 5, 6]
+other_li = [4, 5, 6]
-# Aggiungi cose alla fine di una lista con append
+# Aggiungere alla fine di una lista con append
li.append(1) # li ora è [1]
li.append(2) # li ora è [1, 2]
li.append(4) # li ora è [1, 2, 4]
@@ -212,14 +209,10 @@ li.append(3) # li ora è [1, 2, 4, 3] di nuovo.
# Accedi ad una lista come faresti con un array
li[0] # => 1
-# Assegna nuovo valore agli indici che sono già stati inizializzati con =
-li[0] = 42
-li[0] # => 42
-li[0] = 1 # Nota: è resettato al valore iniziale
# Guarda l'ultimo elemento
li[-1] # => 3
-# Guardare al di fuori dei limiti è un IndexError
+# Guardare al di fuori dei limiti genera un IndexError
li[4] # Genera IndexError
# Puoi guardare gli intervalli con la sintassi slice (a fetta).
@@ -236,14 +229,11 @@ li[::-1] # => [3, 4, 2, 1]
# Usa combinazioni per fare slices avanzate
# li[inizio:fine:passo]
+# Crea una copia (one layer deep copy) usando la sintassi slices
+li2 = li[:] # => li2 = [1, 2, 4, 3] ma (li2 is li) risulterà falso.
+
# Rimuovi arbitrariamente elementi da una lista con "del"
del li[2] # li è ora [1, 2, 3]
-# Puoi sommare le liste
-li + altra_li # => [1, 2, 3, 4, 5, 6]
-# Nota: i valori per li ed altra_li non sono modificati.
-
-# Concatena liste con "extend()"
-li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6]
# Rimuove la prima occorrenza di un elemento
li.remove(2) # Ora li è [1, 3, 4, 5, 6]
@@ -252,10 +242,17 @@ li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista
# Inserisce un elemento all'indice specificato
li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6]
-# Ritorna l'indice della prima occorrenza dell'elemento fornito
+ Ritorna l'indice della prima occorrenza dell'elemento fornito
li.index(2) # => 1
li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista
+# Puoi sommare le liste
+# Nota: i valori per li e per other_li non vengono modificati.
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# Concatena le liste con "extend()"
+li.extend(other_li) # Adesso li è [1, 2, 3, 4, 5, 6]
+
# Controlla l'esistenza di un valore in una lista con "in"
1 in li # => True
@@ -263,93 +260,112 @@ li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista
len(li) # => 6
-# Tuple sono come le liste ma immutabili.
+# Le tuple sono come le liste ma immutabili.
tup = (1, 2, 3)
-tup[0] # => 1
+tup[0] # => 1
tup[0] = 3 # Genera un TypeError
+# Note that a tuple of length one has to have a comma after the last element but
+# tuples of other lengths, even zero, do not.
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
+
# Puoi fare tutte queste cose da lista anche sulle tuple
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
# Puoi scompattare le tuple (o liste) in variabili
-a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3
+a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 e c è ora 3
d, e, f = 4, 5, 6 # puoi anche omettere le parentesi
# Le tuple sono create di default se non usi le parentesi
g = 4, 5, 6 # => (4, 5, 6)
# Guarda come è facile scambiare due valori
-e, d = d, e # d è ora 5 ed e è ora 4
-
+e, d = d, e # d è ora 5 ed e è ora 4
-# Dizionari immagazzinano mappature
-empty_dict = {}
-# Questo è un dizionario pre-riempito
+# I dizionari memorizzano insiemi di dati indicizzati da nomi arbitrari (chiavi)
+empty_dict= {}
+# Questo è un dizionario pre-caricato
filled_dict = {"uno": 1, "due": 2, "tre": 3}
-# Accedi ai valori con []
+# Nota: le chiavi dei dizionari devono essere di tipo immutabile. Questo per
+# assicurare che le chiavi possano essere convertite in calori hash costanti
+# per un risposta più veloce.
+invalid_dict = {[1,2,3]: "123"} # => Emette un TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # I valori, invece, possono essere di qualunque tipo
+
+# Accedi ai valori indicando la chiave tra []
filled_dict["uno"] # => 1
-# Ottieni tutte le chiavi come una lista con "keys()"
-filled_dict.keys() # => ["tre", "due", "uno"]
+# Puoi ottenere tutte le chiavi di un dizionario con "keys()"
+# (come oggetto iterabile). Per averle in formato lista è necessario
+# utilizzare list().
# Nota - Nei dizionari l'ordine delle chiavi non è garantito.
# Il tuo risultato potrebbe non essere uguale a questo.
+list(filled_dict.keys()) # => ["tre", "due", "uno"]
-# Ottieni tutt i valori come una lista con "values()"
-filled_dict.values() # => [3, 2, 1]
-# Nota - Come sopra riguardo l'ordinamento delle chiavi.
-# Ottieni tutte le coppie chiave-valore, sotto forma di lista di tuple, utilizzando "items()"
-filled_dicts.items() # => [("uno", 1), ("due", 2), ("tre", 3)]
+# Puoi ottenere tutti i valori di un dizionario con "values()"
+# (come oggetto iterabile).
+# Anche in questo caso, er averle in formato lista, è necessario utilizzare list()
+# Anche in questo caso, come per le chiavi, l'ordine non è garantito
+list(filled_dict.values()) # => [3, 2, 1]
# Controlla l'esistenza delle chiavi in un dizionario con "in"
"uno" in filled_dict # => True
-1 in filled_dict # => False
+1 in filled_dict # => False
-# Cercando una chiave non esistente è un KeyError
+# Cercando una chiave non esistente genera un KeyError
filled_dict["quattro"] # KeyError
# Usa il metodo "get()" per evitare KeyError
-filled_dict.get("uno") # => 1
-filled_dict.get("quattro") # => None
+filled_dict.get("uno") # => 1
+filled_dict.get("quattro") # => None
# Il metodo get supporta un argomento di default quando il valore è mancante
filled_dict.get("uno", 4) # => 1
filled_dict.get("quattro", 4) # => 4
-# nota che filled_dict.get("quattro") è ancora => None
-# (get non imposta il valore nel dizionario)
-# imposta il valore di una chiave con una sintassi simile alle liste
-filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4
-# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente
-filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5
-filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5
+# "setdefault()" inserisce un valore per una chiave in un dizionario
+# solo se la chiave data non è già presente
+filled_dict.setdefault("cinque", 5) # filled_dict["cinque"] viene impostato a 5
+filled_dict.setdefault("cinque", 6) # filled_dict["cinque"] rimane 5
+# Aggiungere una coppia chiave->valore a un dizionario
+filled_dict.update({"quattro":4}) # => {"uno": 1, "due": 2, "tre": 3, "quattro": 4}
+filled_dict["quattro"] = 4 # un altro modo pe aggiungere a un dizionario
-# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni)
-empty_set = set()
-# Inizializza un "set()" con un po' di valori
-some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4])
+# Rimuovi una chiave da un dizionario con del
+del filled_dict["uno"] # Rimuove la chiave "uno" dal dizionario
-# l'ordine non è garantito, anche se a volta può sembrare ordinato
-another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4])
+# Da Python 3.5 puoi anche usare ulteriori opzioni di spacchettamento
+{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
+{'a': 1, **{'a': 2}} # => {'a': 2}
-# Da Python 2.7, {} può essere usato per dichiarare un set
-filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+# I set sono come le liste ma non possono contenere doppioni
+empty_set = set()
+# Inizializza un "set()" con un dei valori. Sì, sembra un dizionario.
+some_set = {1, 1, 2, 2, 3, 4} # set_nuovo è {1, 2, 3, 4}
+
+# Come le chiavi di un dizionario, gli elementi di un set devono essere
+# di tipo immutabile
+invalid_set = {[1], 1} # => Genera un "TypeError: unhashable type: 'list'""
+valid_set = {(1,), 1}
-# Aggiungere elementi ad un set
-filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5}
+# Aggiungere uno o più elementi ad un set
+some_set.add(5) # some_set ora è {1, 2, 3, 4, 5}
# Fai intersezioni su un set con &
other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
+some_set & other_set # => {3, 4, 5}
# Fai unioni su set con |
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+some_set | other_set # => {1, 2, 3, 4, 5, 6}
# Fai differenze su set con -
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# Effettua la differenza simmetrica con ^
{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
@@ -361,65 +377,77 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
{1, 2} <= {1, 2, 3} # => True
# Controlla l'esistenza in un set con in
-2 in filled_set # => True
-10 in filled_set # => False
+2 in some_set # => True
+10 in some_set # => False
+
####################################################
-## 3. Control Flow
+## 3. Control Flow e oggetti Iterabili
####################################################
-# Dichiariamo una variabile
+# Dichiariamo una variabile
some_var = 5
# Questo è un controllo if. L'indentazione è molto importante in python!
-# stampa "some_var è più piccola di 10"
+# Come convenzione si utilizzano quattro spazi, non la tabulazione.
+# Il seguente codice stampa "some_var è minore di 10"
if some_var > 10:
- print "some_var è decisamente più grande di 10."
-elif some_var < 10: # Questa clausola elif è opzionale.
- print "some_var è più piccola di 10."
-else: # Anche questo è opzionale.
- print "some_var è precisamente 10."
-
+ print("some_var è maggiore di 10")
+elif some_var < 10: # La clausolo elif è opzionale
+ print("some_var è minore di 10")
+else: # Anche else è opzionale
+ print("some_var è 10.")
"""
-I cicli for iterano sulle liste
-stampa:
+I cicli for iterano sulle liste, cioè ripetono un codice per ogni elemento
+di una lista.
+Il seguente codice scriverà:
cane è un mammifero
gatto è un mammifero
topo è un mammifero
"""
for animale in ["cane", "gatto", "topo"]:
- # Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.)
- print "{0} è un mammifero".format(animale)
+ # Puoi usare format() per interpolare le stringhe formattate.
+ print("{} è un mammifero".format(animale))
"""
-"range(numero)" restituisce una lista di numeri
-da zero al numero dato
-stampa:
+"range(numero)" restituisce una lista di numeri da zero al numero dato
+Il seguente codice scriverà:
0
1
2
3
"""
for i in range(4):
- print i
+ print(i)
"""
-"range(lower, upper)" restituisce una lista di numeri
-dal più piccolo (lower) al più grande (upper)
-stampa:
+"range(lower, upper)" restituisce una lista di numeri dal più piccolo (lower)
+al più grande (upper).
+Il seguente codice scriverà:
4
5
6
7
"""
for i in range(4, 8):
- print i
+ print(i)
"""
+"range(lower, upper, step)" rrestituisce una lista di numeri dal più piccolo
+(lower) al più grande (upper), incrementando del valore step.
+Se step non è indicato, avrà come valore di default 1.
+Il seguente codice scriverà:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+"""
+
I cicli while vengono eseguiti finchè una condizione viene a mancare
-stampa:
+Il seguente codice scriverà:
0
1
2
@@ -427,28 +455,62 @@ stampa:
"""
x = 0
while x < 4:
- print x
+ print(x)
x += 1 # Forma compatta per x = x + 1
-# Gestisci le eccezioni con un blocco try/except
-
-# Funziona da Python 2.6 in su:
+# Gestione delle eccezioni con un blocco try/except
try:
# Usa "raise" per generare un errore
- raise IndexError("Questo è un errore di indice")
+ raise IndexError("Questo è un IndexError")
except IndexError as e:
- pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero.
+ pass # Pass è solo una non-operazione. Solitamente vorrai rimediare all'errore.
except (TypeError, NameError):
pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario.
-else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except
- print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni
+else: # Clausola opzionale al blocco try/except. Deve essere dopo tutti i blocchi except
+ print("Tutto ok!") # Viene eseguita solo se il codice dentro try non genera eccezioni
finally: # Eseguito sempre
- print "Possiamo liberare risorse qui"
+ print("Possiamo liberare risorse qui")
-# Invece di try/finally per liberare risorse puoi usare il metodo with
+# Se ti serve solo un try/finally, per liberare risorse, puoi usare il metodo with
with open("myfile.txt") as f:
for line in f:
- print line
+ print(line)
+
+# In Python qualunque oggetto in grado di essere trattato come una
+# sequenza è definito un oggetto Iterable (itarabile).
+# L'oggetto restituito da una funzione range è un iterabile.
+
+filled_dict = {"uno": 1, "due": 2, "tre": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) # => dict_keys(['uno', 'due', 'tre']).
+# Questo è un oggetto che implementa la nostra interfaccia Iterable.
+
+# È possibile utilizzarlo con i loop:
+for i in our_iterable:
+ print(i) # Scrive uno, due, tre
+
+# Tuttavia non possiamo recuperarne i valori tramite indice.
+our_iterable[1] # Genera un TypeError
+
+# Un oggetto iterabile è in grado di generare un iteratore
+our_iterator = iter(our_iterable)
+
+# L'iteratore è un oggetto che ricorda il suo stato mentro lo si "attraversa"
+# Possiamo accedere al successivo elemento con "next()".
+next(our_iterator) # => "uno"
+
+# Mantiene il suo stato mentro eseguiamo l'iterazione
+next(our_iterator) # => "due"
+next(our_iterator) # => "tre"
+
+# Dopo che un iteratore ha restituito tutti i suoi dati, genera
+# un'eccezione StopIteration
+next(our_iterator) # Raises StopIteration
+
+# Puoi prendere tutti gli elementi di un iteratore utilizzando list().
+list(filled_dict.keys()) # => Returns ["one", "two", "three"]
+
+
####################################################
## 4. Funzioni
@@ -456,23 +518,20 @@ with open("myfile.txt") as f:
# Usa "def" per creare nuove funzioni
def aggiungi(x, y):
- print "x è {0} e y è {1}".format(x, y)
- return x + y # Restituisce valori con il metodo return
+ print("x è {} e y è {}".format(x, y)) // Scrive i valori formattati in una stringa
+ return x + y # Restituisce la somma dei valori con il metodo return
# Chiamare funzioni con parametri
-aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11
+aggiungi(5, 6) # => scrive "x è 5 e y è 6" e restituisce 11
# Un altro modo per chiamare funzioni è con parole chiave come argomenti
-aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine.
+aggiungi(y=6, x=5) # In questo modo non è necessario rispettare l'ordine degli argomenti
-
-# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali
-# che verranno interpretati come tuple usando il *
+# Puoi definire funzioni che accettano un numero non definito di argomenti
def varargs(*args):
return args
-varargs(1, 2, 3) # => (1, 2, 3)
-
+varargs(1, 2, 3) # => (1, 2, 3)
# Puoi definire funzioni che accettano un numero variabile di parole chiave
# come argomento, che saranno interpretati come un dizionario usando **
@@ -485,8 +544,8 @@ keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# Puoi farle entrambi in una volta, se ti va
def all_the_args(*args, **kwargs):
- print args
- print kwargs
+ print(args)
+ print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) stampa:
(1, 2)
@@ -494,38 +553,44 @@ all_the_args(1, 2, a=3, b=4) stampa:
"""
# Quando chiami funzioni, puoi fare l'opposto di args/kwargs!
-# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave
+# Usa * per sviluppare gli argomenti posizionale ed usa ** per
+# espandere gli argomenti parola chiave
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
-all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
-
-# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs
-# sviluppandoli, rispettivamente, con * e **
-def pass_all_the_args(*args, **kwargs):
- all_the_args(*args, **kwargs)
- print varargs(*args)
- print keyword_args(**kwargs)
-
-# Funzioni Scope
+all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
+
+
+# Restituire valori multipli (with tuple assignments)
+def swap(x, y):
+ return y, x # Restituisce valori multipli come tupla senza parentesi
+ # (Nota: le parentesi sono state escluse ma possono essere messe)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Le parentesi sono state escluse ma possono essere incluse.
+
+# Funzioni - Visibilità delle variabili (variable scope)
x = 5
def set_x(num):
- # La variabile locale x non è uguale alla variabile globale x
- x = num # => 43
- print x # => 43
+ # La variabile locale x non è la variabile globale x
+ x = num # => 43
+ print(x) # => 43
def set_global_x(num):
global x
- print x # => 5
- x = num # la variabile globable x è ora 6
- print x # => 6
+ print(x) # => 5
+ x = num # la variabile globable x è ora 6
+ print(x) # => 6
set_x(43)
set_global_x(6)
-# Python ha funzioni di prima classe
+
+# Python ha "first class functions"
def create_adder(x):
def adder(y):
return x + y
@@ -535,204 +600,381 @@ add_10 = create_adder(10)
add_10(3) # => 13
# Ci sono anche funzioni anonime
-(lambda x: x > 2)(3) # => True
-(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
-# Esse sono incluse in funzioni di alto livello
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+# È possibile creare "mappe" e "filtri"
+list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
+list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
-# Possiamo usare la comprensione delle liste per mappe e filtri
-[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+# Possiamo usare le "list comprehensions" per mappe e filtri
+# Le "list comprehensions" memorizzano l'output come una lista che può essere
+# di per sé una lista annidata
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
# Puoi fare anche la comprensione di set e dizionari
-{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'}
+{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
####################################################
-## 5. Classi
+## 5. Modules
+####################################################
+
+# Puoi importare moduli
+import math
+print(math.sqrt(16)) # => 4.0
+
+# Puoi ottenere specifiche funzione da un modulo
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# Puoi importare tutte le funzioni da un modulo
+# Attenzione: questo non è raccomandato
+from math import *
+
+# Puoi abbreviare i nomi dei moduli
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+
+# I moduli di Python sono normali file python. Ne puoi
+# scrivere di tuoi ed importarli. Il nome del modulo
+# è lo stesso del nome del file.
+
+# Potete scoprire quali funzioni e attributi
+# sono definiti in un modulo
+import math
+dir(math)
+
+# Se nella cartella corrente hai uno script chiamato math.py,
+# Python caricherà quello invece del modulo math.
+# Questo succede perchè la cartella corrente ha priorità
+# sulle librerie standard di Python
+
+# Se hai uno script Python chiamato math.py nella stessa
+# cartella del tua script, Python caricherà quello al posto del
+# comune modulo math.
+# Questo accade perché la cartella locale ha la priorità
+# sulle librerie built-in di Python.
+
+
+####################################################
+## 6. Classes
####################################################
-# Usiamo una sottoclasse da un oggetto per avere una classe.
-class Human(object):
+# Usiamo l'istruzione "class" per creare una classe
+class Human:
- # Un attributo della classe. E' condiviso da tutte le istanze delle classe
+ # Un attributo della classe. E' condiviso tra tutte le istanze delle classe
species = "H. sapiens"
- # Costruttore base, richiamato quando la classe viene inizializzata.
- # Si noti che il doppio leading e gli underscore finali denotano oggetti
- # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato
- # dall'utente. Non dovresti usare nomi di questo genere.
+ # Si noti che i doppi underscore iniziali e finali denotano gli oggetti o
+ # attributi utilizzati da Python ma che vivono nel namespace controllato
+ # dall'utente
+ # Metodi, oggetti o attributi come: __init__, __str__, __repr__, etc. sono
+ # chiamati metodi speciali (o talvolta chiamati "dunder methods").
+ # Non dovresti inventare tali nomi da solo.
+
def __init__(self, name):
# Assegna l'argomento all'attributo name dell'istanza
self.name = name
# Inizializza una proprietà
- self.age = 0
+ self._age = 0
# Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento
def say(self, msg):
- return "{0}: {1}".format(self.name, msg)
+ print("{name}: {message}".format(name=self.name, message=msg))
+
+ # Un altro metodo dell'istanza
+ def sing(self):
+ return 'yo... yo... microphone check... one two... one two...'
# Un metodo della classe è condiviso fra tutte le istanze
- # Sono chiamate con la classe chiamante come primo argomento
+ # Sono chiamati con la classe chiamante come primo argomento
@classmethod
def get_species(cls):
return cls.species
- # Un metodo statico è chiamato senza una classe od una istanza di riferimento
+ # Un metodo statico è chiamato senza classe o istanza di riferimento
@staticmethod
def grunt():
return "*grunt*"
- # Una proprietà è come un metodo getter.
- # Trasforma il metodo age() in un attributo in sola lettura, che ha lo stesso nome
+ # Una property è come un metodo getter.
+ # Trasforma il metodo age() in un attributo in sola lettura, che ha
+ # lo stesso nome
+ # In Python non c'è bisogno di scrivere futili getter e setter.
@property
def age(self):
return self._age
- # Questo metodo permette di modificare la proprietà
+ # Questo metodo permette di modificare una property
@age.setter
def age(self, age):
self._age = age
- # Questo metodo permette di cancellare la proprietà
+ # Questo metodo permette di cancellare una property
@age.deleter
def age(self):
del self._age
-# Instanziare una classe
-i = Human(name="Ian")
-print i.say("hi") # stampa "Ian: hi"
+# Quando l'interprete Python legge un sorgente esegue tutto il suo codice.
+# Questo controllo su __name__ assicura che questo blocco di codice venga
+# eseguito solo quando questo modulo è il programma principale.
+
+if __name__ == '__main__':
+ # Crea un'istanza della classe
+ i = Human(name="Ian")
+ i.say("hi") # "Ian: hi"
+ j = Human("Joel")
+ j.say("hello") # "Joel: hello"
+ # i e j sono istanze del tipo Human, o in altre parole sono oggetti Human
+
+ # Chiama un metodo della classe
+ i.say(i.get_species()) # "Ian: H. sapiens"
+ # Cambia l'attributo condiviso
+ Human.species = "H. neanderthalensis"
+ i.say(i.get_species()) # => "Ian: H. neanderthalensis"
+ j.say(j.get_species()) # => "Joel: H. neanderthalensis"
+
+ # Chiama un metodo statico
+ print(Human.grunt()) # => "*grunt*"
+
+ # Non è possibile chiamare il metodo statico con l'istanza dell'oggetto
+ # poiché i.grunt() metterà automaticamente "self" (l'oggetto i)
+ # come argomento
+ print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
+
+ # Aggiorna la property (age) di questa istanza
+ i.age = 42
+ # Leggi la property
+ i.say(i.age) # => "Ian: 42"
+ j.say(j.age) # => "Joel: 0"
+ # Cancella la property
+ del i.age
+ i.age # => questo genererà un AttributeError
-j = Human("Joel")
-print j.say("hello") # stampa "Joel: hello"
-# Chiamare metodi della classe
-i.get_species() # => "H. sapiens"
+####################################################
+## 6.1 Ereditarietà (Inheritance)
+####################################################
-# Cambiare l'attributo condiviso
-Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
+# L'ereditarietà consente di definire nuove classi figlio che ereditano metodi e
+# variabili dalla loro classe genitore.
-# Chiamare il metodo condiviso
-Human.grunt() # => "*grunt*"
+# Usando la classe Human definita sopra come classe base o genitore, possiamo
+# definire una classe figlia, Superhero, che erediterà le variabili di classe
+# come "species", "name" e "age", così come i metodi, come "sing" e "grunt",
+# dalla classe Human, ma potrà anche avere le sue proprietà uniche.
-# Aggiorna la proprietà
-i.age = 42
+# Per importare le funzioni da altri file usa il seguente formato
+# from "nomefile-senza-estensione" import "funzione-o-classe"
-# Ritorna il valore della proprietà
-i.age # => 42
+from human import Human
-# Cancella la proprietà
-del i.age
-i.age # => Emette un AttributeError
+# Specificare le classi genitore come parametri della definizione della classe
+class Superhero(Human):
+ # Se la classe figlio deve ereditare tutte le definizioni del genitore
+ # senza alcuna modifica, puoi semplicemente usare la parola chiave "pass"
+ # (e nient'altro)
-####################################################
-## 6. Moduli
-####################################################
+ #Le classi figlio possono sovrascrivere gli attributi dei loro genitori
+ species = 'Superhuman'
-# Puoi importare moduli
-import math
-print math.sqrt(16) # => 4.0
+ # Le classi figlie ereditano automaticamente il costruttore della classe
+ # genitore, inclusi i suoi argomenti, ma possono anche definire ulteriori
+ # argomenti o definizioni e sovrascrivere i suoi metodi (compreso il
+ # costruttore della classe).
+ # Questo costruttore eredita l'argomento "nome" dalla classe "Human" e
+ # aggiunge gli argomenti "superpowers" e "movie":
-# Puoi ottenere specifiche funzione da un modulo
-from math import ceil, floor
-print ceil(3.7) # => 4.0
-print floor(3.7) # => 3.0
+ def __init__(self, name, movie=False,
+ superpowers=["super strength", "bulletproofing"]):
-# Puoi importare tutte le funzioni da un modulo
-# Attenzione: questo non è raccomandato
-from math import *
+ # aggiungi ulteriori attributi della classe
+ self.fictional = True
+ self.movie = movie
+ self.superpowers = superpowers
-# Puoi abbreviare i nomi dei moduli
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
-# puoi anche verificare che le funzioni sono equivalenti
-from math import sqrt
-math.sqrt == m.sqrt == sqrt # => True
+ # La funzione "super" ti consente di accedere ai metodi della classe
+ # genitore che sono stati sovrascritti dalla classe figlia,
+ # in questo caso il metodo __init__.
+ # Il seguente codice esegue il costruttore della classe genitore:
+ super().__init__(name)
-# I moduli di Python sono normali file python. Ne puoi
-# scrivere di tuoi ed importarli. Il nome del modulo
-# è lo stesso del nome del file.
+ # Sovrascrivere il metodo "sing"
+ def sing(self):
+ return 'Dun, dun, DUN!'
-# Potete scoprire quali funzioni e attributi
-# definiscono un modulo
-import math
-dir(math)
+ # Aggiungi un ulteriore metodo dell'istanza
+ def boast(self):
+ for power in self.superpowers:
+ print("I wield the power of {pow}!".format(pow=power))
-# Se nella cartella corrente hai uno script chiamato math.py,
-# Python caricherà quello invece del modulo math.
-# Questo succede perchè la cartella corrente ha priorità
-# sulle librerie standard di Python
+if __name__ == '__main__':
+ sup = Superhero(name="Tick")
+
+ # Controllo del tipo di istanza
+ if isinstance(sup, Human):
+ print('I am human')
+ if type(sup) is Superhero:
+ print('I am a superhero')
+
+ # Ottieni il "Method Resolution search Order" usato sia da getattr ()
+ # che da super (). Questo attributo è dinamico e può essere aggiornato
+ print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
+ # => <class 'human.Human'>, <class 'object'>)
+
+ # Esegui il metodo principale ma utilizza il proprio attributo di classe
+ print(sup.get_species()) # => Superhuman
+
+ # Esegui un metodo che è stato sovrascritto
+ print(sup.sing()) # => Dun, dun, DUN!
+
+ # Esegui un metodo di Human
+ sup.say('Spoon') # => Tick: Spoon
+
+ # Esegui un metodo che esiste solo in Superhero
+ sup.boast() # => I wield the power of super strength!
+ # => I wield the power of bulletproofing!
+
+ # Attributo di classe ereditato
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Attributo che esiste solo in Superhero
+ print('Am I Oscar eligible? ' + str(sup.movie))
####################################################
-## 7. Avanzate
+## 6.2 Ereditarietà multipla
####################################################
-# Generatori
-# Un generatore appunto "genera" valori solo quando vengono richiesti,
-# invece di memorizzarli tutti subito fin dall'inizio
+# Un'altra definizione di classe
+# bat.py
+class Bat:
-# Il metodo seguente (che NON è un generatore) raddoppia tutti i valori e li memorizza
-# dentro `double_arr`. Se gli oggetti iterabili sono grandi, il vettore risultato
-# potrebbe diventare enorme!
-def double_numbers(iterable):
- double_arr = []
- for i in iterable:
- double_arr.append(i + i)
+ species = 'Baty'
-# Eseguendo il seguente codice, noi andiamo a raddoppiare prima tutti i valori, e poi
-# li ritorniamo tutti e andiamo a controllare la condizione
-for value in double_numbers(range(1000000)): # `test_senza_generatore`
- print value
- if value > 5:
- break
+ def __init__(self, can_fly=True):
+ self.fly = can_fly
+
+ # Questa classe ha anche un metodo "say"
+ def say(self, msg):
+ msg = '... ... ...'
+ return msg
+
+ # E anche un suo metodo personale
+ def sonar(self):
+ return '))) ... ((('
+
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('hello'))
+ print(b.fly)
+
+# Definizione di classe che eredita da Superhero e Bat
+# superhero.py
+from superhero import Superhero
+from bat import Bat
+
+# Definisci Batman come classe figlia che eredita sia da Superhero che da Bat
+class Batman(Superhero, Bat):
+
+ def __init__(self, *args, **kwargs):
+ # In genere per ereditare gli attributi devi chiamare super:
+ # super(Batman, self).__init__(*args, **kwargs)
+ # Ma qui abbiamo a che fare con l'ereditarietà multipla, e super()
+ # funziona solo con la successiva classe nell'elenco MRO.
+ # Quindi, invece, chiamiamo esplicitamente __init__ per tutti gli
+ # antenati. L'uso di *args e **kwargs consente di passare in modo
+ # pulito gli argomenti, con ciascun genitore che "sbuccia un
+ # livello della cipolla".
+ Superhero.__init__(self, 'anonymous', movie=True,
+ superpowers=['Wealthy'], *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # sovrascrivere il valore per l'attributo name
+ self.name = 'Sad Affleck'
-# Invece, potremmo usare un generatore per "generare" il valore raddoppiato non
-# appena viene richiesto
-def double_numbers_generator(iterable):
+ def sing(self):
+ return 'nan nan nan nan nan batman!'
+
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # Ottieni il "Method Resolution search Order" utilizzato da getattr() e super().
+ # Questo attributo è dinamico e può essere aggiornato
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
+ # => <class 'bat.Bat'>, <class 'object'>)
+
+ # Esegui il metodo del genitore ma utilizza il proprio attributo di classe
+ print(sup.get_species()) # => Superhuman
+
+ # Esegui un metodo che è stato sovrascritto
+ print(sup.sing()) # => nan nan nan nan nan batman!
+
+ # Esegui un metodo da Human, perché l'ordine di ereditarietà è importante
+ sup.say('I agree') # => Sad Affleck: I agree
+
+ # Esegui un metodo che esiste solo nel 2o antenato
+ print(sup.sonar()) # => ))) ... (((
+
+ # Attributo di classe ereditato
+ sup.age = 100
+ print(sup.age) # => 100
+
+ # Attributo ereditato dal secondo antenato il cui valore predefinito
+ # è stato ignorato.
+ print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
+
+
+
+####################################################
+## 7. Advanced
+####################################################
+
+# I generatori ti aiutano a creare codice pigro (lazy code).
+# Codice che darà un risultato solo quando sarà "valutato"
+def double_numbers(iterable):
for i in iterable:
yield i + i
-# Utilizzando lo stesso test di prima, stavolta però con un generatore, ci permette
-# di iterare sui valori e raddoppiarli uno alla volta, non appena vengono richiesti dalla
-# logica del programma. Per questo, non appena troviamo un valore > 5, usciamo dal ciclo senza
-# bisogno di raddoppiare la maggior parte dei valori del range (MOLTO PIU VELOCE!)
-for value in double_numbers_generator(xrange(1000000)): # `test_generatore`
- print value
- if value > 5:
+# I generatori sono efficienti in termini di memoria perché caricano
+# solo i dati necessari per elaborare il valore successivo nell'iterabile.
+# Ciò consente loro di eseguire operazioni su intervalli di valori
+# altrimenti proibitivi.
+# NOTA: `range` sostituisce` xrange` in Python 3.
+for i in double_numbers(range(1, 900000000)): # `range` is a generator.
+ print(i)
+ if i >= 30:
break
-# Nota: hai notato l'uso di `range` in `test_senza_generatore` e `xrange` in `test_generatore`?
-# Proprio come `double_numbers_generator` è la versione col generatore di `double_numbers`
-# Abbiamo `xrange` come versione col generatore di `range`
-# `range` ritorna un array di 1000000 elementi
-# `xrange` invece genera 1000000 valori quando lo richiediamo/iteriamo su di essi
-
-# Allo stesso modo della comprensione delle liste, puoi creare la comprensione
-# dei generatori.
+# Proprio come è possibile creare una "list comprehension", è possibile
+# creare anche delle "generator comprehensions".
values = (-x for x in [1,2,3,4,5])
for x in values:
- print(x) # stampa -1 -2 -3 -4 -5
+ print(x) # prints -1 -2 -3 -4 -5 to console/terminal
-# Puoi anche fare il cast diretto di una comprensione di generatori ad una lista.
+# Puoi anche trasmettere una "generator comprehensions" direttamente
+# ad un elenco.
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
print(gen_to_list) # => [-1, -2, -3, -4, -5]
# Decoratori
-# in questo esempio beg include say
-# Beg chiamerà say. Se say_please è True allora cambierà il messaggio
-# ritornato
+# In questo esempio "beg" avvolge/wrappa "say".
+# Se say_please è True, cambierà il messaggio restituito.
from functools import wraps
def beg(target_function):
@@ -752,8 +994,8 @@ def say(say_please=False):
return msg, say_please
-print say() # Puoi comprarmi una birra?
-print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :(
+print(say()) # Puoi comprarmi una birra?
+print(say(say_please=True)) # Puoi comprarmi una birra? Per favore! Sono povero :(
```
## Pronto per qualcosa di più?
@@ -761,18 +1003,14 @@ print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero
### Gratis Online
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [Python Course](http://www.python-course.eu/index.php)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
-* [LearnPython](http://www.learnpython.org/)
-* [Fullstack Python](https://www.fullstackpython.com/)
-
-### Libri cartacei
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
+* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
+* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
+* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
diff --git a/it-it/python3-it.html.markdown b/it-it/python3-it.html.markdown
deleted file mode 100644
index 04f78cff..00000000
--- a/it-it/python3-it.html.markdown
+++ /dev/null
@@ -1,1016 +0,0 @@
----
-language: python3
-filename: learnpython3-it.py
-contributors:
- - ["Louie Dinh", "http://pythonpracticeprojects.com"]
- - ["Steven Basart", "http://github.com/xksteven"]
- - ["Andre Polykanine", "https://github.com/Oire"]
- - ["Zachary Ferguson", "http://github.com/zfergus2"]
- - ["evuez", "http://github.com/evuez"]
- - ["Rommel Martinez", "https://ebzzry.io"]
-translators:
- - ["Draio", "http://github.com/Draio/"]
- - ["Ale46", "http://github.com/Ale46/"]
- - ["Tommaso Pifferi", "http://github.com/neslinesli93/"]
-lang: it-it
----
-
-Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente pseudocodice eseguibile.
-
-Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service]
-
-Nota: Questo articolo è riferito a Python 3 in modo specifico. Se volete avete la necessità di utilizzare Python 2.7 potete consultarla [qui](https://learnxinyminutes.com/docs/it-it/python-it/)
-
-```python
-
-# I commenti su una sola linea iniziano con un cancelletto
-
-
-""" Più stringhe possono essere scritte
- usando tre ", e sono spesso usate
- come documentazione
-"""
-
-####################################################
-## 1. Tipi di dati primitivi ed Operatori
-####################################################
-
-# Ci sono i numeri
-3 # => 3
-
-# La matematica è quello che vi aspettereste
-1 + 1 # => 2
-8 - 1 # => 7
-10 * 2 # => 20
-35 / 5 # => 7.0
-
-# Risultato della divisione intera troncata sia in positivo che in negativo
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # works on floats too
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
-
-# Il risultato di una divisione è sempre un numero decimale (float)
-10.0 / 3 # => 3.3333333333333335
-
-# Operazione Modulo
-7 % 3 # => 1
-
-# Elevamento a potenza (x alla y-esima potenza)
-2**3 # => 8
-
-# Forzare le precedenze con le parentesi
-(1 + 3) * 2 # => 8
-
-# I valori booleani sono primitive del linguaggio (nota la maiuscola)
-True
-False
-
-# nega con not
-not True # => False
-not False # => True
-
-# Operatori Booleani
-# Nota "and" e "or" sono case-sensitive
-True and False # => False
-False or True # => True
-
-# Note sull'uso di operatori Bool con interi
-# False è 0 e True è 1
-# Non confonderti tra bool(ints) e le operazioni bitwise and/or (&,|)
-0 and 2 # => 0
--5 or 0 # => -5
-0 == False # => True
-2 == True # => False
-1 == True # => True
--5 != False != True #=> True
-
-# Uguaglianza è ==
-1 == 1 # => True
-2 == 1 # => False
-
-# Disuguaglianza è !=
-1 != 1 # => False
-2 != 1 # => True
-
-# Altri confronti
-1 < 10 # => True
-1 > 10 # => False
-2 <= 2 # => True
-2 >= 2 # => True
-
-# I confronti possono essere concatenati!
-1 < 2 < 3 # => True
-2 < 3 < 2 # => False
-
-# ('is' vs. '==')
-# 'is' controlla se due variabili si riferiscono allo stesso oggetto
-# '==' controlla se gli oggetti puntati hanno lo stesso valore.
-a = [1, 2, 3, 4] # a punta ad una nuova lista [1, 2, 3, 4]
-b = a # b punta a ciò a cui punta a
-b is a # => True, a e b puntano allo stesso oggeto
-b == a # => True, gli oggetti di a e b sono uguali
-b = [1, 2, 3, 4] # b punta ad una nuova lista [1, 2, 3, 4]
-b is a # => False, a e b non puntano allo stesso oggetto
-b == a # => True, gli oggetti di a e b sono uguali
-
-# Le stringhe sono create con " o '
-"Questa è una stringa."
-'Anche questa è una stringa.'
-
-# Anche le stringhe possono essere sommate! Ma cerca di non farlo.
-"Hello " + "world!" # => "Hello world!"
-# Le stringhe (ma non le variabili contenenti stringhe) possono essere
-# sommate anche senza '+'
-"Hello " "world!" # => "Hello world!"
-
-# Una stringa può essere considerata come una lista di caratteri
-"Questa è una stringa"[0] # => 'Q'
-
-# Puoi conoscere la lunghezza di una stringa
-len("Questa è una stringa") # => 20
-
-# .format può essere usato per formattare le stringhe, in questo modo:
-"{} possono essere {}".format("Le stringhe", "interpolate") # => "Le stringhe possono essere interpolate"
-
-# Puoi ripetere gli argomenti di formattazione per risparmiare un po' di codice
-"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
-# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
-
-# Puoi usare dei nomi se non vuoi contare gli argomenti
-"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="le lasagne") # => "Bob vuole mangiare le lasagne"
-
-# Se il tuo codice Python 3 necessita di eseguire codice Python 2.x puoi ancora
-# utilizzare il vecchio stile di formattazione:
-"%s possono essere %s nel %s modo" % ("Le stringhe", "interpolate", "vecchio") # => "Le stringhe possono essere interpolate nel vecchio modo"
-
-# None è un oggetto
-None # => None
-
-# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None
-# Usa "is" invece
-"etc" is None # => False
-None is None # => True
-
-# None, 0, e stringhe/liste/dizionari/tuple vuoti vengono considerati
-# falsi (False). Tutti gli altri valori sono considerati veri (True).
-bool(0) # => False
-bool("") # => False
-bool([]) # => False
-bool({}) # => False
-bool(()) # => False
-
-####################################################
-## 2. Variabili e Collections
-####################################################
-
-# Python ha una funzione per scrivere (sul tuo schermo)
-print("Sono Python. Piacere di conoscerti!") # => Sono Python. Piacere di conoscerti!
-
-# Di default la funzione print() scrive e va a capo aggiungendo un carattere
-# newline alla fine della stringa. È possibile utilizzare l'argomento opzionale
-# end per cambiare quest'ultimo carattere aggiunto.
-print("Hello, World", end="!") # => Hello, World!
-
-# Un modo semplice per ricevere dati in input dalla riga di comando
-variabile_stringa_input = input("Inserisci del testo: ") # Restituisce i dati letti come stringa
-# Nota: Nelle precedenti vesioni di Python, il metodo input()
-# era chiamato raw_input()
-
-# Non c'è bisogno di dichiarare una variabile per assegnarle un valore
-# Come convenzione, per i nomi delle variabili, si utilizzano i caratteri
-# minuscoli separati, se necessario, da underscore
-some_var = 5
-some_var # => 5
-
-# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione.
-# Dai un'occhiata al Control Flow per imparare di più su come gestire
-# le eccezioni.
-some_unknown_var # Genera un errore di nome
-
-# if può essere usato come un'espressione
-# È l'equivalente dell'operatore ternario in C
-"yahoo!" if 3 > 2 else 2 # => "yahoo!"
-
-# Le liste immagazzinano sequenze
-li = []
-# Puoi partire con una lista pre-riempita
-other_li = [4, 5, 6]
-
-# Aggiungere alla fine di una lista con append
-li.append(1) # li ora è [1]
-li.append(2) # li ora è [1, 2]
-li.append(4) # li ora è [1, 2, 4]
-li.append(3) # li ora è [1, 2, 4, 3]
-# Rimuovi dalla fine della lista con pop
-li.pop() # => 3 e li ora è [1, 2, 4]
-# Rimettiamolo a posto
-li.append(3) # li ora è [1, 2, 4, 3] di nuovo.
-
-# Accedi ad una lista come faresti con un array
-li[0] # => 1
-# Guarda l'ultimo elemento
-li[-1] # => 3
-
-# Guardare al di fuori dei limiti genera un IndexError
-li[4] # Genera IndexError
-
-# Puoi guardare gli intervalli con la sintassi slice (a fetta).
-# (E' un intervallo chiuso/aperto per voi tipi matematici.)
-li[1:3] # => [2, 4]
-# Ometti l'inizio
-li[2:] # => [4, 3]
-# Ometti la fine
-li[:3] # => [1, 2, 4]
-# Seleziona ogni seconda voce
-li[::2] # =>[1, 4]
-# Copia al contrario della lista
-li[::-1] # => [3, 4, 2, 1]
-# Usa combinazioni per fare slices avanzate
-# li[inizio:fine:passo]
-
-# Crea una copia (one layer deep copy) usando la sintassi slices
-li2 = li[:] # => li2 = [1, 2, 4, 3] ma (li2 is li) risulterà falso.
-
-# Rimuovi arbitrariamente elementi da una lista con "del"
-del li[2] # li è ora [1, 2, 3]
-
-# Rimuove la prima occorrenza di un elemento
-li.remove(2) # Ora li è [1, 3, 4, 5, 6]
-li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista
-
-# Inserisce un elemento all'indice specificato
-li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6]
-
- Ritorna l'indice della prima occorrenza dell'elemento fornito
-li.index(2) # => 1
-li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista
-
-# Puoi sommare le liste
-# Nota: i valori per li e per other_li non vengono modificati.
-li + other_li # => [1, 2, 3, 4, 5, 6]
-
-# Concatena le liste con "extend()"
-li.extend(other_li) # Adesso li è [1, 2, 3, 4, 5, 6]
-
-# Controlla l'esistenza di un valore in una lista con "in"
-1 in li # => True
-
-# Esamina la lunghezza con "len()"
-len(li) # => 6
-
-
-# Le tuple sono come le liste ma immutabili.
-tup = (1, 2, 3)
-tup[0] # => 1
-tup[0] = 3 # Genera un TypeError
-
-# Note that a tuple of length one has to have a comma after the last element but
-# tuples of other lengths, even zero, do not.
-type((1)) # => <class 'int'>
-type((1,)) # => <class 'tuple'>
-type(()) # => <class 'tuple'>
-
-# Puoi fare tutte queste cose da lista anche sulle tuple
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
-
-# Puoi scompattare le tuple (o liste) in variabili
-a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 e c è ora 3
-d, e, f = 4, 5, 6 # puoi anche omettere le parentesi
-# Le tuple sono create di default se non usi le parentesi
-g = 4, 5, 6 # => (4, 5, 6)
-# Guarda come è facile scambiare due valori
-e, d = d, e # d è ora 5 ed e è ora 4
-
-# I dizionari memorizzano insiemi di dati indicizzati da nomi arbitrari (chiavi)
-empty_dict= {}
-# Questo è un dizionario pre-caricato
-filled_dict = {"uno": 1, "due": 2, "tre": 3}
-
-# Nota: le chiavi dei dizionari devono essere di tipo immutabile. Questo per
-# assicurare che le chiavi possano essere convertite in calori hash costanti
-# per un risposta più veloce.
-invalid_dict = {[1,2,3]: "123"} # => Emette un TypeError: unhashable type: 'list'
-valid_dict = {(1,2,3):[1,2,3]} # I valori, invece, possono essere di qualunque tipo
-
-# Accedi ai valori indicando la chiave tra []
-filled_dict["uno"] # => 1
-
-# Puoi ottenere tutte le chiavi di un dizionario con "keys()"
-# (come oggetto iterabile). Per averle in formato lista è necessario
-# utilizzare list().
-# Nota - Nei dizionari l'ordine delle chiavi non è garantito.
-# Il tuo risultato potrebbe non essere uguale a questo.
-list(filled_dict.keys()) # => ["tre", "due", "uno"]
-
-
-# Puoi ottenere tutti i valori di un dizionario con "values()"
-# (come oggetto iterabile).
-# Anche in questo caso, er averle in formato lista, è necessario utilizzare list()
-# Anche in questo caso, come per le chiavi, l'ordine non è garantito
-list(filled_dict.values()) # => [3, 2, 1]
-
-# Controlla l'esistenza delle chiavi in un dizionario con "in"
-"uno" in filled_dict # => True
-1 in filled_dict # => False
-
-# Cercando una chiave non esistente genera un KeyError
-filled_dict["quattro"] # KeyError
-
-# Usa il metodo "get()" per evitare KeyError
-filled_dict.get("uno") # => 1
-filled_dict.get("quattro") # => None
-# Il metodo get supporta un argomento di default quando il valore è mancante
-filled_dict.get("uno", 4) # => 1
-filled_dict.get("quattro", 4) # => 4
-
-
-# "setdefault()" inserisce un valore per una chiave in un dizionario
-# solo se la chiave data non è già presente
-filled_dict.setdefault("cinque", 5) # filled_dict["cinque"] viene impostato a 5
-filled_dict.setdefault("cinque", 6) # filled_dict["cinque"] rimane 5
-
-# Aggiungere una coppia chiave->valore a un dizionario
-filled_dict.update({"quattro":4}) # => {"uno": 1, "due": 2, "tre": 3, "quattro": 4}
-filled_dict["quattro"] = 4 # un altro modo pe aggiungere a un dizionario
-
-# Rimuovi una chiave da un dizionario con del
-del filled_dict["uno"] # Rimuove la chiave "uno" dal dizionario
-
-# Da Python 3.5 puoi anche usare ulteriori opzioni di spacchettamento
-{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
-{'a': 1, **{'a': 2}} # => {'a': 2}
-
-# I set sono come le liste ma non possono contenere doppioni
-empty_set = set()
-# Inizializza un "set()" con un dei valori. Sì, sembra un dizionario.
-some_set = {1, 1, 2, 2, 3, 4} # set_nuovo è {1, 2, 3, 4}
-
-# Come le chiavi di un dizionario, gli elementi di un set devono essere
-# di tipo immutabile
-invalid_set = {[1], 1} # => Genera un "TypeError: unhashable type: 'list'""
-valid_set = {(1,), 1}
-
-# Aggiungere uno o più elementi ad un set
-some_set.add(5) # some_set ora è {1, 2, 3, 4, 5}
-
-# Fai intersezioni su un set con &
-other_set = {3, 4, 5, 6}
-some_set & other_set # => {3, 4, 5}
-
-# Fai unioni su set con |
-some_set | other_set # => {1, 2, 3, 4, 5, 6}
-
-# Fai differenze su set con -
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
-
-# Effettua la differenza simmetrica con ^
-{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
-
-# Controlla se il set a sinistra contiene quello a destra
-{1, 2} >= {1, 2, 3} # => False
-
-# Controlla se il set a sinistra è un sottoinsieme di quello a destra
-{1, 2} <= {1, 2, 3} # => True
-
-# Controlla l'esistenza in un set con in
-2 in some_set # => True
-10 in some_set # => False
-
-
-
-####################################################
-## 3. Control Flow e oggetti Iterabili
-####################################################
-
-# Dichiariamo una variabile
-some_var = 5
-
-# Questo è un controllo if. L'indentazione è molto importante in python!
-# Come convenzione si utilizzano quattro spazi, non la tabulazione.
-# Il seguente codice stampa "some_var è minore di 10"
-if some_var > 10:
- print("some_var è maggiore di 10")
-elif some_var < 10: # La clausolo elif è opzionale
- print("some_var è minore di 10")
-else: # Anche else è opzionale
- print("some_var è 10.")
-
-"""
-I cicli for iterano sulle liste, cioè ripetono un codice per ogni elemento
-di una lista.
-Il seguente codice scriverà:
- cane è un mammifero
- gatto è un mammifero
- topo è un mammifero
-"""
-for animale in ["cane", "gatto", "topo"]:
- # Puoi usare format() per interpolare le stringhe formattate.
- print("{} è un mammifero".format(animale))
-
-"""
-"range(numero)" restituisce una lista di numeri da zero al numero dato
-Il seguente codice scriverà:
- 0
- 1
- 2
- 3
-"""
-for i in range(4):
- print(i)
-
-"""
-"range(lower, upper)" restituisce una lista di numeri dal più piccolo (lower)
-al più grande (upper).
-Il seguente codice scriverà:
- 4
- 5
- 6
- 7
-"""
-for i in range(4, 8):
- print(i)
-
-"""
-"range(lower, upper, step)" rrestituisce una lista di numeri dal più piccolo
-(lower) al più grande (upper), incrementando del valore step.
-Se step non è indicato, avrà come valore di default 1.
-Il seguente codice scriverà:
- 4
- 6
-"""
-for i in range(4, 8, 2):
- print(i)
-"""
-
-I cicli while vengono eseguiti finchè una condizione viene a mancare
-Il seguente codice scriverà:
- 0
- 1
- 2
- 3
-"""
-x = 0
-while x < 4:
- print(x)
- x += 1 # Forma compatta per x = x + 1
-
-# Gestione delle eccezioni con un blocco try/except
-try:
- # Usa "raise" per generare un errore
- raise IndexError("Questo è un IndexError")
-except IndexError as e:
- pass # Pass è solo una non-operazione. Solitamente vorrai rimediare all'errore.
-except (TypeError, NameError):
- pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario.
-else: # Clausola opzionale al blocco try/except. Deve essere dopo tutti i blocchi except
- print("Tutto ok!") # Viene eseguita solo se il codice dentro try non genera eccezioni
-finally: # Eseguito sempre
- print("Possiamo liberare risorse qui")
-
-# Se ti serve solo un try/finally, per liberare risorse, puoi usare il metodo with
-with open("myfile.txt") as f:
- for line in f:
- print(line)
-
-# In Python qualunque oggetto in grado di essere trattato come una
-# sequenza è definito un oggetto Iterable (itarabile).
-# L'oggetto restituito da una funzione range è un iterabile.
-
-filled_dict = {"uno": 1, "due": 2, "tre": 3}
-our_iterable = filled_dict.keys()
-print(our_iterable) # => dict_keys(['uno', 'due', 'tre']).
-# Questo è un oggetto che implementa la nostra interfaccia Iterable.
-
-# È possibile utilizzarlo con i loop:
-for i in our_iterable:
- print(i) # Scrive uno, due, tre
-
-# Tuttavia non possiamo recuperarne i valori tramite indice.
-our_iterable[1] # Genera un TypeError
-
-# Un oggetto iterabile è in grado di generare un iteratore
-our_iterator = iter(our_iterable)
-
-# L'iteratore è un oggetto che ricorda il suo stato mentro lo si "attraversa"
-# Possiamo accedere al successivo elemento con "next()".
-next(our_iterator) # => "uno"
-
-# Mantiene il suo stato mentro eseguiamo l'iterazione
-next(our_iterator) # => "due"
-next(our_iterator) # => "tre"
-
-# Dopo che un iteratore ha restituito tutti i suoi dati, genera
-# un'eccezione StopIteration
-next(our_iterator) # Raises StopIteration
-
-# Puoi prendere tutti gli elementi di un iteratore utilizzando list().
-list(filled_dict.keys()) # => Returns ["one", "two", "three"]
-
-
-
-####################################################
-## 4. Funzioni
-####################################################
-
-# Usa "def" per creare nuove funzioni
-def aggiungi(x, y):
- print("x è {} e y è {}".format(x, y)) // Scrive i valori formattati in una stringa
- return x + y # Restituisce la somma dei valori con il metodo return
-
-# Chiamare funzioni con parametri
-aggiungi(5, 6) # => scrive "x è 5 e y è 6" e restituisce 11
-
-# Un altro modo per chiamare funzioni è con parole chiave come argomenti
-aggiungi(y=6, x=5) # In questo modo non è necessario rispettare l'ordine degli argomenti
-
-# Puoi definire funzioni che accettano un numero non definito di argomenti
-def varargs(*args):
- return args
-
-varargs(1, 2, 3) # => (1, 2, 3)
-
-# Puoi definire funzioni che accettano un numero variabile di parole chiave
-# come argomento, che saranno interpretati come un dizionario usando **
-def keyword_args(**kwargs):
- return kwargs
-
-# Chiamiamola per vedere cosa succede
-keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
-
-
-# Puoi farle entrambi in una volta, se ti va
-def all_the_args(*args, **kwargs):
- print(args)
- print(kwargs)
-"""
-all_the_args(1, 2, a=3, b=4) stampa:
- (1, 2)
- {"a": 3, "b": 4}
-"""
-
-# Quando chiami funzioni, puoi fare l'opposto di args/kwargs!
-# Usa * per sviluppare gli argomenti posizionale ed usa ** per
-# espandere gli argomenti parola chiave
-args = (1, 2, 3, 4)
-kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
-all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
-
-
-# Restituire valori multipli (with tuple assignments)
-def swap(x, y):
- return y, x # Restituisce valori multipli come tupla senza parentesi
- # (Nota: le parentesi sono state escluse ma possono essere messe)
-
-x = 1
-y = 2
-x, y = swap(x, y) # => x = 2, y = 1
-# (x, y) = swap(x,y) # Le parentesi sono state escluse ma possono essere incluse.
-
-# Funzioni - Visibilità delle variabili (variable scope)
-x = 5
-
-def set_x(num):
- # La variabile locale x non è la variabile globale x
- x = num # => 43
- print(x) # => 43
-
-def set_global_x(num):
- global x
- print(x) # => 5
- x = num # la variabile globable x è ora 6
- print(x) # => 6
-
-set_x(43)
-set_global_x(6)
-
-
-# Python ha "first class functions"
-def create_adder(x):
- def adder(y):
- return x + y
- return adder
-
-add_10 = create_adder(10)
-add_10(3) # => 13
-
-# Ci sono anche funzioni anonime
-(lambda x: x > 2)(3) # => True
-(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
-
-# È possibile creare "mappe" e "filtri"
-list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
-list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
-
-list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
-
-# Possiamo usare le "list comprehensions" per mappe e filtri
-# Le "list comprehensions" memorizzano l'output come una lista che può essere
-# di per sé una lista annidata
-[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
-
-# Puoi fare anche la comprensione di set e dizionari
-{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
-{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
-
-
-####################################################
-## 5. Modules
-####################################################
-
-# Puoi importare moduli
-import math
-print(math.sqrt(16)) # => 4.0
-
-# Puoi ottenere specifiche funzione da un modulo
-from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
-
-# Puoi importare tutte le funzioni da un modulo
-# Attenzione: questo non è raccomandato
-from math import *
-
-# Puoi abbreviare i nomi dei moduli
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
-
-
-# I moduli di Python sono normali file python. Ne puoi
-# scrivere di tuoi ed importarli. Il nome del modulo
-# è lo stesso del nome del file.
-
-# Potete scoprire quali funzioni e attributi
-# sono definiti in un modulo
-import math
-dir(math)
-
-# Se nella cartella corrente hai uno script chiamato math.py,
-# Python caricherà quello invece del modulo math.
-# Questo succede perchè la cartella corrente ha priorità
-# sulle librerie standard di Python
-
-# Se hai uno script Python chiamato math.py nella stessa
-# cartella del tua script, Python caricherà quello al posto del
-# comune modulo math.
-# Questo accade perché la cartella locale ha la priorità
-# sulle librerie built-in di Python.
-
-
-####################################################
-## 6. Classes
-####################################################
-
-# Usiamo l'istruzione "class" per creare una classe
-class Human:
-
- # Un attributo della classe. E' condiviso tra tutte le istanze delle classe
- species = "H. sapiens"
-
- # Si noti che i doppi underscore iniziali e finali denotano gli oggetti o
- # attributi utilizzati da Python ma che vivono nel namespace controllato
- # dall'utente
- # Metodi, oggetti o attributi come: __init__, __str__, __repr__, etc. sono
- # chiamati metodi speciali (o talvolta chiamati "dunder methods").
- # Non dovresti inventare tali nomi da solo.
-
- def __init__(self, name):
- # Assegna l'argomento all'attributo name dell'istanza
- self.name = name
-
- # Inizializza una proprietà
- self._age = 0
-
- # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento
- def say(self, msg):
- print("{name}: {message}".format(name=self.name, message=msg))
-
- # Un altro metodo dell'istanza
- def sing(self):
- return 'yo... yo... microphone check... one two... one two...'
-
- # Un metodo della classe è condiviso fra tutte le istanze
- # Sono chiamati con la classe chiamante come primo argomento
- @classmethod
- def get_species(cls):
- return cls.species
-
- # Un metodo statico è chiamato senza classe o istanza di riferimento
- @staticmethod
- def grunt():
- return "*grunt*"
-
- # Una property è come un metodo getter.
- # Trasforma il metodo age() in un attributo in sola lettura, che ha
- # lo stesso nome
- # In Python non c'è bisogno di scrivere futili getter e setter.
- @property
- def age(self):
- return self._age
-
- # Questo metodo permette di modificare una property
- @age.setter
- def age(self, age):
- self._age = age
-
- # Questo metodo permette di cancellare una property
- @age.deleter
- def age(self):
- del self._age
-
-# Quando l'interprete Python legge un sorgente esegue tutto il suo codice.
-# Questo controllo su __name__ assicura che questo blocco di codice venga
-# eseguito solo quando questo modulo è il programma principale.
-
-if __name__ == '__main__':
- # Crea un'istanza della classe
- i = Human(name="Ian")
- i.say("hi") # "Ian: hi"
- j = Human("Joel")
- j.say("hello") # "Joel: hello"
- # i e j sono istanze del tipo Human, o in altre parole sono oggetti Human
-
- # Chiama un metodo della classe
- i.say(i.get_species()) # "Ian: H. sapiens"
- # Cambia l'attributo condiviso
- Human.species = "H. neanderthalensis"
- i.say(i.get_species()) # => "Ian: H. neanderthalensis"
- j.say(j.get_species()) # => "Joel: H. neanderthalensis"
-
- # Chiama un metodo statico
- print(Human.grunt()) # => "*grunt*"
-
- # Non è possibile chiamare il metodo statico con l'istanza dell'oggetto
- # poiché i.grunt() metterà automaticamente "self" (l'oggetto i)
- # come argomento
- print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
-
- # Aggiorna la property (age) di questa istanza
- i.age = 42
- # Leggi la property
- i.say(i.age) # => "Ian: 42"
- j.say(j.age) # => "Joel: 0"
- # Cancella la property
- del i.age
- i.age # => questo genererà un AttributeError
-
-
-####################################################
-## 6.1 Ereditarietà (Inheritance)
-####################################################
-
-# L'ereditarietà consente di definire nuove classi figlio che ereditano metodi e
-# variabili dalla loro classe genitore.
-
-# Usando la classe Human definita sopra come classe base o genitore, possiamo
-# definire una classe figlia, Superhero, che erediterà le variabili di classe
-# come "species", "name" e "age", così come i metodi, come "sing" e "grunt",
-# dalla classe Human, ma potrà anche avere le sue proprietà uniche.
-
-# Per importare le funzioni da altri file usa il seguente formato
-# from "nomefile-senza-estensione" import "funzione-o-classe"
-
-from human import Human
-
-# Specificare le classi genitore come parametri della definizione della classe
-class Superhero(Human):
-
- # Se la classe figlio deve ereditare tutte le definizioni del genitore
- # senza alcuna modifica, puoi semplicemente usare la parola chiave "pass"
- # (e nient'altro)
-
- #Le classi figlio possono sovrascrivere gli attributi dei loro genitori
- species = 'Superhuman'
-
- # Le classi figlie ereditano automaticamente il costruttore della classe
- # genitore, inclusi i suoi argomenti, ma possono anche definire ulteriori
- # argomenti o definizioni e sovrascrivere i suoi metodi (compreso il
- # costruttore della classe).
- # Questo costruttore eredita l'argomento "nome" dalla classe "Human" e
- # aggiunge gli argomenti "superpowers" e "movie":
-
- def __init__(self, name, movie=False,
- superpowers=["super strength", "bulletproofing"]):
-
- # aggiungi ulteriori attributi della classe
- self.fictional = True
- self.movie = movie
- self.superpowers = superpowers
-
- # La funzione "super" ti consente di accedere ai metodi della classe
- # genitore che sono stati sovrascritti dalla classe figlia,
- # in questo caso il metodo __init__.
- # Il seguente codice esegue il costruttore della classe genitore:
- super().__init__(name)
-
- # Sovrascrivere il metodo "sing"
- def sing(self):
- return 'Dun, dun, DUN!'
-
- # Aggiungi un ulteriore metodo dell'istanza
- def boast(self):
- for power in self.superpowers:
- print("I wield the power of {pow}!".format(pow=power))
-
-
-if __name__ == '__main__':
- sup = Superhero(name="Tick")
-
- # Controllo del tipo di istanza
- if isinstance(sup, Human):
- print('I am human')
- if type(sup) is Superhero:
- print('I am a superhero')
-
- # Ottieni il "Method Resolution search Order" usato sia da getattr ()
- # che da super (). Questo attributo è dinamico e può essere aggiornato
- print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
- # => <class 'human.Human'>, <class 'object'>)
-
- # Esegui il metodo principale ma utilizza il proprio attributo di classe
- print(sup.get_species()) # => Superhuman
-
- # Esegui un metodo che è stato sovrascritto
- print(sup.sing()) # => Dun, dun, DUN!
-
- # Esegui un metodo di Human
- sup.say('Spoon') # => Tick: Spoon
-
- # Esegui un metodo che esiste solo in Superhero
- sup.boast() # => I wield the power of super strength!
- # => I wield the power of bulletproofing!
-
- # Attributo di classe ereditato
- sup.age = 31
- print(sup.age) # => 31
-
- # Attributo che esiste solo in Superhero
- print('Am I Oscar eligible? ' + str(sup.movie))
-
-####################################################
-## 6.2 Ereditarietà multipla
-####################################################
-
-# Un'altra definizione di classe
-# bat.py
-class Bat:
-
- species = 'Baty'
-
- def __init__(self, can_fly=True):
- self.fly = can_fly
-
- # Questa classe ha anche un metodo "say"
- def say(self, msg):
- msg = '... ... ...'
- return msg
-
- # E anche un suo metodo personale
- def sonar(self):
- return '))) ... ((('
-
-if __name__ == '__main__':
- b = Bat()
- print(b.say('hello'))
- print(b.fly)
-
-# Definizione di classe che eredita da Superhero e Bat
-# superhero.py
-from superhero import Superhero
-from bat import Bat
-
-# Definisci Batman come classe figlia che eredita sia da Superhero che da Bat
-class Batman(Superhero, Bat):
-
- def __init__(self, *args, **kwargs):
- # In genere per ereditare gli attributi devi chiamare super:
- # super(Batman, self).__init__(*args, **kwargs)
- # Ma qui abbiamo a che fare con l'ereditarietà multipla, e super()
- # funziona solo con la successiva classe nell'elenco MRO.
- # Quindi, invece, chiamiamo esplicitamente __init__ per tutti gli
- # antenati. L'uso di *args e **kwargs consente di passare in modo
- # pulito gli argomenti, con ciascun genitore che "sbuccia un
- # livello della cipolla".
- Superhero.__init__(self, 'anonymous', movie=True,
- superpowers=['Wealthy'], *args, **kwargs)
- Bat.__init__(self, *args, can_fly=False, **kwargs)
- # sovrascrivere il valore per l'attributo name
- self.name = 'Sad Affleck'
-
- def sing(self):
- return 'nan nan nan nan nan batman!'
-
-
-if __name__ == '__main__':
- sup = Batman()
-
- # Ottieni il "Method Resolution search Order" utilizzato da getattr() e super().
- # Questo attributo è dinamico e può essere aggiornato
- print(Batman.__mro__) # => (<class '__main__.Batman'>,
- # => <class 'superhero.Superhero'>,
- # => <class 'human.Human'>,
- # => <class 'bat.Bat'>, <class 'object'>)
-
- # Esegui il metodo del genitore ma utilizza il proprio attributo di classe
- print(sup.get_species()) # => Superhuman
-
- # Esegui un metodo che è stato sovrascritto
- print(sup.sing()) # => nan nan nan nan nan batman!
-
- # Esegui un metodo da Human, perché l'ordine di ereditarietà è importante
- sup.say('I agree') # => Sad Affleck: I agree
-
- # Esegui un metodo che esiste solo nel 2o antenato
- print(sup.sonar()) # => ))) ... (((
-
- # Attributo di classe ereditato
- sup.age = 100
- print(sup.age) # => 100
-
- # Attributo ereditato dal secondo antenato il cui valore predefinito
- # è stato ignorato.
- print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
-
-
-
-####################################################
-## 7. Advanced
-####################################################
-
-# I generatori ti aiutano a creare codice pigro (lazy code).
-# Codice che darà un risultato solo quando sarà "valutato"
-def double_numbers(iterable):
- for i in iterable:
- yield i + i
-
-# I generatori sono efficienti in termini di memoria perché caricano
-# solo i dati necessari per elaborare il valore successivo nell'iterabile.
-# Ciò consente loro di eseguire operazioni su intervalli di valori
-# altrimenti proibitivi.
-# NOTA: `range` sostituisce` xrange` in Python 3.
-for i in double_numbers(range(1, 900000000)): # `range` is a generator.
- print(i)
- if i >= 30:
- break
-
-# Proprio come è possibile creare una "list comprehension", è possibile
-# creare anche delle "generator comprehensions".
-values = (-x for x in [1,2,3,4,5])
-for x in values:
- print(x) # prints -1 -2 -3 -4 -5 to console/terminal
-
-# Puoi anche trasmettere una "generator comprehensions" direttamente
-# ad un elenco.
-values = (-x for x in [1,2,3,4,5])
-gen_to_list = list(values)
-print(gen_to_list) # => [-1, -2, -3, -4, -5]
-
-
-# Decoratori
-# In questo esempio "beg" avvolge/wrappa "say".
-# Se say_please è True, cambierà il messaggio restituito.
-from functools import wraps
-
-def beg(target_function):
- @wraps(target_function)
- def wrapper(*args, **kwargs):
- msg, say_please = target_function(*args, **kwargs)
- if say_please:
- return "{} {}".format(msg, "Per favore! Sono povero :(")
- return msg
-
- return wrapper
-
-
-@beg
-def say(say_please=False):
- msg = "Puoi comprarmi una birra?"
- return msg, say_please
-
-
-print(say()) # Puoi comprarmi una birra?
-print(say(say_please=True)) # Puoi comprarmi una birra? Per favore! Sono povero :(
-```
-
-## Pronto per qualcosa di più?
-
-### Gratis Online
-
-* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Course](http://www.python-course.eu/index.php)
-* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
-* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
-* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
-* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
-* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
-* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
-* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
diff --git a/it-it/pythonlegacy-it.html.markdown b/it-it/pythonlegacy-it.html.markdown
new file mode 100644
index 00000000..4c8b2a17
--- /dev/null
+++ b/it-it/pythonlegacy-it.html.markdown
@@ -0,0 +1,778 @@
+---
+language: Python 2 (legacy)
+filename: learnpythonlegacy-it.py
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Amin Bandali", "http://aminbandali.com"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
+translators:
+ - ["Ale46", "http://github.com/Ale46/"]
+ - ["Tommaso Pifferi", "http://github.com/neslinesli93/"]
+lang: it-it
+---
+Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari
+linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente
+pseudocodice eseguibile.
+
+Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service]
+
+Nota: questo articolo è riferito a Python 2.7 in modo specifico, ma dovrebbe andar
+bene anche per Python 2.x. Python 2.7 sta raggiungendo il "fine vita", ovvero non sarà
+più supportato nel 2020. Quindi è consigliato imparare Python utilizzando Python 3.
+Per maggiori informazioni su Python 3.x, dai un'occhiata al [tutorial di Python 3](http://learnxinyminutes.com/docs/python/).
+
+E' possibile anche scrivere codice compatibile sia con Python 2.7 che con Python 3.x,
+utilizzando [il modulo `__future__`](https://docs.python.org/2/library/__future__.html) di Python.
+Il modulo `__future__` permette di scrivere codice in Python 3, che può essere eseguito
+utilizzando Python 2: cosa aspetti a vedere il tutorial di Python 3?
+
+```python
+
+# I commenti su una sola linea iniziano con un cancelletto
+
+""" Più stringhe possono essere scritte
+ usando tre ", e sono spesso usate
+ come commenti
+"""
+
+####################################################
+## 1. Tipi di dati primitivi ed Operatori
+####################################################
+
+# Hai i numeri
+3 # => 3
+
+# La matematica è quello che vi aspettereste
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7
+
+# La divisione è un po' complicata. E' una divisione fra interi in cui viene
+# restituito in automatico il risultato intero.
+5 / 2 # => 2
+
+# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats.
+2.0 # Questo è un float
+11.0 / 4.0 # => 2.75 ahhh...molto meglio
+
+# Il risultato di una divisione fra interi troncati positivi e negativi
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # funziona anche per i floats
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# E' possibile importare il modulo "division" (vedi la sezione 6 di questa guida, Moduli)
+# per effettuare la divisione normale usando solo '/'.
+from __future__ import division
+11/4 # => 2.75 ...divisione normale
+11//4 # => 2 ...divisione troncata
+
+# Operazione Modulo
+7 % 3 # => 1
+
+# Elevamento a potenza (x alla y-esima potenza)
+2**4 # => 16
+
+# Forzare le precedenze con le parentesi
+(1 + 3) * 2 # => 8
+
+# Operatori Booleani
+# Nota "and" e "or" sono case-sensitive
+True and False #=> False
+False or True #=> True
+
+# Note sull'uso di operatori Bool con interi
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
+# nega con not
+not True # => False
+not False # => True
+
+# Uguaglianza è ==
+1 == 1 # => True
+2 == 1 # => False
+
+# Disuguaglianza è !=
+1 != 1 # => False
+2 != 1 # => True
+
+# Altri confronti
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# I confronti possono essere concatenati!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# Le stringhe sono create con " o '
+"Questa è una stringa."
+'Anche questa è una stringa.'
+
+# Anche le stringhe possono essere sommate!
+"Ciao " + "mondo!" # => Ciao mondo!"
+# Le stringhe possono essere sommate anche senza '+'
+"Ciao " "mondo!" # => Ciao mondo!"
+
+# ... oppure moltiplicate
+"Hello" * 3 # => "HelloHelloHello"
+
+# Una stringa può essere considerata come una lista di caratteri
+"Questa è una stringa"[0] # => 'Q'
+
+# Per sapere la lunghezza di una stringa
+len("Questa è una stringa") # => 20
+
+# Formattazione delle stringhe con %
+# Anche se l'operatore % per le stringe sarà deprecato con Python 3.1, e verrà rimosso
+# successivamente, può comunque essere utile sapere come funziona
+x = 'mela'
+y = 'limone'
+z = "La cesta contiene una %s e un %s" % (x,y)
+
+# Un nuovo modo per fomattare le stringhe è il metodo format.
+# Questo metodo è quello consigliato
+"{} è un {}".format("Questo", "test")
+"{0} possono essere {1}".format("le stringhe", "formattate")
+# Puoi usare delle parole chiave se non vuoi contare
+"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna")
+
+# None è un oggetto
+None # => None
+
+# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None
+# Usa "is" invece
+"etc" is None # => False
+None is None # => True
+
+# L'operatore 'is' testa l'identità di un oggetto. Questo non è
+# molto utile quando non hai a che fare con valori primitivi, ma lo è
+# quando hai a che fare con oggetti.
+
+# Qualunque oggetto può essere usato nei test booleani
+# I seguenti valori sono considerati falsi:
+# - None
+# - Lo zero, come qualunque tipo numerico (quindi 0, 0L, 0.0, 0.j)
+# - Sequenze vuote (come '', (), [])
+# - Contenitori vuoti (tipo {}, set())
+# - Istanze di classi definite dall'utente, che soddisfano certi criteri
+# vedi: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# Tutti gli altri valori sono considerati veri: la funzione bool() usata su di loro, ritorna True.
+bool(0) # => False
+bool("") # => False
+
+
+####################################################
+## 2. Variabili e Collections
+####################################################
+
+# Python ha una funzione di stampa
+print "Sono Python. Piacere di conoscerti!" # => Sono Python. Piacere di conoscerti!
+
+# Un modo semplice per ricevere dati in input dalla riga di comando
+variabile_stringa_input = raw_input("Inserisci del testo: ") # Ritorna i dati letti come stringa
+variabile_input = input("Inserisci del testo: ") # Interpreta i dati letti come codice python
+# Attenzione: bisogna stare attenti quando si usa input()
+# Nota: In python 3, input() è deprecato, e raw_input() si chiama input()
+
+# Non c'è bisogno di dichiarare una variabile per assegnarle un valore
+una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores
+una_variabile # => 5
+
+# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione.
+# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni.
+un_altra_variabile # Genera un errore di nome
+
+# if può essere usato come un'espressione
+# E' l'equivalente dell'operatore ternario in C
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# Liste immagazzinano sequenze
+li = []
+# Puoi partire con una lista pre-riempita
+altra_li = [4, 5, 6]
+
+# Aggiungi cose alla fine di una lista con append
+li.append(1) # li ora è [1]
+li.append(2) # li ora è [1, 2]
+li.append(4) # li ora è [1, 2, 4]
+li.append(3) # li ora è [1, 2, 4, 3]
+# Rimuovi dalla fine della lista con pop
+li.pop() # => 3 e li ora è [1, 2, 4]
+# Rimettiamolo a posto
+li.append(3) # li ora è [1, 2, 4, 3] di nuovo.
+
+# Accedi ad una lista come faresti con un array
+li[0] # => 1
+# Assegna nuovo valore agli indici che sono già stati inizializzati con =
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # Nota: è resettato al valore iniziale
+# Guarda l'ultimo elemento
+li[-1] # => 3
+
+# Guardare al di fuori dei limiti è un IndexError
+li[4] # Genera IndexError
+
+# Puoi guardare gli intervalli con la sintassi slice (a fetta).
+# (E' un intervallo chiuso/aperto per voi tipi matematici.)
+li[1:3] # => [2, 4]
+# Ometti l'inizio
+li[2:] # => [4, 3]
+# Ometti la fine
+li[:3] # => [1, 2, 4]
+# Seleziona ogni seconda voce
+li[::2] # =>[1, 4]
+# Copia al contrario della lista
+li[::-1] # => [3, 4, 2, 1]
+# Usa combinazioni per fare slices avanzate
+# li[inizio:fine:passo]
+
+# Rimuovi arbitrariamente elementi da una lista con "del"
+del li[2] # li è ora [1, 2, 3]
+# Puoi sommare le liste
+li + altra_li # => [1, 2, 3, 4, 5, 6]
+# Nota: i valori per li ed altra_li non sono modificati.
+
+# Concatena liste con "extend()"
+li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6]
+
+# Rimuove la prima occorrenza di un elemento
+li.remove(2) # Ora li è [1, 3, 4, 5, 6]
+li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista
+
+# Inserisce un elemento all'indice specificato
+li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6]
+
+# Ritorna l'indice della prima occorrenza dell'elemento fornito
+li.index(2) # => 1
+li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista
+
+# Controlla l'esistenza di un valore in una lista con "in"
+1 in li # => True
+
+# Esamina la lunghezza con "len()"
+len(li) # => 6
+
+
+# Tuple sono come le liste ma immutabili.
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # Genera un TypeError
+
+# Puoi fare tutte queste cose da lista anche sulle tuple
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Puoi scompattare le tuple (o liste) in variabili
+a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3
+d, e, f = 4, 5, 6 # puoi anche omettere le parentesi
+# Le tuple sono create di default se non usi le parentesi
+g = 4, 5, 6 # => (4, 5, 6)
+# Guarda come è facile scambiare due valori
+e, d = d, e # d è ora 5 ed e è ora 4
+
+
+# Dizionari immagazzinano mappature
+empty_dict = {}
+# Questo è un dizionario pre-riempito
+filled_dict = {"uno": 1, "due": 2, "tre": 3}
+
+# Accedi ai valori con []
+filled_dict["uno"] # => 1
+
+# Ottieni tutte le chiavi come una lista con "keys()"
+filled_dict.keys() # => ["tre", "due", "uno"]
+# Nota - Nei dizionari l'ordine delle chiavi non è garantito.
+# Il tuo risultato potrebbe non essere uguale a questo.
+
+# Ottieni tutt i valori come una lista con "values()"
+filled_dict.values() # => [3, 2, 1]
+# Nota - Come sopra riguardo l'ordinamento delle chiavi.
+
+# Ottieni tutte le coppie chiave-valore, sotto forma di lista di tuple, utilizzando "items()"
+filled_dicts.items() # => [("uno", 1), ("due", 2), ("tre", 3)]
+
+# Controlla l'esistenza delle chiavi in un dizionario con "in"
+"uno" in filled_dict # => True
+1 in filled_dict # => False
+
+# Cercando una chiave non esistente è un KeyError
+filled_dict["quattro"] # KeyError
+
+# Usa il metodo "get()" per evitare KeyError
+filled_dict.get("uno") # => 1
+filled_dict.get("quattro") # => None
+# Il metodo get supporta un argomento di default quando il valore è mancante
+filled_dict.get("uno", 4) # => 1
+filled_dict.get("quattro", 4) # => 4
+# nota che filled_dict.get("quattro") è ancora => None
+# (get non imposta il valore nel dizionario)
+
+# imposta il valore di una chiave con una sintassi simile alle liste
+filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4
+
+# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente
+filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5
+
+
+# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni)
+empty_set = set()
+# Inizializza un "set()" con un po' di valori
+some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4])
+
+# l'ordine non è garantito, anche se a volta può sembrare ordinato
+another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4])
+
+# Da Python 2.7, {} può essere usato per dichiarare un set
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# Aggiungere elementi ad un set
+filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5}
+
+# Fai intersezioni su un set con &
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# Fai unioni su set con |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# Fai differenze su set con -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# Effettua la differenza simmetrica con ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Controlla se il set a sinistra contiene quello a destra
+{1, 2} >= {1, 2, 3} # => False
+
+# Controlla se il set a sinistra è un sottoinsieme di quello a destra
+{1, 2} <= {1, 2, 3} # => True
+
+# Controlla l'esistenza in un set con in
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+## 3. Control Flow
+####################################################
+
+# Dichiariamo una variabile
+some_var = 5
+
+# Questo è un controllo if. L'indentazione è molto importante in python!
+# stampa "some_var è più piccola di 10"
+if some_var > 10:
+ print "some_var è decisamente più grande di 10."
+elif some_var < 10: # Questa clausola elif è opzionale.
+ print "some_var è più piccola di 10."
+else: # Anche questo è opzionale.
+ print "some_var è precisamente 10."
+
+
+"""
+I cicli for iterano sulle liste
+stampa:
+ cane è un mammifero
+ gatto è un mammifero
+ topo è un mammifero
+"""
+for animale in ["cane", "gatto", "topo"]:
+ # Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.)
+ print "{0} è un mammifero".format(animale)
+
+"""
+"range(numero)" restituisce una lista di numeri
+da zero al numero dato
+stampa:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+"range(lower, upper)" restituisce una lista di numeri
+dal più piccolo (lower) al più grande (upper)
+stampa:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print i
+
+"""
+I cicli while vengono eseguiti finchè una condizione viene a mancare
+stampa:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Forma compatta per x = x + 1
+
+# Gestisci le eccezioni con un blocco try/except
+
+# Funziona da Python 2.6 in su:
+try:
+ # Usa "raise" per generare un errore
+ raise IndexError("Questo è un errore di indice")
+except IndexError as e:
+ pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero.
+except (TypeError, NameError):
+ pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario.
+else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except
+ print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni
+finally: # Eseguito sempre
+ print "Possiamo liberare risorse qui"
+
+# Invece di try/finally per liberare risorse puoi usare il metodo with
+with open("myfile.txt") as f:
+ for line in f:
+ print line
+
+####################################################
+## 4. Funzioni
+####################################################
+
+# Usa "def" per creare nuove funzioni
+def aggiungi(x, y):
+ print "x è {0} e y è {1}".format(x, y)
+ return x + y # Restituisce valori con il metodo return
+
+# Chiamare funzioni con parametri
+aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11
+
+# Un altro modo per chiamare funzioni è con parole chiave come argomenti
+aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine.
+
+
+# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali
+# che verranno interpretati come tuple usando il *
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+
+# Puoi definire funzioni che accettano un numero variabile di parole chiave
+# come argomento, che saranno interpretati come un dizionario usando **
+def keyword_args(**kwargs):
+ return kwargs
+
+# Chiamiamola per vedere cosa succede
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# Puoi farle entrambi in una volta, se ti va
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) stampa:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Quando chiami funzioni, puoi fare l'opposto di args/kwargs!
+# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
+
+# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs
+# sviluppandoli, rispettivamente, con * e **
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
+# Funzioni Scope
+x = 5
+
+def set_x(num):
+ # La variabile locale x non è uguale alla variabile globale x
+ x = num # => 43
+ print x # => 43
+
+def set_global_x(num):
+ global x
+ print x # => 5
+ x = num # la variabile globable x è ora 6
+ print x # => 6
+
+set_x(43)
+set_global_x(6)
+
+# Python ha funzioni di prima classe
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# Ci sono anche funzioni anonime
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# Esse sono incluse in funzioni di alto livello
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# Possiamo usare la comprensione delle liste per mappe e filtri
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+# Puoi fare anche la comprensione di set e dizionari
+{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'}
+{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
+
+####################################################
+## 5. Classi
+####################################################
+
+# Usiamo una sottoclasse da un oggetto per avere una classe.
+class Human(object):
+
+ # Un attributo della classe. E' condiviso da tutte le istanze delle classe
+ species = "H. sapiens"
+
+ # Costruttore base, richiamato quando la classe viene inizializzata.
+ # Si noti che il doppio leading e gli underscore finali denotano oggetti
+ # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato
+ # dall'utente. Non dovresti usare nomi di questo genere.
+ def __init__(self, name):
+ # Assegna l'argomento all'attributo name dell'istanza
+ self.name = name
+
+ # Inizializza una proprietà
+ self.age = 0
+
+ # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento
+ def say(self, msg):
+ return "{0}: {1}".format(self.name, msg)
+
+ # Un metodo della classe è condiviso fra tutte le istanze
+ # Sono chiamate con la classe chiamante come primo argomento
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Un metodo statico è chiamato senza una classe od una istanza di riferimento
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # Una proprietà è come un metodo getter.
+ # Trasforma il metodo age() in un attributo in sola lettura, che ha lo stesso nome
+ @property
+ def age(self):
+ return self._age
+
+ # Questo metodo permette di modificare la proprietà
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # Questo metodo permette di cancellare la proprietà
+ @age.deleter
+ def age(self):
+ del self._age
+
+# Instanziare una classe
+i = Human(name="Ian")
+print i.say("hi") # stampa "Ian: hi"
+
+j = Human("Joel")
+print j.say("hello") # stampa "Joel: hello"
+
+# Chiamare metodi della classe
+i.get_species() # => "H. sapiens"
+
+# Cambiare l'attributo condiviso
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# Chiamare il metodo condiviso
+Human.grunt() # => "*grunt*"
+
+# Aggiorna la proprietà
+i.age = 42
+
+# Ritorna il valore della proprietà
+i.age # => 42
+
+# Cancella la proprietà
+del i.age
+i.age # => Emette un AttributeError
+
+
+####################################################
+## 6. Moduli
+####################################################
+
+# Puoi importare moduli
+import math
+print math.sqrt(16) # => 4.0
+
+# Puoi ottenere specifiche funzione da un modulo
+from math import ceil, floor
+print ceil(3.7) # => 4.0
+print floor(3.7) # => 3.0
+
+# Puoi importare tutte le funzioni da un modulo
+# Attenzione: questo non è raccomandato
+from math import *
+
+# Puoi abbreviare i nomi dei moduli
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+# puoi anche verificare che le funzioni sono equivalenti
+from math import sqrt
+math.sqrt == m.sqrt == sqrt # => True
+
+# I moduli di Python sono normali file python. Ne puoi
+# scrivere di tuoi ed importarli. Il nome del modulo
+# è lo stesso del nome del file.
+
+# Potete scoprire quali funzioni e attributi
+# definiscono un modulo
+import math
+dir(math)
+
+# Se nella cartella corrente hai uno script chiamato math.py,
+# Python caricherà quello invece del modulo math.
+# Questo succede perchè la cartella corrente ha priorità
+# sulle librerie standard di Python
+
+
+####################################################
+## 7. Avanzate
+####################################################
+
+# Generatori
+# Un generatore appunto "genera" valori solo quando vengono richiesti,
+# invece di memorizzarli tutti subito fin dall'inizio
+
+# Il metodo seguente (che NON è un generatore) raddoppia tutti i valori e li memorizza
+# dentro `double_arr`. Se gli oggetti iterabili sono grandi, il vettore risultato
+# potrebbe diventare enorme!
+def double_numbers(iterable):
+ double_arr = []
+ for i in iterable:
+ double_arr.append(i + i)
+
+# Eseguendo il seguente codice, noi andiamo a raddoppiare prima tutti i valori, e poi
+# li ritorniamo tutti e andiamo a controllare la condizione
+for value in double_numbers(range(1000000)): # `test_senza_generatore`
+ print value
+ if value > 5:
+ break
+
+# Invece, potremmo usare un generatore per "generare" il valore raddoppiato non
+# appena viene richiesto
+def double_numbers_generator(iterable):
+ for i in iterable:
+ yield i + i
+
+# Utilizzando lo stesso test di prima, stavolta però con un generatore, ci permette
+# di iterare sui valori e raddoppiarli uno alla volta, non appena vengono richiesti dalla
+# logica del programma. Per questo, non appena troviamo un valore > 5, usciamo dal ciclo senza
+# bisogno di raddoppiare la maggior parte dei valori del range (MOLTO PIU VELOCE!)
+for value in double_numbers_generator(xrange(1000000)): # `test_generatore`
+ print value
+ if value > 5:
+ break
+
+# Nota: hai notato l'uso di `range` in `test_senza_generatore` e `xrange` in `test_generatore`?
+# Proprio come `double_numbers_generator` è la versione col generatore di `double_numbers`
+# Abbiamo `xrange` come versione col generatore di `range`
+# `range` ritorna un array di 1000000 elementi
+# `xrange` invece genera 1000000 valori quando lo richiediamo/iteriamo su di essi
+
+# Allo stesso modo della comprensione delle liste, puoi creare la comprensione
+# dei generatori.
+values = (-x for x in [1,2,3,4,5])
+for x in values:
+ print(x) # stampa -1 -2 -3 -4 -5
+
+# Puoi anche fare il cast diretto di una comprensione di generatori ad una lista.
+values = (-x for x in [1,2,3,4,5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
+
+# Decoratori
+# in questo esempio beg include say
+# Beg chiamerà say. Se say_please è True allora cambierà il messaggio
+# ritornato
+from functools import wraps
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Per favore! Sono povero :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Puoi comprarmi una birra?"
+ return msg, say_please
+
+
+print say() # Puoi comprarmi una birra?
+print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :(
+```
+
+## Pronto per qualcosa di più?
+
+### Gratis Online
+
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [LearnPython](http://www.learnpython.org/)
+* [Fullstack Python](https://www.fullstackpython.com/)
+
+### Libri cartacei
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/ja-jp/python3-jp.html.markdown b/ja-jp/python-jp.html.markdown
index b9731411..c80b4d4c 100644
--- a/ja-jp/python3-jp.html.markdown
+++ b/ja-jp/python-jp.html.markdown
@@ -1,5 +1,5 @@
---
-language: python3
+language: Python
contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
- ["Steven Basart", "http://github.com/xksteven"]
@@ -11,7 +11,7 @@ contributors:
translators:
- ["kakakaya", "https://github.com/kakakaya"]
- ["Ryota Kayanuma", "https://github.com/PicoSushi"]
-filename: learnpython3-jp.py
+filename: learnpython-jp.py
lang: ja-jp
---
@@ -21,7 +21,7 @@ lang: ja-jp
フィードバッグは大歓迎です! [@louiedinh](http://twitter.com/louiedinh) または louiedinh [at] [google's email service] にご連絡下さい!
-Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/python/) をご確認下さい。
+Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/pythonlegacy/) をご確認下さい。
```python
# 1行のコメントは番号記号(#)から始まります。
diff --git a/ko-kr/python-kr.html.markdown b/ko-kr/pythonlegacy-kr.html.markdown
index 0145754d..978a9f33 100644
--- a/ko-kr/python-kr.html.markdown
+++ b/ko-kr/pythonlegacy-kr.html.markdown
@@ -1,9 +1,9 @@
---
-language: python
+language: Python 2 (legacy)
category: language
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
-filename: learnpython-ko.py
+filename: learnpythonlegacy-ko.py
translators:
- ["wikibook", "http://wikibook.co.kr"]
lang: ko-kr
diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/pythonlegacy-pl.html.markdown
index 222f753f..9e322658 100644
--- a/pl-pl/python-pl.html.markdown
+++ b/pl-pl/pythonlegacy-pl.html.markdown
@@ -1,8 +1,8 @@
---
name: python
category: language
-language: python
-filename: learnpython-pl.py
+language: Python 2 (legacy)
+filename: learnpythonlegacy-pl.py
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown
index 82b70117..3f9c54c1 100644
--- a/pt-br/python-pt.html.markdown
+++ b/pt-br/python-pt.html.markdown
@@ -1,29 +1,36 @@
---
-language: python
+language: Python
contributors:
- - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
translators:
- - ["Vilson Vieira", "http://automata.cc"]
+ - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"]
+ - ["Monique Baptista", "https://github.com/bfmonique"]
lang: pt-br
filename: learnpython-pt.py
---
-Python foi criado por Guido Van Rossum no começo dos anos 90. Atualmente é uma
-das linguagens de programação mais populares. Eu me apaixonei por Python, por
-sua clareza de sintaxe. É basicamente pseudocódigo executável.
+Python foi criada por Guido Van Rossum nos anos 1990. Ela é atualmente uma
+das linguagens mais populares existentes. Eu me apaixonei por
+Python por sua clareza sintática. É praticamente pseudocódigo executável.
-Comentários serão muito apreciados! Você pode me contactar em
-[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [arroba]
-[serviço de email do google]
+Opniões são muito bem vindas. Você pode encontrar-me em
+[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em]
+[serviço de e-mail do google].
-Nota: Este artigo usa Python 2.7 especificamente, mas deveria ser aplicável a
-qualquer Python 2.x. Logo haverá uma versão abordando Python 3!
+Observação: Este artigo trata de Python 3 especificamente. Verifique
+[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende
+aprender o velho Python 2.7.
```python
-# Comentários de uma linha começam com cerquilha (ou sustenido)
+
+# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido).
+
""" Strings de várias linhas podem ser escritas
usando três ", e são comumente usadas
- como comentários
+ como comentários.
"""
####################################################
@@ -31,287 +38,385 @@ qualquer Python 2.x. Logo haverá uma versão abordando Python 3!
####################################################
# Você usa números normalmente
-3 #=> 3
-
-# Operadores matemáticos são aqueles que você já está acostumado
-1 + 1 #=> 2
-8 - 1 #=> 7
-10 * 2 #=> 20
-35 / 5 #=> 7
-
-# A divisão é um pouco estranha. A divisão de números inteiros arredonda
-# para baixo o resultado, automaticamente
-5 / 2 #=> 2
+3 # => 3
-# Para concertar a divisão, precisamos aprender sobre números de ponto
-# flutuante (conhecidos como 'float').
-2.0 # Isso é um 'float'
-11.0 / 4.0 #=> 2.75 ahhh... muito melhor
+# Matemática é como você espera que seja
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
-# Forçamos a precedência de operadores usando parênteses
-(1 + 3) * 2 #=> 8
+# Números são inteiros por padrão, exceto na divisão, que retorna número
+# de ponto flutuante (float).
+35 / 5 # => 7.0
-# Valores booleanos (ou 'boolean') são também tipos primitivos
-True
-False
+# O resultado da divisão inteira arredonda para baixo tanto para números
+# positivos como para negativos.
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # funciona em float também
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
-# Negamos usando 'not'
-not True #=> False
-not False #=> True
+# Quando você usa um float, o resultado é float.
+3 * 2.0 # => 6.0
-# Testamos igualdade usando '=='
-1 == 1 #=> True
-2 == 1 #=> False
+# operador módulo
+7 % 3 # => 1
-# E desigualdade com '!='
-1 != 1 #=> False
-2 != 1 #=> True
-
-# Mais comparações
-1 < 10 #=> True
-1 > 10 #=> False
-2 <= 2 #=> True
-2 >= 2 #=> True
+# Exponenciação (x**y, x elevado à potência y)
+2**4 # => 16
-# As comparações podem ser encadeadas!
-1 < 2 < 3 #=> True
-2 < 3 < 2 #=> False
+# Determine a precedência usando parênteses
+(1 + 3) * 2 # => 8
-# Strings são criadas com " ou '
-"Isso é uma string."
-'Isso também é uma string.'
+# Valores lógicos são primitivos (Atenção à primeira letra maiúscula)
+True
+False
-# Strings podem ser somadas (ou melhor, concatenadas)!
-"Olá " + "mundo!" #=> "Olá mundo!"
+# negação lógica com not
+not True # => False
+not False # => True
-# Uma string pode ser tratada como uma lista de caracteres
-"Esta é uma string"[0] #=> 'E'
+# Operadores lógicos
+# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas
+True and False # => False
+False or True # => True
-# O caractere % pode ser usado para formatar strings, desta forma:
-"%s podem ser %s" % ("strings", "interpoladas")
+# Observe a utilização de operadores lógicos com números inteiros
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
-# Um jeito novo de formatar strings é usando o método 'format'.
-# Esse método é o jeito mais usado
-"{0} podem ser {1}".format("strings", "formatadas")
-# Você pode usar palavras-chave (ou 'keywords') se você não quiser contar.
-"{nome} quer comer {comida}".format(nome="João", comida="lasanha")
+# Igualdade é ==
+1 == 1 # => True
+2 == 1 # => False
-# 'None' é um objeto
-None #=> None
+# Diferença é !=
+1 != 1 # => False
+2 != 1 # => True
-# Não use o operador de igualdade `==` para comparar objetos com 'None'
-# Ao invés disso, use `is`
-"etc" is None #=> False
-None is None #=> True
+# Mais comparações
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# Comparações podem ser agrupadas
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# 'is' verifica se duas variáveis representam o mesmo endereço
+# na memória; '==' verifica se duas variáveis têm o mesmo valor
+a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4]
+b = a # b referencia o que está referenciado por a
+b is a # => True, a e b referenciam o mesmo objeto
+b == a # => True, objetos a e b tem o mesmo conteúdo
+b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4]
+b is a # => False, a e b não referenciam o mesmo objeto
+b == a # => True, objetos a e b tem o mesmo conteúdo
-# O operador 'is' teste a identidade de um objeto. Isso não é
-# muito útil quando estamos lidando com valores primitivos, mas é
-# muito útil quando lidamos com objetos.
+# Strings são criadas com " ou '
+"Isto é uma string."
+'Isto também é uma string.'
-# None, 0, e strings/listas vazias são todas interpretadas como 'False'.
-# Todos os outros valores são 'True'
-0 == False #=> True
-"" == False #=> True
+# Strings também podem ser somadas! Mas tente não fazer isso.
+"Olá " + "mundo!" # => "Olá mundo!"
+# Strings podem ser somadas sem usar o '+'
+"Olá " "mundo!" # => "Olá mundo!"
+# Uma string pode ser manipulada como se fosse uma lista de caracteres
+"Isso é uma string"[0] # => 'I'
-####################################################
-## 2. Variáveis e Coleções
-####################################################
+# .format pode ser usado para formatar strings, dessa forma:
+"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas"
-# Imprimir na tela é muito fácil
-print "Eu sou o Python. Prazer em te conhecer!"
+# Você pode repetir os argumentos para digitar menos.
+"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal")
+# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack."
+# Você pode usar palavras-chave se quiser contar.
+"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha"
-# Nós não precisamos declarar variáveis antes de usá-las, basta usar!
-alguma_variavel = 5 # A convenção é usar caixa_baixa_com_sobrescritos
-alguma_variavel #=> 5
+# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto:
+"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga"
-# Acessar uma variável que não teve nenhum valor atribuído anteriormente é
-# uma exceção.
-# Veja a seção 'Controle' para aprender mais sobre tratamento de exceção.
-outra_variavel # Gera uma exceção de erro de nome
-# 'if' pode ser usado como uma expressão
-"uepa!" if 3 > 2 else 2 #=> "uepa!"
+# None é um objeto
+None # => None
-# Listas armazenam sequências de elementos
-lista = []
-# Você pode inicializar uma lista com valores
-outra_lista = [4, 5, 6]
+# Não use o operador de igualdade "==" para comparar objetos com None
+# Use "is" para isso. Ele checará pela identidade dos objetos.
+"etc" is None # => False
+None is None # => True
-# Adicione elementos no final da lista usando 'append'
-lista.append(1) # lista é agora [1]
-lista.append(2) # lista é agora [1, 2]
-lista.append(4) # lista é agora [1, 2, 4]
-lista.append(3) # lista é agora [1, 2, 4, 3]
-# Remova elementos do fim da lista usando 'pop'
-lista.pop() #=> 3 e lista é agora [1, 2, 4]
-# Vamos adicionar o elemento novamente
-lista.append(3) # lista agora é [1, 2, 4, 3] novamente.
+# None, 0, e strings/listas/dicionários vazios todos retornam False.
+# Qualquer outra coisa retorna True
+bool(0) # => False
+bool("") # => False
+bool([]) # => False
+bool({}) # => False
-# Acesse elementos de uma lista através de seu índices
-lista[0] #=> 1
-# Acesse o último elemento com índice negativo!
-lista[-1] #=> 3
-# Tentar acessar um elemento fora dos limites da lista gera uma exceção
-# do tipo 'IndexError'
-lista[4] # Gera uma exceção 'IndexError'
-
-# Você pode acessar vários elementos ao mesmo tempo usando a sintaxe de
-# limites
-# (Para quem gosta de matemática, isso é um limite fechado/aberto)
-lista[1:3] #=> [2, 4]
-# Você pode omitir o fim se quiser os elementos até o final da lista
-lista[2:] #=> [4, 3]
-# O mesmo para o início
-lista[:3] #=> [1, 2, 4]
+####################################################
+## 2. Variáveis e coleções
+####################################################
-# Remova um elemento qualquer de uma lista usando 'del'
-del lista[2] # lista agora é [1, 2, 3]
+# Python tem uma função print
+print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer!
+
+# Por padrão a função print também imprime o caractere de nova linha ao final.
+# Use o argumento opcional end para mudar o caractere final.
+print("Olá, Mundo", end="!") # => Olá, Mundo!
+
+# Forma simples para capturar dados de entrada via console
+input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string
+# Observação: Em versões antigas do Python, o método input() era chamado raw_input()
+
+# Não é necessário declarar variáveis antes de iniciá-las
+# É uma convenção usar letras_minúsculas_com_sublinhados
+alguma_variavel = 5
+alguma_variavel # => 5
+
+# Acessar uma variável que não tenha sido inicializada gera uma exceção.
+# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções.
+alguma_variavel_nao_inicializada # Gera a exceção NameError
+
+# Listas armazenam sequências
+li = []
+# Você pode iniciar uma lista com valores
+outra_li = [4, 5, 6]
+
+# Adicione conteúdo ao fim da lista com append
+li.append(1) # li agora é [1]
+li.append(2) # li agora é [1, 2]
+li.append(4) # li agora é [1, 2, 4]
+li.append(3) # li agora é [1, 2, 4, 3]
+# Remova do final da lista com pop
+li.pop() # => 3 e agora li é [1, 2, 4]
+# Vamos colocá-lo lá novamente!
+li.append(3) # li agora é [1, 2, 4, 3] novamente.
+
+# Acesse uma lista da mesma forma que você faz com um array
+li[0] # => 1
+# Acessando o último elemento
+li[-1] # => 3
+
+# Acessar além dos limites gera um IndexError
+li[4] # Gera o IndexError
+
+# Você pode acessar vários elementos com a sintaxe de limites
+# Inclusivo para o primeiro termo, exclusivo para o segundo
+li[1:3] # => [2, 4]
+# Omitindo o final
+li[2:] # => [4, 3]
+# Omitindo o início
+li[:3] # => [1, 2, 4]
+# Selecione cada segunda entrada
+li[::2] # => [1, 4]
+# Tenha uma cópia em ordem invertida da lista
+li[::-1] # => [3, 4, 2, 1]
+# Use qualquer combinação dessas para indicar limites complexos
+# li[inicio:fim:passo]
+
+# Faça uma cópia profunda de um nível usando limites
+li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False.
+
+# Apague elementos específicos da lista com "del"
+del li[2] # li agora é [1, 2, 3]
+
+# Você pode somar listas
+# Observação: valores em li e other_li não são modificados.
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# Concatene listas com "extend()"
+li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6]
+
+# Verifique se algo existe na lista com "in"
+1 in li # => True
+
+# Examine tamanho com "len()"
+len(li) # => 6
+
+
+# Tuplas são como l istas, mas imutáveis.
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # Gera um TypeError
+
+# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do
+# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,.
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
+
+# Você pode realizar com tuplas a maior parte das operações que faz com listas
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Você pode desmembrar tuplas (ou listas) em variáveis.
+a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3
+# Por padrão, tuplas são criadas se você não coloca parêntesis.
+d, e, f = 4, 5, 6
+# Veja como é fácil permutar dois valores
+e, d = d, e # d é 5, e é 4
-# Você pode somar listas (obs: as listas originais não são modificadas)
-lista + outra_lista #=> [1, 2, 3, 4, 5, 6]
+# Dicionários armazenam mapeamentos
+empty_dict = {}
+# Aqui está um dicionário preenchido na definição da referência
+filled_dict = {"um": 1, "dois": 2, "três": 3}
-# Você também pode concatenar usando o método 'extend' (lista será modificada!)
-lista.extend(outra_lista) # Agora lista é [1, 2, 3, 4, 5, 6]
+# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para
+# assegurar que a chave pode ser convertida para uma valor hash constante para
+# buscas rápidas.
+# Tipos imutáveis incluem inteiros, flotas, strings e tuplas.
+invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo.
-# Para checar se um elemento pertence a uma lista, use 'in'
-1 in lista #=> True
+# Acesse valores com []
+filled_dict["um"] # => 1
-# Saiba quantos elementos uma lista possui com 'len'
-len(lista) #=> 6
+# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular
+# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso
+# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida.
+# Por isso, os resultados aqui apresentados podem não ser exatamente como os
+# aqui apresentados.
+list(filled_dict.keys()) # => ["três", "dois", "um"]
-# Tuplas são iguais a listas, mas são imutáveis
-tup = (1, 2, 3)
-tup[0] #=> 1
-tup[0] = 3 # Isso gera uma exceção do tipo TypeError
-
-# Você pode fazer nas tuplas todas aquelas coisas fez com a lista
-len(tup) #=> 3
-tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
-tup[:2] #=> (1, 2)
-2 in tup #=> True
-
-# Você pode 'desempacotar' tuplas (ou listas) em variáveis, associando cada
-# elemento da tupla/lista a uma variável correspondente
-a, b, c = (1, 2, 3) # a agora é 1, b agora é 2, c agora é 3
-# Tuplas são criadas por padrão, mesmo se você não usar parênteses
-d, e, f = 4, 5, 6
-# Sabendo disso, veja só como é fácil trocar os valores de duas variáveis!
-e, d = d, e # d agora é 5, e agora é 4
+# Acesse todos os valores de um iterável com "values()". Novamente, é
+# necessário encapsular ele com list() para não termos um iterável, e sim os
+# valores. Observe que, como foi dito acima, a ordem dos elementos não é
+# garantida.
+list(filled_dict.values()) # => [3, 2, 1]
-# Dicionários armazenam 'mapeamentos' (do tipo chave-valor)
-dicionario_vazio = {}
-# Aqui criamos um dicionário já contendo valores
-dicionario = {"um": 1, "dois": 2, "três": 3}
+# Verifique a existência de chaves em um dicionário com "in"
+"um" in filled_dict # => True
+1 in filled_dict # => False
-# Acesse valores usando []
-dicionario["um"] #=> 1
+# Acessar uma chave inexistente gera um KeyError
+filled_dict["quatro"] # KeyError
-# Retorna uma lista com todas as chaves do dicionário
-dicionario.keys() #=> ["três", "dois", "um"]
-# Nota: A ordem das chaves não é garantida.
-# O resultado no seu interpretador não necessariamente será igual a esse.
+# Use o método "get()" para evitar um KeyError
+filled_dict.get("um") # => 1
+filled_dict.get("quatro") # => None
+# O método get permite um parâmetro padrão para quando não existir a chave
+filled_dict.get("um", 4) # => 1
+filled_dict.get("quatro", 4) # => 4
-# Retorna uma lista com todos os valores do dicionário
-dicionario.values() #=> [3, 2, 1]
-# Nota: A mesma nota acima sobre a ordenação é válida aqui.
+# "setdefault()" insere em dicionário apenas se a dada chave não existir
+filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5
+filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5
-# Veja se uma chave qualquer está em um dicionário usando 'in'
-"um" in dicionario #=> True
-1 in dicionario #=> False
+# Inserindo em um dicionário
+filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4}
+#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário
-# Tentar acessar uma chave que não existe gera uma exceção do tipo 'KeyError'
-dicionario["quatro"] # Gera uma exceção KeyError
+# Remova chaves de um dicionário com del
+del filled_dict["um"] # Remove a chave "um" de filled_dict
-# Você pode usar o método 'get' para evitar gerar a exceção 'KeyError'.
-# Ao invés de gerar essa exceção, irá retornar 'None' se a chave não existir.
-dicionario.get("um") #=> 1
-dicionario.get("quatro") #=> None
-# O método 'get' suporta um argumento que diz qual valor deverá ser
-# retornado se a chave não existir (ao invés de 'None').
-dicionario.get("um", 4) #=> 1
-dicionario.get("quatro", 4) #=> 4
-# O método 'setdefault' é um jeito seguro de adicionar um novo par
-# chave-valor a um dicionário, associando um valor padrão imutável à uma chave
-dicionario.setdefault("cinco", 5) # dicionario["cinco"] é definido como 5
-dicionario.setdefault("cinco", 6) # dicionario["cinco"] ainda é igual a 5
+# Armazenamento em sets... bem, são conjuntos
+empty_set = set()
+# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe.
+some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4}
+# Da mesma forma que chaves em um dicionário, elementos de um set devem ser
+# imutáveis.
+invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
-# Conjuntos (ou sets) armazenam ... bem, conjuntos
-# Nota: lembre-se que conjuntos não admitem elementos repetidos!
-conjunto_vazio = set()
-# Podemos inicializar um conjunto com valores
-conjunto = set([1, 2, 2, 3, 4]) # conjunto é set([1, 2, 3, 4]), sem repetição!
+# Pode definir novas variáveis para um conjunto
+filled_set = some_set
-# Desde o Python 2.7, {} pode ser usado para declarar um conjunto
-conjunto = {1, 2, 2, 3, 4} # => {1 2 3 4}
+# Inclua mais um item no set
+filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5}
-# Adicione mais ítens a um conjunto com 'add'
-conjunto.add(5) # conjunto agora é {1, 2, 3, 4, 5}
+# Faça interseção de conjuntos com &
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
-# Calcule a intersecção de dois conjuntos com &
-outro_conj = {3, 4, 5, 6}
-conjunto & outro_conj #=> {3, 4, 5}
+# Faça união de conjuntos com |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-# Calcule a união de dois conjuntos com |
-conjunto | outro_conj #=> {1, 2, 3, 4, 5, 6}
+# Faça a diferença entre conjuntos com -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
-# E a diferença entre dois conjuntos com -
-{1,2,3,4} - {2,3,5} #=> {1, 4}
+# Verifique a existência em um conjunto com in
+2 in filled_set # => True
+10 in filled_set # => False
-# Veja se um elemento existe em um conjunto usando 'in'
-2 in conjunto #=> True
-10 in conjunto #=> False
####################################################
-## 3. Controle
+## 3. Controle de fluxo e iteráveis
####################################################
-# Para começar, vamos apenas criar uma variável
-alguma_var = 5
+# Iniciemos um variável
+some_var = 5
-# Aqui está uma expressão 'if'. Veja como a identação é importante em Python!
-# Esses comandos irão imprimir "alguma_var é menor que 10"
-if alguma_var > 10:
- print "some_var é maior que 10."
-elif some_var < 10: # Esse 'elif' é opcional
- print "some_var é menor que 10."
-else: # Esse 'else' também é opcional
- print "some_var é igual a 10."
+# Aqui está uma expressão if. Indentação é significante em python!
+# imprime "somevar é menor que10"
+if some_var > 10:
+ print("some_var é absolutamente maior que 10.")
+elif some_var < 10: # Esta cláusula elif é opcional.
+ print("some_var é menor que 10.")
+else: # Isto também é opcional.
+ print("some_var é, de fato, 10.")
"""
-Laços (ou loops) 'for' iteram em listas.
-Irá imprimir:
+Laços for iteram sobre listas
+imprime:
cachorro é um mamífero
gato é um mamífero
rato é um mamífero
"""
for animal in ["cachorro", "gato", "rato"]:
- # Você pode usar % para interpolar strings formatadas
- print "%s é um mamífero" % animal
-
+ # Você pode usar format() para interpolar strings formatadas
+ print("{} é um mamífero".format(animal))
+
"""
-A função `range(um número)` retorna uma lista de números
-do zero até o número dado.
-Irá imprimir:
+"range(número)" retorna um iterável de números
+de zero até o número escolhido
+imprime:
0
1
2
3
"""
for i in range(4):
- print i
+ print(i)
+
+"""
+"range(menor, maior)" gera um iterável de números
+começando pelo menor até o maior
+imprime:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
"""
-Laços 'while' executam enquanto uma condição dada for verdadeira.
-Irá imprimir:
+"range(menor, maior, passo)" retorna um iterável de números
+começando pelo menor número até o maior númeno, pulando de
+passo em passo. Se o passo não for indicado, o valor padrão é um.
+imprime:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+"""
+
+Laços while executam até que a condição não seja mais válida.
+imprime:
0
1
2
@@ -319,143 +424,221 @@ Irá imprimir:
"""
x = 0
while x < 4:
- print x
- x += 1 # Isso é um atalho para a expressão x = x + 1
-
-# Tratamos excessões usando o bloco try/except
-# Funciona em Python 2.6 e versões superiores:
+ print(x)
+ x += 1 # Maneira mais curta para for x = x + 1
+# Lide com exceções com um bloco try/except
try:
- # Use 'raise' para gerar um erro
- raise IndexError("Isso é um erro de índice")
+ # Use "raise" para gerar um erro
+ raise IndexError("Isto é um erro de índice")
except IndexError as e:
- pass # Pass é um operador que não faz nada, deixa passar.
- # Usualmente você iria tratar a exceção aqui...
+ pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui.
+except (TypeError, NameError):
+ pass # Varias exceções podem ser gerenciadas, se necessário.
+else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção.
+ print("Tudo certo!") # Executa apenas se o código em try não gera exceção
+finally: # Sempre é executado
+ print("Nós podemos fazer o código de limpeza aqui.")
+
+# Ao invés de try/finally para limpeza você pode usar a cláusula with
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# Python provê uma abstração fundamental chamada Iterável.
+# Um iterável é um objeto que pode ser tratado como uma sequência.
+# O objeto retornou a função range, um iterável.
+
+filled_dict = {"um": 1, "dois": 2, "três": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável.
+
+# Nós podemos percorrê-la.
+for i in our_iterable:
+ print(i) # Imprime um, dois, três
+
+# Mas não podemos acessar os elementos pelo seu índice.
+our_iterable[1] # Gera um TypeError
+
+# Um iterável é um objeto que sabe como criar um iterador.
+our_iterator = iter(our_iterable)
+
+# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos.
+# Nós acessamos o próximo objeto com "next()".
+next(our_iterator) # => "um"
+
+# Ele mantém o estado enquanto nós o percorremos.
+next(our_iterator) # => "dois"
+next(our_iterator) # => "três"
+
+# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator
+next(our_iterator) # Gera StopIteration
+
+# Você pode capturar todos os elementos de um iterador aplicando list() nele.
+list(filled_dict.keys()) # => Retorna ["um", "dois", "três"]
####################################################
## 4. Funções
####################################################
-# Use 'def' para definir novas funções
-def soma(x, y):
- print "x é %s e y é %s" % (x, y)
- return x + y # Retorne valores usando 'return'
+# Use "def" para criar novas funções.
+def add(x, y):
+ print("x é {} e y é {}".format(x, y))
+ return x + y # Retorne valores com a cláusula return
# Chamando funções com parâmetros
-soma(5, 6) #=> imprime "x é 5 e y é 6" e retorna o valor 11
+add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11
-# Um outro jeito de chamar funções é especificando explicitamente os valores
-# de cada parâmetro com chaves
-soma(y=6, x=5) # Argumentos com chaves podem vir em qualquer ordem.
+# Outro meio de chamar funções é com argumentos nomeados
+add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem.
-# Você pode definir funções que recebem um número qualquer de argumentos
-# (respeitando a sua ordem)
+# Você pode definir funções que pegam um número variável de argumentos
+# posicionais
def varargs(*args):
return args
-varargs(1, 2, 3) #=> (1,2,3)
+varargs(1, 2, 3) # => (1, 2, 3)
+# Você pode definir funções que pegam um número variável de argumentos nomeados
+# também
+def keyword_args(**kwargs):
+ return kwargs
-# Você também pode definir funções que recebem um número qualquer de argumentos
-# com chaves
-def args_com_chaves(**ch_args):
- return ch_args
+# Vamos chamá-lo para ver o que acontece
+keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"}
-# Vamos chamar essa função para ver o que acontece
-args_com_chaves(pe="grande", lago="Ness") #=> {"pe": "grande", "lago": "Ness"}
-# Você pode fazer as duas coisas ao mesmo tempo, se desejar
-def todos_args(*args, **ch_wargs):
- print args
- print ch_args
+# Você pode fazer ambos simultaneamente, se você quiser
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
"""
-todos_args(1, 2, a=3, b=4) imprime:
+all_the_args(1, 2, a=3, b=4) imprime:
(1, 2)
{"a": 3, "b": 4}
"""
-# Quando você chamar funções, pode fazer o oposto do que fizemos até agora!
-# Podemos usar * para expandir tuplas de argumentos e ** para expandir
-# dicionários de argumentos com chave.
+# Quando chamar funções, você pode fazer o oposto de args/kwargs!
+# Use * para expandir tuplas e use ** para expandir dicionários!
args = (1, 2, 3, 4)
-ch_args = {"a": 3, "b": 4}
-todos_args(*args) # equivalente a todos_args(1, 2, 3, 4)
-todos_args(**ch_args) # equivalente a todos_args(a=3, b=4)
-todos_args(*args, **ch_args) # equivalente a todos_args(1, 2, 3, 4, a=3, b=4)
-
-# Em Python, funções são elementos de primeira ordem (são como objetos,
-# strings ou números)
-def cria_somador(x):
- def somador(y):
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
+
+# Retornando múltiplos valores (com atribuição de tuplas)
+def swap(x, y):
+ return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis.
+ # (Observação: os parêntesis foram excluídos mas podem estar
+ # presentes)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes.
+
+# Escopo de função
+x = 5
+
+def setX(num):
+ # A variável local x não é a mesma variável global x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # variável global x agora é 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
+# Python tem funções de primeira classe
+def create_adder(x):
+ def adder(y):
return x + y
- return somador
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
-soma_10 = cria_somador(10)
-soma_10(3) #=> 13
+# Também existem as funções anônimas
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
-# Desta forma, existem também funções anônimas
-(lambda x: x > 2)(3) #=> True
+# TODO - Fix for iterables
+# Existem funções internas de alta ordem
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
-# E existem funções de alta ordem por padrão
-map(soma_10, [1,2,3]) #=> [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
-reduce(lambda x, y: x + y, [3, 4, 5, 6, 7]) #=> 25
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-# Nós podemos usar compreensão de listas para mapear e filtrar também
-[soma_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+# Nós podemos usar compreensão de lista para interessantes mapas e filtros
+# Compreensão de lista armazena a saída como uma lista que pode ser uma lista
+# aninhada
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Classes
####################################################
-# Para criar uma nova classe, devemos herdar de 'object'
-class Humano(object):
- # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa
- # classe
- especie = "H. sapiens"
-
- # Definimos um inicializador básico
- def __init__(self, nome):
- # Atribui o valor de argumento dado a um atributo da instância
- self.nome = nome
+# Nós usamos o operador "class" para ter uma classe
+class Human:
- # Um método de instância. Todos os métodos levam 'self' como primeiro
+ # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa
+ # classe.
+ species = "H. sapiens"
+
+ # Construtor básico, é chamado quando esta classe é instanciada.
+ # Note que dois sublinhados no início e no final de uma identificados
+ # significa objetos ou atributos que são usados pelo python mas vivem em
+ # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos)
+ # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou
+ # algumas vezes chamados métodos dunder - "double underscore")
+ # Você não deve usar nomes assim por sua vontade.
+ def __init__(self, name):
+ @ Atribui o argumento ao atributo da instância
+ self.name = name
+
+ # Um método de instância. Todos os métodos tem "self" como primeiro
# argumento
- def diga(self, msg):
- return "%s: %s" % (self.nome, msg)
+ def say(self, msg):
+ return "{name}: {message}".format(name=self.name, message=msg)
# Um método de classe é compartilhado por todas as instâncias
- # Eles são chamados passando o nome da classe como primeiro argumento
+ # Eles são chamados com a classe requisitante como primeiro argumento
@classmethod
- def get_especie(cls):
- return cls.especie
+ def get_species(cls):
+ return cls.species
# Um método estático é chamado sem uma referência a classe ou instância
@staticmethod
- def ronca():
- return "*arrrrrrr*"
+ def grunt():
+ return "*grunt*"
# Instancie uma classe
-i = Humano(nome="Ivone")
-print i.diga("oi") # imprime "Ivone: oi"
+i = Human(name="Ian")
+print(i.say("oi")) # imprime "Ian: oi"
j = Human("Joel")
-print j.say("olá") #prints out "Joel: olá"
+print(j.say("olá")) # imprime "Joel: olá"
-# Chame nosso método de classe
-i.get_especie() #=> "H. sapiens"
+# Chama nosso método de classe
+i.get_species() # => "H. sapiens"
-# Modifique um atributo compartilhado
-Humano.especie = "H. neanderthalensis"
-i.get_especie() #=> "H. neanderthalensis"
-j.get_especie() #=> "H. neanderthalensis"
+# Altera um atributo compartilhado
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
-# Chame o método estático
-Humano.ronca() #=> "*arrrrrrr*"
+# Chama o método estático
+Human.grunt() # => "*grunt*"
####################################################
@@ -464,46 +647,100 @@ Humano.ronca() #=> "*arrrrrrr*"
# Você pode importar módulos
import math
-print math.sqrt(16) #=> 4.0
+print(math.sqrt(16)) # => 4.0
-# Você pode importar funções específicas de um módulo
+# Você pode importar apenas funções específicas de um módulo
from math import ceil, floor
-print ceil(3.7) #=> 4.0
-print floor(3.7) #=> 3.0
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
-# Você também pode importar todas as funções de um módulo
-# Atenção: isso não é recomendado!
+# Você pode importar todas as funções de um módulo para o namespace atual
+# Atenção: isso não é recomendado
from math import *
-# Você pode usar apelidos para os módulos, encurtando seus nomes
+# Você pode encurtar o nome dos módulos
import math as m
-math.sqrt(16) == m.sqrt(16) #=> True
+math.sqrt(16) == m.sqrt(16) # => True
-# Módulos em Python são apenas arquivos Python. Você
-# pode escrever o seu próprio módulo e importá-lo. O nome do
-# módulo será o mesmo que o nome do arquivo.
+# Módulos python são apenas arquivos python comuns. Você
+# pode escrever os seus, e importá-los. O nome do
+# módulo é o mesmo nome do arquivo.
-# Você pode descobrir quais funções e atributos
-# estão definidos em um módulo qualquer.
+# Você pode procurar que atributos e funções definem um módulo.
import math
dir(math)
+####################################################
+## 7. Avançado
+####################################################
+
+# Geradores podem ajudar você a escrever código "preguiçoso"
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Um gerador cria valores conforme necessário.
+# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em
+# cada interação. Isto significa que valores maiores que 15 não serão
+# processados em double_numbers.
+# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar
+# um nome que normalmente colide com uma palavra reservada do python.
+range_ = range(1, 900000000)
+# Multiplica por 2 todos os números até encontrar um resultado >= 30
+for i in double_numbers(range_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# Decoradores
+# Neste exemplo beg encapsula say
+# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem
+# retornada
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Por favor! Eu sou pobre :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Você me paga uma cerveja?"
+ return msg, say_please
+
+
+print(say()) # Você me paga uma cerveja?
+print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :(
```
## Pronto para mais?
-### Online e gratuito
+### Free Online
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2.6/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [Python Course](http://www.python-course.eu/index.php)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
-### Livros impressos
+### Dead Tree
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
-
diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown
deleted file mode 100644
index bc5f801c..00000000
--- a/pt-br/python3-pt.html.markdown
+++ /dev/null
@@ -1,746 +0,0 @@
----
-language: python3
-contributors:
- - ["Louie Dinh", "http://pythonpracticeprojects.com"]
- - ["Steven Basart", "http://github.com/xksteven"]
- - ["Andre Polykanine", "https://github.com/Oire"]
- - ["Zachary Ferguson", "http://github.com/zfergus2"]
-translators:
- - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"]
- - ["Monique Baptista", "https://github.com/bfmonique"]
-lang: pt-br
-filename: learnpython3-pt.py
----
-
-Python foi criada por Guido Van Rossum nos anos 1990. Ela é atualmente uma
-das linguagens mais populares existentes. Eu me apaixonei por
-Python por sua clareza sintática. É praticamente pseudocódigo executável.
-
-Opniões são muito bem vindas. Você pode encontrar-me em
-[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em]
-[serviço de e-mail do google].
-
-Observação: Este artigo trata de Python 3 especificamente. Verifique
-[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende
-aprender o velho Python 2.7.
-
-```python
-
-# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido).
-
-""" Strings de várias linhas podem ser escritas
- usando três ", e são comumente usadas
- como comentários.
-"""
-
-####################################################
-## 1. Tipos de dados primitivos e operadores
-####################################################
-
-# Você usa números normalmente
-3 # => 3
-
-# Matemática é como você espera que seja
-1 + 1 # => 2
-8 - 1 # => 7
-10 * 2 # => 20
-
-# Números são inteiros por padrão, exceto na divisão, que retorna número
-# de ponto flutuante (float).
-35 / 5 # => 7.0
-
-# O resultado da divisão inteira arredonda para baixo tanto para números
-# positivos como para negativos.
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # funciona em float também
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
-
-# Quando você usa um float, o resultado é float.
-3 * 2.0 # => 6.0
-
-# operador módulo
-7 % 3 # => 1
-
-# Exponenciação (x**y, x elevado à potência y)
-2**4 # => 16
-
-# Determine a precedência usando parênteses
-(1 + 3) * 2 # => 8
-
-# Valores lógicos são primitivos (Atenção à primeira letra maiúscula)
-True
-False
-
-# negação lógica com not
-not True # => False
-not False # => True
-
-# Operadores lógicos
-# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas
-True and False # => False
-False or True # => True
-
-# Observe a utilização de operadores lógicos com números inteiros
-0 and 2 # => 0
--5 or 0 # => -5
-0 == False # => True
-2 == True # => False
-1 == True # => True
-
-# Igualdade é ==
-1 == 1 # => True
-2 == 1 # => False
-
-# Diferença é !=
-1 != 1 # => False
-2 != 1 # => True
-
-# Mais comparações
-1 < 10 # => True
-1 > 10 # => False
-2 <= 2 # => True
-2 >= 2 # => True
-
-# Comparações podem ser agrupadas
-1 < 2 < 3 # => True
-2 < 3 < 2 # => False
-
-# 'is' verifica se duas variáveis representam o mesmo endereço
-# na memória; '==' verifica se duas variáveis têm o mesmo valor
-a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4]
-b = a # b referencia o que está referenciado por a
-b is a # => True, a e b referenciam o mesmo objeto
-b == a # => True, objetos a e b tem o mesmo conteúdo
-b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4]
-b is a # => False, a e b não referenciam o mesmo objeto
-b == a # => True, objetos a e b tem o mesmo conteúdo
-
-# Strings são criadas com " ou '
-"Isto é uma string."
-'Isto também é uma string.'
-
-# Strings também podem ser somadas! Mas tente não fazer isso.
-"Olá " + "mundo!" # => "Olá mundo!"
-# Strings podem ser somadas sem usar o '+'
-"Olá " "mundo!" # => "Olá mundo!"
-
-# Uma string pode ser manipulada como se fosse uma lista de caracteres
-"Isso é uma string"[0] # => 'I'
-
-# .format pode ser usado para formatar strings, dessa forma:
-"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas"
-
-# Você pode repetir os argumentos para digitar menos.
-"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal")
-# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack."
-
-# Você pode usar palavras-chave se quiser contar.
-"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha"
-
-# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto:
-"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga"
-
-
-# None é um objeto
-None # => None
-
-# Não use o operador de igualdade "==" para comparar objetos com None
-# Use "is" para isso. Ele checará pela identidade dos objetos.
-"etc" is None # => False
-None is None # => True
-
-# None, 0, e strings/listas/dicionários vazios todos retornam False.
-# Qualquer outra coisa retorna True
-bool(0) # => False
-bool("") # => False
-bool([]) # => False
-bool({}) # => False
-
-
-####################################################
-## 2. Variáveis e coleções
-####################################################
-
-# Python tem uma função print
-print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer!
-
-# Por padrão a função print também imprime o caractere de nova linha ao final.
-# Use o argumento opcional end para mudar o caractere final.
-print("Olá, Mundo", end="!") # => Olá, Mundo!
-
-# Forma simples para capturar dados de entrada via console
-input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string
-# Observação: Em versões antigas do Python, o método input() era chamado raw_input()
-
-# Não é necessário declarar variáveis antes de iniciá-las
-# É uma convenção usar letras_minúsculas_com_sublinhados
-alguma_variavel = 5
-alguma_variavel # => 5
-
-# Acessar uma variável que não tenha sido inicializada gera uma exceção.
-# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções.
-alguma_variavel_nao_inicializada # Gera a exceção NameError
-
-# Listas armazenam sequências
-li = []
-# Você pode iniciar uma lista com valores
-outra_li = [4, 5, 6]
-
-# Adicione conteúdo ao fim da lista com append
-li.append(1) # li agora é [1]
-li.append(2) # li agora é [1, 2]
-li.append(4) # li agora é [1, 2, 4]
-li.append(3) # li agora é [1, 2, 4, 3]
-# Remova do final da lista com pop
-li.pop() # => 3 e agora li é [1, 2, 4]
-# Vamos colocá-lo lá novamente!
-li.append(3) # li agora é [1, 2, 4, 3] novamente.
-
-# Acesse uma lista da mesma forma que você faz com um array
-li[0] # => 1
-# Acessando o último elemento
-li[-1] # => 3
-
-# Acessar além dos limites gera um IndexError
-li[4] # Gera o IndexError
-
-# Você pode acessar vários elementos com a sintaxe de limites
-# Inclusivo para o primeiro termo, exclusivo para o segundo
-li[1:3] # => [2, 4]
-# Omitindo o final
-li[2:] # => [4, 3]
-# Omitindo o início
-li[:3] # => [1, 2, 4]
-# Selecione cada segunda entrada
-li[::2] # => [1, 4]
-# Tenha uma cópia em ordem invertida da lista
-li[::-1] # => [3, 4, 2, 1]
-# Use qualquer combinação dessas para indicar limites complexos
-# li[inicio:fim:passo]
-
-# Faça uma cópia profunda de um nível usando limites
-li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False.
-
-# Apague elementos específicos da lista com "del"
-del li[2] # li agora é [1, 2, 3]
-
-# Você pode somar listas
-# Observação: valores em li e other_li não são modificados.
-li + other_li # => [1, 2, 3, 4, 5, 6]
-
-# Concatene listas com "extend()"
-li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6]
-
-# Verifique se algo existe na lista com "in"
-1 in li # => True
-
-# Examine tamanho com "len()"
-len(li) # => 6
-
-
-# Tuplas são como l istas, mas imutáveis.
-tup = (1, 2, 3)
-tup[0] # => 1
-tup[0] = 3 # Gera um TypeError
-
-# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do
-# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,.
-type((1)) # => <class 'int'>
-type((1,)) # => <class 'tuple'>
-type(()) # => <class 'tuple'>
-
-# Você pode realizar com tuplas a maior parte das operações que faz com listas
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
-
-# Você pode desmembrar tuplas (ou listas) em variáveis.
-a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3
-# Por padrão, tuplas são criadas se você não coloca parêntesis.
-d, e, f = 4, 5, 6
-# Veja como é fácil permutar dois valores
-e, d = d, e # d é 5, e é 4
-
-# Dicionários armazenam mapeamentos
-empty_dict = {}
-# Aqui está um dicionário preenchido na definição da referência
-filled_dict = {"um": 1, "dois": 2, "três": 3}
-
-# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para
-# assegurar que a chave pode ser convertida para uma valor hash constante para
-# buscas rápidas.
-# Tipos imutáveis incluem inteiros, flotas, strings e tuplas.
-invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list'
-valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo.
-
-# Acesse valores com []
-filled_dict["um"] # => 1
-
-# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular
-# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso
-# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida.
-# Por isso, os resultados aqui apresentados podem não ser exatamente como os
-# aqui apresentados.
-list(filled_dict.keys()) # => ["três", "dois", "um"]
-
-
-# Acesse todos os valores de um iterável com "values()". Novamente, é
-# necessário encapsular ele com list() para não termos um iterável, e sim os
-# valores. Observe que, como foi dito acima, a ordem dos elementos não é
-# garantida.
-list(filled_dict.values()) # => [3, 2, 1]
-
-
-# Verifique a existência de chaves em um dicionário com "in"
-"um" in filled_dict # => True
-1 in filled_dict # => False
-
-# Acessar uma chave inexistente gera um KeyError
-filled_dict["quatro"] # KeyError
-
-# Use o método "get()" para evitar um KeyError
-filled_dict.get("um") # => 1
-filled_dict.get("quatro") # => None
-# O método get permite um parâmetro padrão para quando não existir a chave
-filled_dict.get("um", 4) # => 1
-filled_dict.get("quatro", 4) # => 4
-
-# "setdefault()" insere em dicionário apenas se a dada chave não existir
-filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5
-filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5
-
-# Inserindo em um dicionário
-filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4}
-#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário
-
-# Remova chaves de um dicionário com del
-del filled_dict["um"] # Remove a chave "um" de filled_dict
-
-
-# Armazenamento em sets... bem, são conjuntos
-empty_set = set()
-# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe.
-some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4}
-
-# Da mesma forma que chaves em um dicionário, elementos de um set devem ser
-# imutáveis.
-invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list'
-valid_set = {(1,), 1}
-
-# Pode definir novas variáveis para um conjunto
-filled_set = some_set
-
-# Inclua mais um item no set
-filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5}
-
-# Faça interseção de conjuntos com &
-other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
-
-# Faça união de conjuntos com |
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-
-# Faça a diferença entre conjuntos com -
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
-
-# Verifique a existência em um conjunto com in
-2 in filled_set # => True
-10 in filled_set # => False
-
-
-
-####################################################
-## 3. Controle de fluxo e iteráveis
-####################################################
-
-# Iniciemos um variável
-some_var = 5
-
-# Aqui está uma expressão if. Indentação é significante em python!
-# imprime "somevar é menor que10"
-if some_var > 10:
- print("some_var é absolutamente maior que 10.")
-elif some_var < 10: # Esta cláusula elif é opcional.
- print("some_var é menor que 10.")
-else: # Isto também é opcional.
- print("some_var é, de fato, 10.")
-
-
-"""
-Laços for iteram sobre listas
-imprime:
- cachorro é um mamífero
- gato é um mamífero
- rato é um mamífero
-"""
-for animal in ["cachorro", "gato", "rato"]:
- # Você pode usar format() para interpolar strings formatadas
- print("{} é um mamífero".format(animal))
-
-"""
-"range(número)" retorna um iterável de números
-de zero até o número escolhido
-imprime:
- 0
- 1
- 2
- 3
-"""
-for i in range(4):
- print(i)
-
-"""
-"range(menor, maior)" gera um iterável de números
-começando pelo menor até o maior
-imprime:
- 4
- 5
- 6
- 7
-"""
-for i in range(4, 8):
- print(i)
-
-"""
-"range(menor, maior, passo)" retorna um iterável de números
-começando pelo menor número até o maior númeno, pulando de
-passo em passo. Se o passo não for indicado, o valor padrão é um.
-imprime:
- 4
- 6
-"""
-for i in range(4, 8, 2):
- print(i)
-"""
-
-Laços while executam até que a condição não seja mais válida.
-imprime:
- 0
- 1
- 2
- 3
-"""
-x = 0
-while x < 4:
- print(x)
- x += 1 # Maneira mais curta para for x = x + 1
-
-# Lide com exceções com um bloco try/except
-try:
- # Use "raise" para gerar um erro
- raise IndexError("Isto é um erro de índice")
-except IndexError as e:
- pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui.
-except (TypeError, NameError):
- pass # Varias exceções podem ser gerenciadas, se necessário.
-else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção.
- print("Tudo certo!") # Executa apenas se o código em try não gera exceção
-finally: # Sempre é executado
- print("Nós podemos fazer o código de limpeza aqui.")
-
-# Ao invés de try/finally para limpeza você pode usar a cláusula with
-with open("myfile.txt") as f:
- for line in f:
- print(line)
-
-# Python provê uma abstração fundamental chamada Iterável.
-# Um iterável é um objeto que pode ser tratado como uma sequência.
-# O objeto retornou a função range, um iterável.
-
-filled_dict = {"um": 1, "dois": 2, "três": 3}
-our_iterable = filled_dict.keys()
-print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável.
-
-# Nós podemos percorrê-la.
-for i in our_iterable:
- print(i) # Imprime um, dois, três
-
-# Mas não podemos acessar os elementos pelo seu índice.
-our_iterable[1] # Gera um TypeError
-
-# Um iterável é um objeto que sabe como criar um iterador.
-our_iterator = iter(our_iterable)
-
-# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos.
-# Nós acessamos o próximo objeto com "next()".
-next(our_iterator) # => "um"
-
-# Ele mantém o estado enquanto nós o percorremos.
-next(our_iterator) # => "dois"
-next(our_iterator) # => "três"
-
-# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator
-next(our_iterator) # Gera StopIteration
-
-# Você pode capturar todos os elementos de um iterador aplicando list() nele.
-list(filled_dict.keys()) # => Retorna ["um", "dois", "três"]
-
-
-####################################################
-## 4. Funções
-####################################################
-
-# Use "def" para criar novas funções.
-def add(x, y):
- print("x é {} e y é {}".format(x, y))
- return x + y # Retorne valores com a cláusula return
-
-# Chamando funções com parâmetros
-add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11
-
-# Outro meio de chamar funções é com argumentos nomeados
-add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem.
-
-# Você pode definir funções que pegam um número variável de argumentos
-# posicionais
-def varargs(*args):
- return args
-
-varargs(1, 2, 3) # => (1, 2, 3)
-
-# Você pode definir funções que pegam um número variável de argumentos nomeados
-# também
-def keyword_args(**kwargs):
- return kwargs
-
-# Vamos chamá-lo para ver o que acontece
-keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"}
-
-
-# Você pode fazer ambos simultaneamente, se você quiser
-def all_the_args(*args, **kwargs):
- print(args)
- print(kwargs)
-"""
-all_the_args(1, 2, a=3, b=4) imprime:
- (1, 2)
- {"a": 3, "b": 4}
-"""
-
-# Quando chamar funções, você pode fazer o oposto de args/kwargs!
-# Use * para expandir tuplas e use ** para expandir dicionários!
-args = (1, 2, 3, 4)
-kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
-all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
-
-# Retornando múltiplos valores (com atribuição de tuplas)
-def swap(x, y):
- return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis.
- # (Observação: os parêntesis foram excluídos mas podem estar
- # presentes)
-
-x = 1
-y = 2
-x, y = swap(x, y) # => x = 2, y = 1
-# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes.
-
-# Escopo de função
-x = 5
-
-def setX(num):
- # A variável local x não é a mesma variável global x
- x = num # => 43
- print (x) # => 43
-
-def setGlobalX(num):
- global x
- print (x) # => 5
- x = num # variável global x agora é 6
- print (x) # => 6
-
-setX(43)
-setGlobalX(6)
-
-
-# Python tem funções de primeira classe
-def create_adder(x):
- def adder(y):
- return x + y
- return adder
-
-add_10 = create_adder(10)
-add_10(3) # => 13
-
-# Também existem as funções anônimas
-(lambda x: x > 2)(3) # => True
-(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
-
-# TODO - Fix for iterables
-# Existem funções internas de alta ordem
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
-
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-
-# Nós podemos usar compreensão de lista para interessantes mapas e filtros
-# Compreensão de lista armazena a saída como uma lista que pode ser uma lista
-# aninhada
-[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
-
-####################################################
-## 5. Classes
-####################################################
-
-
-# Nós usamos o operador "class" para ter uma classe
-class Human:
-
- # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa
- # classe.
- species = "H. sapiens"
-
- # Construtor básico, é chamado quando esta classe é instanciada.
- # Note que dois sublinhados no início e no final de uma identificados
- # significa objetos ou atributos que são usados pelo python mas vivem em
- # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos)
- # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou
- # algumas vezes chamados métodos dunder - "double underscore")
- # Você não deve usar nomes assim por sua vontade.
- def __init__(self, name):
- @ Atribui o argumento ao atributo da instância
- self.name = name
-
- # Um método de instância. Todos os métodos tem "self" como primeiro
- # argumento
- def say(self, msg):
- return "{name}: {message}".format(name=self.name, message=msg)
-
- # Um método de classe é compartilhado por todas as instâncias
- # Eles são chamados com a classe requisitante como primeiro argumento
- @classmethod
- def get_species(cls):
- return cls.species
-
- # Um método estático é chamado sem uma referência a classe ou instância
- @staticmethod
- def grunt():
- return "*grunt*"
-
-
-# Instancie uma classe
-i = Human(name="Ian")
-print(i.say("oi")) # imprime "Ian: oi"
-
-j = Human("Joel")
-print(j.say("olá")) # imprime "Joel: olá"
-
-# Chama nosso método de classe
-i.get_species() # => "H. sapiens"
-
-# Altera um atributo compartilhado
-Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
-
-# Chama o método estático
-Human.grunt() # => "*grunt*"
-
-
-####################################################
-## 6. Módulos
-####################################################
-
-# Você pode importar módulos
-import math
-print(math.sqrt(16)) # => 4.0
-
-# Você pode importar apenas funções específicas de um módulo
-from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
-
-# Você pode importar todas as funções de um módulo para o namespace atual
-# Atenção: isso não é recomendado
-from math import *
-
-# Você pode encurtar o nome dos módulos
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
-
-# Módulos python são apenas arquivos python comuns. Você
-# pode escrever os seus, e importá-los. O nome do
-# módulo é o mesmo nome do arquivo.
-
-# Você pode procurar que atributos e funções definem um módulo.
-import math
-dir(math)
-
-
-####################################################
-## 7. Avançado
-####################################################
-
-# Geradores podem ajudar você a escrever código "preguiçoso"
-def double_numbers(iterable):
- for i in iterable:
- yield i + i
-
-# Um gerador cria valores conforme necessário.
-# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em
-# cada interação. Isto significa que valores maiores que 15 não serão
-# processados em double_numbers.
-# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar
-# um nome que normalmente colide com uma palavra reservada do python.
-range_ = range(1, 900000000)
-# Multiplica por 2 todos os números até encontrar um resultado >= 30
-for i in double_numbers(range_):
- print(i)
- if i >= 30:
- break
-
-
-# Decoradores
-# Neste exemplo beg encapsula say
-# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem
-# retornada
-from functools import wraps
-
-
-def beg(target_function):
- @wraps(target_function)
- def wrapper(*args, **kwargs):
- msg, say_please = target_function(*args, **kwargs)
- if say_please:
- return "{} {}".format(msg, "Por favor! Eu sou pobre :(")
- return msg
-
- return wrapper
-
-
-@beg
-def say(say_please=False):
- msg = "Você me paga uma cerveja?"
- return msg, say_please
-
-
-print(say()) # Você me paga uma cerveja?
-print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :(
-```
-
-## Pronto para mais?
-
-### Free Online
-
-* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
-* [Python Course](http://www.python-course.eu/index.php)
-* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
-* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
-* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
-* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
-
-### Dead Tree
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/pt-br/pythonlegacy-pt.html.markdown b/pt-br/pythonlegacy-pt.html.markdown
new file mode 100644
index 00000000..572bb787
--- /dev/null
+++ b/pt-br/pythonlegacy-pt.html.markdown
@@ -0,0 +1,509 @@
+---
+language: Python 2 (legacy)
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+translators:
+ - ["Vilson Vieira", "http://automata.cc"]
+lang: pt-br
+filename: learnpythonlegacy-pt.py
+---
+
+Python foi criado por Guido Van Rossum no começo dos anos 90. Atualmente é uma
+das linguagens de programação mais populares. Eu me apaixonei por Python, por
+sua clareza de sintaxe. É basicamente pseudocódigo executável.
+
+Comentários serão muito apreciados! Você pode me contactar em
+[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [arroba]
+[serviço de email do google]
+
+Nota: Este artigo usa Python 2.7 especificamente, mas deveria ser aplicável a
+qualquer Python 2.x. Logo haverá uma versão abordando Python 3!
+
+```python
+# Comentários de uma linha começam com cerquilha (ou sustenido)
+""" Strings de várias linhas podem ser escritas
+ usando três ", e são comumente usadas
+ como comentários
+"""
+
+####################################################
+## 1. Tipos de dados primitivos e operadores
+####################################################
+
+# Você usa números normalmente
+3 #=> 3
+
+# Operadores matemáticos são aqueles que você já está acostumado
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# A divisão é um pouco estranha. A divisão de números inteiros arredonda
+# para baixo o resultado, automaticamente
+5 / 2 #=> 2
+
+# Para concertar a divisão, precisamos aprender sobre números de ponto
+# flutuante (conhecidos como 'float').
+2.0 # Isso é um 'float'
+11.0 / 4.0 #=> 2.75 ahhh... muito melhor
+
+# Forçamos a precedência de operadores usando parênteses
+(1 + 3) * 2 #=> 8
+
+# Valores booleanos (ou 'boolean') são também tipos primitivos
+True
+False
+
+# Negamos usando 'not'
+not True #=> False
+not False #=> True
+
+# Testamos igualdade usando '=='
+1 == 1 #=> True
+2 == 1 #=> False
+
+# E desigualdade com '!='
+1 != 1 #=> False
+2 != 1 #=> True
+
+# Mais comparações
+1 < 10 #=> True
+1 > 10 #=> False
+2 <= 2 #=> True
+2 >= 2 #=> True
+
+# As comparações podem ser encadeadas!
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
+
+# Strings são criadas com " ou '
+"Isso é uma string."
+'Isso também é uma string.'
+
+# Strings podem ser somadas (ou melhor, concatenadas)!
+"Olá " + "mundo!" #=> "Olá mundo!"
+
+# Uma string pode ser tratada como uma lista de caracteres
+"Esta é uma string"[0] #=> 'E'
+
+# O caractere % pode ser usado para formatar strings, desta forma:
+"%s podem ser %s" % ("strings", "interpoladas")
+
+# Um jeito novo de formatar strings é usando o método 'format'.
+# Esse método é o jeito mais usado
+"{0} podem ser {1}".format("strings", "formatadas")
+# Você pode usar palavras-chave (ou 'keywords') se você não quiser contar.
+"{nome} quer comer {comida}".format(nome="João", comida="lasanha")
+
+# 'None' é um objeto
+None #=> None
+
+# Não use o operador de igualdade `==` para comparar objetos com 'None'
+# Ao invés disso, use `is`
+"etc" is None #=> False
+None is None #=> True
+
+# O operador 'is' teste a identidade de um objeto. Isso não é
+# muito útil quando estamos lidando com valores primitivos, mas é
+# muito útil quando lidamos com objetos.
+
+# None, 0, e strings/listas vazias são todas interpretadas como 'False'.
+# Todos os outros valores são 'True'
+0 == False #=> True
+"" == False #=> True
+
+
+####################################################
+## 2. Variáveis e Coleções
+####################################################
+
+# Imprimir na tela é muito fácil
+print "Eu sou o Python. Prazer em te conhecer!"
+
+
+# Nós não precisamos declarar variáveis antes de usá-las, basta usar!
+alguma_variavel = 5 # A convenção é usar caixa_baixa_com_sobrescritos
+alguma_variavel #=> 5
+
+# Acessar uma variável que não teve nenhum valor atribuído anteriormente é
+# uma exceção.
+# Veja a seção 'Controle' para aprender mais sobre tratamento de exceção.
+outra_variavel # Gera uma exceção de erro de nome
+
+# 'if' pode ser usado como uma expressão
+"uepa!" if 3 > 2 else 2 #=> "uepa!"
+
+# Listas armazenam sequências de elementos
+lista = []
+# Você pode inicializar uma lista com valores
+outra_lista = [4, 5, 6]
+
+# Adicione elementos no final da lista usando 'append'
+lista.append(1) # lista é agora [1]
+lista.append(2) # lista é agora [1, 2]
+lista.append(4) # lista é agora [1, 2, 4]
+lista.append(3) # lista é agora [1, 2, 4, 3]
+# Remova elementos do fim da lista usando 'pop'
+lista.pop() #=> 3 e lista é agora [1, 2, 4]
+# Vamos adicionar o elemento novamente
+lista.append(3) # lista agora é [1, 2, 4, 3] novamente.
+
+# Acesse elementos de uma lista através de seu índices
+lista[0] #=> 1
+# Acesse o último elemento com índice negativo!
+lista[-1] #=> 3
+
+# Tentar acessar um elemento fora dos limites da lista gera uma exceção
+# do tipo 'IndexError'
+lista[4] # Gera uma exceção 'IndexError'
+
+# Você pode acessar vários elementos ao mesmo tempo usando a sintaxe de
+# limites
+# (Para quem gosta de matemática, isso é um limite fechado/aberto)
+lista[1:3] #=> [2, 4]
+# Você pode omitir o fim se quiser os elementos até o final da lista
+lista[2:] #=> [4, 3]
+# O mesmo para o início
+lista[:3] #=> [1, 2, 4]
+
+# Remova um elemento qualquer de uma lista usando 'del'
+del lista[2] # lista agora é [1, 2, 3]
+
+# Você pode somar listas (obs: as listas originais não são modificadas)
+lista + outra_lista #=> [1, 2, 3, 4, 5, 6]
+
+# Você também pode concatenar usando o método 'extend' (lista será modificada!)
+lista.extend(outra_lista) # Agora lista é [1, 2, 3, 4, 5, 6]
+
+# Para checar se um elemento pertence a uma lista, use 'in'
+1 in lista #=> True
+
+# Saiba quantos elementos uma lista possui com 'len'
+len(lista) #=> 6
+
+
+# Tuplas são iguais a listas, mas são imutáveis
+tup = (1, 2, 3)
+tup[0] #=> 1
+tup[0] = 3 # Isso gera uma exceção do tipo TypeError
+
+# Você pode fazer nas tuplas todas aquelas coisas fez com a lista
+len(tup) #=> 3
+tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
+tup[:2] #=> (1, 2)
+2 in tup #=> True
+
+# Você pode 'desempacotar' tuplas (ou listas) em variáveis, associando cada
+# elemento da tupla/lista a uma variável correspondente
+a, b, c = (1, 2, 3) # a agora é 1, b agora é 2, c agora é 3
+# Tuplas são criadas por padrão, mesmo se você não usar parênteses
+d, e, f = 4, 5, 6
+# Sabendo disso, veja só como é fácil trocar os valores de duas variáveis!
+e, d = d, e # d agora é 5, e agora é 4
+
+
+# Dicionários armazenam 'mapeamentos' (do tipo chave-valor)
+dicionario_vazio = {}
+# Aqui criamos um dicionário já contendo valores
+dicionario = {"um": 1, "dois": 2, "três": 3}
+
+# Acesse valores usando []
+dicionario["um"] #=> 1
+
+# Retorna uma lista com todas as chaves do dicionário
+dicionario.keys() #=> ["três", "dois", "um"]
+# Nota: A ordem das chaves não é garantida.
+# O resultado no seu interpretador não necessariamente será igual a esse.
+
+# Retorna uma lista com todos os valores do dicionário
+dicionario.values() #=> [3, 2, 1]
+# Nota: A mesma nota acima sobre a ordenação é válida aqui.
+
+# Veja se uma chave qualquer está em um dicionário usando 'in'
+"um" in dicionario #=> True
+1 in dicionario #=> False
+
+# Tentar acessar uma chave que não existe gera uma exceção do tipo 'KeyError'
+dicionario["quatro"] # Gera uma exceção KeyError
+
+# Você pode usar o método 'get' para evitar gerar a exceção 'KeyError'.
+# Ao invés de gerar essa exceção, irá retornar 'None' se a chave não existir.
+dicionario.get("um") #=> 1
+dicionario.get("quatro") #=> None
+# O método 'get' suporta um argumento que diz qual valor deverá ser
+# retornado se a chave não existir (ao invés de 'None').
+dicionario.get("um", 4) #=> 1
+dicionario.get("quatro", 4) #=> 4
+
+# O método 'setdefault' é um jeito seguro de adicionar um novo par
+# chave-valor a um dicionário, associando um valor padrão imutável à uma chave
+dicionario.setdefault("cinco", 5) # dicionario["cinco"] é definido como 5
+dicionario.setdefault("cinco", 6) # dicionario["cinco"] ainda é igual a 5
+
+
+# Conjuntos (ou sets) armazenam ... bem, conjuntos
+# Nota: lembre-se que conjuntos não admitem elementos repetidos!
+conjunto_vazio = set()
+# Podemos inicializar um conjunto com valores
+conjunto = set([1, 2, 2, 3, 4]) # conjunto é set([1, 2, 3, 4]), sem repetição!
+
+# Desde o Python 2.7, {} pode ser usado para declarar um conjunto
+conjunto = {1, 2, 2, 3, 4} # => {1 2 3 4}
+
+# Adicione mais ítens a um conjunto com 'add'
+conjunto.add(5) # conjunto agora é {1, 2, 3, 4, 5}
+
+# Calcule a intersecção de dois conjuntos com &
+outro_conj = {3, 4, 5, 6}
+conjunto & outro_conj #=> {3, 4, 5}
+
+# Calcule a união de dois conjuntos com |
+conjunto | outro_conj #=> {1, 2, 3, 4, 5, 6}
+
+# E a diferença entre dois conjuntos com -
+{1,2,3,4} - {2,3,5} #=> {1, 4}
+
+# Veja se um elemento existe em um conjunto usando 'in'
+2 in conjunto #=> True
+10 in conjunto #=> False
+
+
+####################################################
+## 3. Controle
+####################################################
+
+# Para começar, vamos apenas criar uma variável
+alguma_var = 5
+
+# Aqui está uma expressão 'if'. Veja como a identação é importante em Python!
+# Esses comandos irão imprimir "alguma_var é menor que 10"
+if alguma_var > 10:
+ print "some_var é maior que 10."
+elif some_var < 10: # Esse 'elif' é opcional
+ print "some_var é menor que 10."
+else: # Esse 'else' também é opcional
+ print "some_var é igual a 10."
+
+
+"""
+Laços (ou loops) 'for' iteram em listas.
+Irá imprimir:
+ cachorro é um mamífero
+ gato é um mamífero
+ rato é um mamífero
+"""
+for animal in ["cachorro", "gato", "rato"]:
+ # Você pode usar % para interpolar strings formatadas
+ print "%s é um mamífero" % animal
+
+"""
+A função `range(um número)` retorna uma lista de números
+do zero até o número dado.
+Irá imprimir:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+Laços 'while' executam enquanto uma condição dada for verdadeira.
+Irá imprimir:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Isso é um atalho para a expressão x = x + 1
+
+# Tratamos excessões usando o bloco try/except
+# Funciona em Python 2.6 e versões superiores:
+
+try:
+ # Use 'raise' para gerar um erro
+ raise IndexError("Isso é um erro de índice")
+except IndexError as e:
+ pass # Pass é um operador que não faz nada, deixa passar.
+ # Usualmente você iria tratar a exceção aqui...
+
+
+####################################################
+## 4. Funções
+####################################################
+
+# Use 'def' para definir novas funções
+def soma(x, y):
+ print "x é %s e y é %s" % (x, y)
+ return x + y # Retorne valores usando 'return'
+
+# Chamando funções com parâmetros
+soma(5, 6) #=> imprime "x é 5 e y é 6" e retorna o valor 11
+
+# Um outro jeito de chamar funções é especificando explicitamente os valores
+# de cada parâmetro com chaves
+soma(y=6, x=5) # Argumentos com chaves podem vir em qualquer ordem.
+
+# Você pode definir funções que recebem um número qualquer de argumentos
+# (respeitando a sua ordem)
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) #=> (1,2,3)
+
+
+# Você também pode definir funções que recebem um número qualquer de argumentos
+# com chaves
+def args_com_chaves(**ch_args):
+ return ch_args
+
+# Vamos chamar essa função para ver o que acontece
+args_com_chaves(pe="grande", lago="Ness") #=> {"pe": "grande", "lago": "Ness"}
+
+# Você pode fazer as duas coisas ao mesmo tempo, se desejar
+def todos_args(*args, **ch_wargs):
+ print args
+ print ch_args
+"""
+todos_args(1, 2, a=3, b=4) imprime:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Quando você chamar funções, pode fazer o oposto do que fizemos até agora!
+# Podemos usar * para expandir tuplas de argumentos e ** para expandir
+# dicionários de argumentos com chave.
+args = (1, 2, 3, 4)
+ch_args = {"a": 3, "b": 4}
+todos_args(*args) # equivalente a todos_args(1, 2, 3, 4)
+todos_args(**ch_args) # equivalente a todos_args(a=3, b=4)
+todos_args(*args, **ch_args) # equivalente a todos_args(1, 2, 3, 4, a=3, b=4)
+
+# Em Python, funções são elementos de primeira ordem (são como objetos,
+# strings ou números)
+def cria_somador(x):
+ def somador(y):
+ return x + y
+ return somador
+
+soma_10 = cria_somador(10)
+soma_10(3) #=> 13
+
+# Desta forma, existem também funções anônimas
+(lambda x: x > 2)(3) #=> True
+
+# E existem funções de alta ordem por padrão
+map(soma_10, [1,2,3]) #=> [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+reduce(lambda x, y: x + y, [3, 4, 5, 6, 7]) #=> 25
+
+# Nós podemos usar compreensão de listas para mapear e filtrar também
+[soma_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+
+####################################################
+## 5. Classes
+####################################################
+
+# Para criar uma nova classe, devemos herdar de 'object'
+class Humano(object):
+
+ # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa
+ # classe
+ especie = "H. sapiens"
+
+ # Definimos um inicializador básico
+ def __init__(self, nome):
+ # Atribui o valor de argumento dado a um atributo da instância
+ self.nome = nome
+
+ # Um método de instância. Todos os métodos levam 'self' como primeiro
+ # argumento
+ def diga(self, msg):
+ return "%s: %s" % (self.nome, msg)
+
+ # Um método de classe é compartilhado por todas as instâncias
+ # Eles são chamados passando o nome da classe como primeiro argumento
+ @classmethod
+ def get_especie(cls):
+ return cls.especie
+
+ # Um método estático é chamado sem uma referência a classe ou instância
+ @staticmethod
+ def ronca():
+ return "*arrrrrrr*"
+
+
+# Instancie uma classe
+i = Humano(nome="Ivone")
+print i.diga("oi") # imprime "Ivone: oi"
+
+j = Human("Joel")
+print j.say("olá") #prints out "Joel: olá"
+
+# Chame nosso método de classe
+i.get_especie() #=> "H. sapiens"
+
+# Modifique um atributo compartilhado
+Humano.especie = "H. neanderthalensis"
+i.get_especie() #=> "H. neanderthalensis"
+j.get_especie() #=> "H. neanderthalensis"
+
+# Chame o método estático
+Humano.ronca() #=> "*arrrrrrr*"
+
+
+####################################################
+## 6. Módulos
+####################################################
+
+# Você pode importar módulos
+import math
+print math.sqrt(16) #=> 4.0
+
+# Você pode importar funções específicas de um módulo
+from math import ceil, floor
+print ceil(3.7) #=> 4.0
+print floor(3.7) #=> 3.0
+
+# Você também pode importar todas as funções de um módulo
+# Atenção: isso não é recomendado!
+from math import *
+
+# Você pode usar apelidos para os módulos, encurtando seus nomes
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Módulos em Python são apenas arquivos Python. Você
+# pode escrever o seu próprio módulo e importá-lo. O nome do
+# módulo será o mesmo que o nome do arquivo.
+
+# Você pode descobrir quais funções e atributos
+# estão definidos em um módulo qualquer.
+import math
+dir(math)
+
+
+```
+
+## Pronto para mais?
+
+### Online e gratuito
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+
+### Livros impressos
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/python.html.markdown b/python.html.markdown
index 0cc33a80..2e1f8c90 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -1,32 +1,22 @@
---
-language: python
+language: python3
contributors:
- - ["Louie Dinh", "http://ldinh.ca"]
- - ["Amin Bandali", "https://aminb.org"]
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
- ["evuez", "http://github.com/evuez"]
- - ["asyne", "https://github.com/justblah"]
- - ["habi", "http://github.com/habi"]
- ["Rommel Martinez", "https://ebzzry.io"]
+ - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"]
+ - ["caminsha", "https://github.com/caminsha"]
filename: learnpython.py
---
-Python was created by Guido Van Rossum in the early 90s. It is now one of the
-most popular languages in existence. I fell in love with Python for its
-syntactic clarity. It's basically executable pseudocode.
+Python was created by Guido van Rossum in the early 90s. It is now one of the most popular
+languages in existence. I fell in love with Python for its syntactic clarity. It's basically
+executable pseudocode.
-Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh)
-or louiedinh [at] [google's email service]
-
-Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. Python 2.7 is reaching end of life and will stop being
-maintained in 2020, it is though recommended to start learning Python with
-Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
-
-It is also possible to write Python code which is compatible with Python 2.7
-and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
-allow you to write Python 3 code that will run on Python 2, so check out the
-Python 3 tutorial.
+Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/pythonlegacy/) if you want to learn the old Python 2.7
```python
@@ -34,67 +24,72 @@ Python 3 tutorial.
""" Multiline strings can be written
using three "s, and are often used
- as comments
+ as documentation.
"""
####################################################
-# 1. Primitive Datatypes and Operators
+## 1. Primitive Datatypes and Operators
####################################################
# You have numbers
3 # => 3
# Math is what you would expect
-1 + 1 # => 2
-8 - 1 # => 7
+1 + 1 # => 2
+8 - 1 # => 7
10 * 2 # => 20
-35 / 5 # => 7
-
-# Division is a bit tricky. It is integer division and floors the results
-# automatically.
-5 / 2 # => 2
+35 / 5 # => 7.0
-# To fix division we need to learn about floats.
-2.0 # This is a float
-11.0 / 4.0 # => 2.75 ahhh...much better
-
-# Result of integer division truncated down both for positive and negative.
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # works on floats too
--5 // 3 # => -2
+# Integer division rounds down for both positive and negative numbers.
+5 // 3 # => 1
+-5 // 3 # => -2
+5.0 // 3.0 # => 1.0 # works on floats too
-5.0 // 3.0 # => -2.0
-# Note that we can also import division module(Section 6 Modules)
-# to carry out normal division with just one '/'.
-from __future__ import division
-
-11 / 4 # => 2.75 ...normal division
-11 // 4 # => 2 ...floored division
+# The result of division is always a float
+10.0 / 3 # => 3.3333333333333335
# Modulo operation
7 % 3 # => 1
-# Exponentiation (x to the yth power)
-2 ** 4 # => 16
+# Exponentiation (x**y, x to the yth power)
+2**3 # => 8
# Enforce precedence with parentheses
+1 + 3 * 2 # => 7
(1 + 3) * 2 # => 8
+# Boolean values are primitives (Note: the capitalization)
+True # => True
+False # => False
+
+# negate with not
+not True # => False
+not False # => True
+
# Boolean Operators
# Note "and" and "or" are case-sensitive
True and False # => False
-False or True # => True
+False or True # => True
-# Note using Bool operators with ints
-0 and 2 # => 0
--5 or 0 # => -5
-0 == False # => True
-2 == True # => False
-1 == True # => True
+# True and False are actually 1 and 0 but with different keywords
+True + True # => 2
+True * 8 # => 8
+False - 5 # => -5
-# negate with not
-not True # => False
-not False # => True
+# Comparison operators look at the numerical value of True and False
+0 == False # => True
+1 == True # => True
+2 == True # => False
+-5 != False # => True
+
+# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned
+# Don't mix up with bool(ints) and bitwise and/or (&,|)
+bool(0) # => False
+bool(4) # => True
+bool(-6) # => True
+0 and 2 # => 0
+-5 or 0 # => -5
# Equality is ==
1 == 1 # => True
@@ -110,21 +105,31 @@ not False # => True
2 <= 2 # => True
2 >= 2 # => True
-# Comparisons can be chained!
+# Seeing whether a value is in a range
+1 < 2 and 2 < 3 # => True
+2 < 3 and 3 < 2 # => False
+# Chaining makes this look nicer
1 < 2 < 3 # => True
2 < 3 < 2 # => False
+# (is vs. ==) is checks if two variables refer to the same object, but == checks
+# if the objects pointed to have the same values.
+a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
+b = a # Point b at what a is pointing to
+b is a # => True, a and b refer to the same object
+b == a # => True, a's and b's objects are equal
+b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4]
+b is a # => False, a and b do not refer to the same object
+b == a # => True, a's and b's objects are equal
+
# Strings are created with " or '
"This is a string."
'This is also a string.'
-# Strings can be added too!
+# Strings can be added too! But try not to do this.
"Hello " + "world!" # => "Hello world!"
-# Strings can be added without using '+'
-"Hello " "world!" # => "Hello world!"
-
-# ... or multiplied
-"Hello" * 3 # => "HelloHelloHello"
+# String literals (but not variables) can be concatenated without using '+'
+"Hello " "world!" # => "Hello world!"
# A string can be treated like a list of characters
"This is a string"[0] # => 'T'
@@ -132,67 +137,52 @@ not False # => True
# You can find the length of a string
len("This is a string") # => 16
-# String formatting with %
-# Even though the % string operator will be deprecated on Python 3.1 and removed
-# later at some time, it may still be good to know how it works.
-x = 'apple'
-y = 'lemon'
-z = "The items in the basket are %s and %s" % (x, y)
+# You can also format using f-strings or formatted string literals (in Python 3.6+)
+name = "Reiko"
+f"She said her name is {name}." # => "She said her name is Reiko"
+# You can basically put any Python statement inside the braces and it will be output in the string.
+f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
-# A newer way to format strings is the format method.
-# This method is the preferred way
-"{} is a {}".format("This", "placeholder")
-"{0} can be {1}".format("strings", "formatted")
-# You can use keywords if you don't want to count.
-"{name} wants to eat {food}".format(name="Bob", food="lasagna")
# None is an object
None # => None
# Don't use the equality "==" symbol to compare objects to None
-# Use "is" instead
+# Use "is" instead. This checks for equality of object identity.
"etc" is None # => False
-None is None # => True
-
-# The 'is' operator tests for object identity. This isn't
-# very useful when dealing with primitive values, but is
-# very useful when dealing with objects.
-
-# Any object can be used in a Boolean context.
-# The following values are considered falsey:
-# - None
-# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j)
-# - empty sequences (e.g., '', (), [])
-# - empty containers (e.g., {}, set())
-# - instances of user-defined classes meeting certain conditions
-# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
-#
-# All other values are truthy (using the bool() function on them returns True).
-bool(0) # => False
-bool("") # => False
+None is None # => True
+# None, 0, and empty strings/lists/dicts/tuples all evaluate to False.
+# All other values are True
+bool(0) # => False
+bool("") # => False
+bool([]) # => False
+bool({}) # => False
+bool(()) # => False
####################################################
-# 2. Variables and Collections
+## 2. Variables and Collections
####################################################
-# Python has a print statement
-print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+# Python has a print function
+print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
+
+# By default the print function also prints out a newline at the end.
+# Use the optional argument end to change the end string.
+print("Hello, World", end="!") # => Hello, World!
# Simple way to get input data from console
-input_string_var = raw_input(
- "Enter some data: ") # Returns the data as a string
-input_var = input("Enter some data: ") # Evaluates the data as python code
-# Warning: Caution is recommended for input() method usage
-# Note: In python 3, input() is deprecated and raw_input() is renamed to input()
-
-# No need to declare variables before assigning to them.
-some_var = 5 # Convention is to use lower_case_with_underscores
+input_string_var = input("Enter some data: ") # Returns the data as a string
+# Note: In earlier versions of Python, input() method was named as raw_input()
+
+# There are no declarations, only assignments.
+# Convention is to use lower_case_with_underscores
+some_var = 5
some_var # => 5
# Accessing a previously unassigned variable is an exception.
# See Control Flow to learn more about exception handling.
-some_other_var # Raises a name error
+some_unknown_var # Raises a NameError
# if can be used as an expression
# Equivalent of C's '?:' ternary operator
@@ -204,21 +194,17 @@ li = []
other_li = [4, 5, 6]
# Add stuff to the end of a list with append
-li.append(1) # li is now [1]
-li.append(2) # li is now [1, 2]
-li.append(4) # li is now [1, 2, 4]
-li.append(3) # li is now [1, 2, 4, 3]
+li.append(1) # li is now [1]
+li.append(2) # li is now [1, 2]
+li.append(4) # li is now [1, 2, 4]
+li.append(3) # li is now [1, 2, 4, 3]
# Remove from the end with pop
-li.pop() # => 3 and li is now [1, 2, 4]
+li.pop() # => 3 and li is now [1, 2, 4]
# Let's put it back
-li.append(3) # li is now [1, 2, 4, 3] again.
+li.append(3) # li is now [1, 2, 4, 3] again.
# Access a list like you would any array
-li[0] # => 1
-# Assign new values to indexes that have already been initialized with =
-li[0] = 42
-li[0] # => 42
-li[0] = 1 # Note: setting it back to the original value
+li[0] # => 1
# Look at the last element
li[-1] # => 3
@@ -226,39 +212,39 @@ li[-1] # => 3
li[4] # Raises an IndexError
# You can look at ranges with slice syntax.
+# The start index is included, the end index is not
# (It's a closed/open range for you mathy types.)
-li[1:3] # => [2, 4]
-# Omit the beginning
-li[2:] # => [4, 3]
-# Omit the end
-li[:3] # => [1, 2, 4]
-# Select every second entry
-li[::2] # =>[1, 4]
-# Reverse a copy of the list
-li[::-1] # => [3, 4, 2, 1]
+li[1:3] # Return list from index 1 to 3 => [2, 4]
+li[2:] # Return list starting from index 2 => [4, 3]
+li[:3] # Return list from beginning until index 3 => [1, 2, 4]
+li[::2] # Return list selecting every second entry => [1, 4]
+li[::-1] # Return list in reverse order => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
+# Make a one layer deep copy using slices
+li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
+
# Remove arbitrary elements from a list with "del"
del li[2] # li is now [1, 2, 3]
-# You can add lists
-li + other_li # => [1, 2, 3, 4, 5, 6]
-# Note: values for li and for other_li are not modified.
-
-# Concatenate lists with "extend()"
-li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
-
# Remove first occurrence of a value
-li.remove(2) # li is now [1, 3, 4, 5, 6]
+li.remove(2) # li is now [1, 3]
li.remove(2) # Raises a ValueError as 2 is not in the list
# Insert an element at a specific index
-li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again
+li.insert(1, 2) # li is now [1, 2, 3] again
-# Get the index of the first item found
+# Get the index of the first item found matching the argument
li.index(2) # => 1
-li.index(7) # Raises a ValueError as 7 is not in the list
+li.index(4) # Raises a ValueError as 4 is not in the list
+
+# You can add lists
+# Note: values for li and for other_li are not modified.
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# Concatenate lists with "extend()"
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
# Check for existence in a list with "in"
1 in li # => True
@@ -266,82 +252,109 @@ li.index(7) # Raises a ValueError as 7 is not in the list
# Examine the length with "len()"
len(li) # => 6
+
# Tuples are like lists but are immutable.
tup = (1, 2, 3)
-tup[0] # => 1
+tup[0] # => 1
tup[0] = 3 # Raises a TypeError
-# You can do all those list thingies on tuples too
-len(tup) # => 3
+# Note that a tuple of length one has to have a comma after the last element but
+# tuples of other lengths, even zero, do not.
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
+
+# You can do most of the list operations on tuples too
+len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
+tup[:2] # => (1, 2)
+2 in tup # => True
# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
-d, e, f = 4, 5, 6 # you can leave out the parentheses
+# You can also do extended unpacking
+a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4
# Tuples are created by default if you leave out the parentheses
-g = 4, 5, 6 # => (4, 5, 6)
+d, e, f = 4, 5, 6 # tuple 4, 5, 6 is unpacked into variables d, e and f
+# respectively such that d = 4, e = 5 and f = 6
# Now look how easy it is to swap two values
e, d = d, e # d is now 5 and e is now 4
-# Dictionaries store mappings
+
+# Dictionaries store mappings from keys to values
empty_dict = {}
# Here is a prefilled dictionary
filled_dict = {"one": 1, "two": 2, "three": 3}
+# Note keys for dictionaries have to be immutable types. This is to ensure that
+# the key can be converted to a constant hash value for quick look-ups.
+# Immutable types include ints, floats, strings, tuples.
+invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
+
# Look up values with []
filled_dict["one"] # => 1
-# Get all keys as a list with "keys()"
-filled_dict.keys() # => ["three", "two", "one"]
-# Note - Dictionary key ordering is not guaranteed.
-# Your results might not match this exactly.
+# Get all keys as an iterable with "keys()". We need to wrap the call in list()
+# to turn it into a list. We'll talk about those later. Note - for Python
+# versions <3.7, dictionary key ordering is not guaranteed. Your results might
+# not match the example below exactly. However, as of Python 3.7, dictionary
+# items maintain the order at which they are inserted into the dictionary.
+list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7
+list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+
-# Get all values as a list with "values()"
-filled_dict.values() # => [3, 2, 1]
-# Note - Same as above regarding key ordering.
-# Get all key-value pairs as a list of tuples with "items()"
-filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)]
+# Get all values as an iterable with "values()". Once again we need to wrap it
+# in list() to get it out of the iterable. Note - Same as above regarding key
+# ordering.
+list(filled_dict.values()) # => [3, 2, 1] in Python <3.7
+list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+
# Check for existence of keys in a dictionary with "in"
"one" in filled_dict # => True
-1 in filled_dict # => False
+1 in filled_dict # => False
# Looking up a non-existing key is a KeyError
filled_dict["four"] # KeyError
# Use "get()" method to avoid the KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
# The get method supports a default argument when the value is missing
-filled_dict.get("one", 4) # => 1
+filled_dict.get("one", 4) # => 1
filled_dict.get("four", 4) # => 4
-# note that filled_dict.get("four") is still => None
-# (get doesn't set the value in the dictionary)
-
-# set the value of a key with a syntax similar to lists
-filled_dict["four"] = 4 # now, filled_dict["four"] => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
-# You can declare sets (which are like unordered lists that cannot contain
-# duplicate values) using the set object.
-empty_set = set()
-# Initialize a "set()" with a bunch of values
-some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4])
+# Adding to a dictionary
+filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
+filled_dict["four"] = 4 # another way to add to dict
+
+# Remove keys from a dictionary with del
+del filled_dict["one"] # Removes the key "one" from filled dict
+
+# From Python 3.5 you can also use the additional unpacking options
+{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
+{'a': 1, **{'a': 2}} # => {'a': 2}
+
+
-# order is not guaranteed, even though it may sometimes look sorted
-another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4])
+# Sets store ... well sets
+empty_set = set()
+# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
+some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
-# Since Python 2.7, {} can be used to declare a set
-filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+# Similar to keys of a dictionary, elements of a set have to be immutable.
+invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
-# Add more items to a set
+# Add one more item to the set
+filled_set = some_set
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+# Sets do not have duplicate elements
+filled_set.add(5) # it remains as before {1, 2, 3, 4, 5}
# Do set intersection with &
other_set = {3, 4, 5, 6}
@@ -357,37 +370,37 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
# Check if set on the left is a superset of set on the right
-{1, 2} >= {1, 2, 3} # => False
+{1, 2} >= {1, 2, 3} # => False
# Check if set on the left is a subset of set on the right
-{1, 2} <= {1, 2, 3} # => True
+{1, 2} <= {1, 2, 3} # => True
# Check for existence in a set with in
-2 in filled_set # => True
+2 in filled_set # => True
10 in filled_set # => False
-10 not in filled_set # => True
-# Check data type of variable
-type(li) # => list
-type(filled_dict) # => dict
-type(5) # => int
+# Make a one layer deep copy
+filled_set = some_set.copy() # filled_set is {1, 2, 3, 4, 5}
+filled_set is some_set # => False
####################################################
-# 3. Control Flow
+## 3. Control Flow and Iterables
####################################################
# Let's just make a variable
some_var = 5
-# Here is an if statement. Indentation is significant in python!
-# prints "some_var is smaller than 10"
+# Here is an if statement. Indentation is significant in Python!
+# Convention is to use four spaces, not tabs.
+# This prints "some_var is smaller than 10"
if some_var > 10:
- print "some_var is totally bigger than 10."
-elif some_var < 10: # This elif clause is optional.
- print "some_var is smaller than 10."
-else: # This is optional too.
- print "some_var is indeed 10."
+ print("some_var is totally bigger than 10.")
+elif some_var < 10: # This elif clause is optional.
+ print("some_var is smaller than 10.")
+else: # This is optional too.
+ print("some_var is indeed 10.")
+
"""
For loops iterate over lists
@@ -397,11 +410,11 @@ prints:
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
- # You can use {0} to interpolate formatted strings. (See above.)
- print "{0} is a mammal".format(animal)
+ # You can use format() to interpolate formatted strings
+ print("{} is a mammal".format(animal))
"""
-"range(number)" returns a list of numbers
+"range(number)" returns an iterable of numbers
from zero to the given number
prints:
0
@@ -410,10 +423,10 @@ prints:
3
"""
for i in range(4):
- print i
+ print(i)
"""
-"range(lower, upper)" returns a list of numbers
+"range(lower, upper)" returns an iterable of numbers
from the lower number to the upper number
prints:
4
@@ -422,7 +435,29 @@ prints:
7
"""
for i in range(4, 8):
- print i
+ print(i)
+
+"""
+"range(lower, upper, step)" returns an iterable of numbers
+from the lower number to the upper number, while incrementing
+by step. If step is not indicated, the default value is 1.
+prints:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+
+"""
+To loop over a list, and retrieve both the index and the value of each item in the list
+prints:
+ 0 dog
+ 1 cat
+ 2 mouse
+"""
+animals = ["dog", "cat", "mouse"]
+for i, value in enumerate(animals):
+ print(i, value)
"""
While loops go until a condition is no longer met.
@@ -434,72 +469,121 @@ prints:
"""
x = 0
while x < 4:
- print x
+ print(x)
x += 1 # Shorthand for x = x + 1
# Handle exceptions with a try/except block
-
-# Works on Python 2.6 and up:
try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
- pass # Pass is just a no-op. Usually you would do recovery here.
+ pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
- pass # Multiple exceptions can be handled together, if required.
-else: # Optional clause to the try/except block. Must follow all except blocks
- print "All good!" # Runs only if the code in try raises no exceptions
-finally: # Execute under all circumstances
- print "We can clean up resources here"
+ pass # Multiple exceptions can be handled together, if required.
+else: # Optional clause to the try/except block. Must follow all except blocks
+ print("All good!") # Runs only if the code in try raises no exceptions
+finally: # Execute under all circumstances
+ print("We can clean up resources here")
# Instead of try/finally to cleanup resources you can use a with statement
with open("myfile.txt") as f:
for line in f:
- print line
+ print(line)
+
+# Writing to a file
+contents = {"aa": 12, "bb": 21}
+with open("myfile1.txt", "w+") as file:
+ file.write(str(contents)) # writes a string to a file
+
+with open("myfile2.txt", "w+") as file:
+ file.write(json.dumps(contents)) # writes an object to a file
+
+# Reading from a file
+with open('myfile1.txt', "r+") as file:
+ contents = file.read() # reads a string from a file
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+with open('myfile2.txt', "r+") as file:
+ contents = json.load(file) # reads a json object from a file
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+
+# Python offers a fundamental abstraction called the Iterable.
+# An iterable is an object that can be treated as a sequence.
+# The object returned by the range function, is an iterable.
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.
+
+# We can loop over it.
+for i in our_iterable:
+ print(i) # Prints one, two, three
+
+# However we cannot address elements by index.
+our_iterable[1] # Raises a TypeError
+
+# An iterable is an object that knows how to create an iterator.
+our_iterator = iter(our_iterable)
+
+# Our iterator is an object that can remember the state as we traverse through it.
+# We get the next object with "next()".
+next(our_iterator) # => "one"
+
+# It maintains state as we iterate.
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
+
+# After the iterator has returned all of its data, it raises a StopIteration exception
+next(our_iterator) # Raises StopIteration
+
+# We can also loop over it, in fact, "for" does this implicitly!
+our_iterator = iter(our_iterable)
+for i in our_iterator:
+ print(i) # Prints one, two, three
+
+# You can grab all the elements of an iterable or iterator by calling list() on it.
+list(our_iterable) # => Returns ["one", "two", "three"]
+list(our_iterator) # => Returns [] because state is saved
####################################################
-# 4. Functions
+## 4. Functions
####################################################
# Use "def" to create new functions
def add(x, y):
- print "x is {0} and y is {1}".format(x, y)
+ print("x is {} and y is {}".format(x, y))
return x + y # Return values with a return statement
-
# Calling functions with parameters
add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
# Another way to call functions is with keyword arguments
add(y=6, x=5) # Keyword arguments can arrive in any order.
-
# You can define functions that take a variable number of
-# positional args, which will be interpreted as a tuple by using *
+# positional arguments
def varargs(*args):
return args
-
varargs(1, 2, 3) # => (1, 2, 3)
-
# You can define functions that take a variable number of
-# keyword args, as well, which will be interpreted as a dict by using **
+# keyword arguments, as well
def keyword_args(**kwargs):
return kwargs
-
# Let's call it to see what happens
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# You can do both at once, if you like
def all_the_args(*args, **kwargs):
- print args
- print kwargs
-
-
+ print(args)
+ print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
@@ -507,38 +591,36 @@ all_the_args(1, 2, a=3, b=4) prints:
"""
# When calling functions, you can do the opposite of args/kwargs!
-# Use * to expand positional args and use ** to expand keyword args.
+# Use * to expand tuples and use ** to expand kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4)
+all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4)
+# Returning multiple values (with tuple assignments)
+def swap(x, y):
+ return y, x # Return multiple values as a tuple without the parenthesis.
+ # (Note: parenthesis have been excluded but can be included)
-# you can pass args and kwargs along to other functions that take args/kwargs
-# by expanding them with * and ** respectively
-def pass_all_the_args(*args, **kwargs):
- all_the_args(*args, **kwargs)
- print varargs(*args)
- print keyword_args(**kwargs)
-
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
# Function Scope
x = 5
-
def set_x(num):
# Local var x not the same as global variable x
- x = num # => 43
- print x # => 43
-
+ x = num # => 43
+ print(x) # => 43
def set_global_x(num):
global x
- print x # => 5
- x = num # global var x is now set to 6
- print x # => 6
-
+ print(x) # => 5
+ x = num # global var x is now set to 6
+ print(x) # => 6
set_x(43)
set_global_x(6)
@@ -548,55 +630,98 @@ set_global_x(6)
def create_adder(x):
def adder(y):
return x + y
-
return adder
-
add_10 = create_adder(10)
-add_10(3) # => 13
+add_10(3) # => 13
# There are also anonymous functions
-(lambda x: x > 2)(3) # => True
+(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# There are built-in higher order functions
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
+list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
# We can use list comprehensions for nice maps and filters
-[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+# List comprehension stores the output as a list which can itself be a nested list
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
# You can construct set and dict comprehensions as well.
-{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}
-{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
+{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
####################################################
-# 5. Classes
+## 5. Modules
####################################################
-# We subclass from object to get a class.
-class Human(object):
+# You can import modules
+import math
+print(math.sqrt(16)) # => 4.0
+
+# You can get specific functions from a module
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# You can import all functions from a module.
+# Warning: this is not recommended
+from math import *
+
+# You can shorten module names
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Python modules are just ordinary Python files. You
+# can write your own, and import them. The name of the
+# module is the same as the name of the file.
+
+# You can find out which functions and attributes
+# are defined in a module.
+import math
+dir(math)
+
+# If you have a Python script named math.py in the same
+# folder as your current script, the file math.py will
+# be loaded instead of the built-in Python module.
+# This happens because the local folder has priority
+# over Python's built-in libraries.
+
+
+####################################################
+## 6. Classes
+####################################################
+
+# We use the "class" statement to create a class
+class Human:
+
# A class attribute. It is shared by all instances of this class
species = "H. sapiens"
# Basic initializer, this is called when this class is instantiated.
# Note that the double leading and trailing underscores denote objects
- # or attributes that are used by python but that live in user-controlled
- # namespaces. You should not invent such names on your own.
+ # or attributes that are used by Python but that live in user-controlled
+ # namespaces. Methods(or objects or attributes) like: __init__, __str__,
+ # __repr__ etc. are called special methods (or sometimes called dunder methods)
+ # You should not invent such names on your own.
def __init__(self, name):
# Assign the argument to the instance's name attribute
self.name = name
# Initialize property
- self.age = 0
+ self._age = 0
# An instance method. All methods take "self" as the first argument
def say(self, msg):
- return "{0}: {1}".format(self.name, msg)
+ print("{name}: {message}".format(name=self.name, message=msg))
+
+ # Another instance method
+ def sing(self):
+ return 'yo... yo... microphone check... one two... one two...'
# A class method is shared among all instances
# They are called with the calling class as the first argument
@@ -610,8 +735,8 @@ class Human(object):
return "*grunt*"
# A property is just like a getter.
- # It turns the method age() into an read-only attribute
- # of the same name.
+ # It turns the method age() into an read-only attribute of the same name.
+ # There's no need to write trivial getters and setters in Python, though.
@property
def age(self):
return self._age
@@ -627,160 +752,254 @@ class Human(object):
del self._age
-# Instantiate a class
-i = Human(name="Ian")
-print i.say("hi") # prints out "Ian: hi"
+# When a Python interpreter reads a source file it executes all its code.
+# This __name__ check makes sure this code block is only executed when this
+# module is the main program.
+if __name__ == '__main__':
+ # Instantiate a class
+ i = Human(name="Ian")
+ i.say("hi") # "Ian: hi"
+ j = Human("Joel")
+ j.say("hello") # "Joel: hello"
+ # i and j are instances of type Human, or in other words: they are Human objects
+
+ # Call our class method
+ i.say(i.get_species()) # "Ian: H. sapiens"
+ # Change the shared attribute
+ Human.species = "H. neanderthalensis"
+ i.say(i.get_species()) # => "Ian: H. neanderthalensis"
+ j.say(j.get_species()) # => "Joel: H. neanderthalensis"
+
+ # Call the static method
+ print(Human.grunt()) # => "*grunt*"
+
+ # Cannot call static method with instance of object
+ # because i.grunt() will automatically put "self" (the object i) as an argument
+ print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
+
+ # Update the property for this instance
+ i.age = 42
+ # Get the property
+ i.say(i.age) # => "Ian: 42"
+ j.say(j.age) # => "Joel: 0"
+ # Delete the property
+ del i.age
+ # i.age # => this would raise an AttributeError
-j = Human("Joel")
-print j.say("hello") # prints out "Joel: hello"
-# Call our class method
-i.get_species() # => "H. sapiens"
+####################################################
+## 6.1 Inheritance
+####################################################
-# Change the shared attribute
-Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
+# Inheritance allows new child classes to be defined that inherit methods and
+# variables from their parent class.
-# Call the static method
-Human.grunt() # => "*grunt*"
+# Using the Human class defined above as the base or parent class, we can
+# define a child class, Superhero, which inherits the class variables like
+# "species", "name", and "age", as well as methods, like "sing" and "grunt"
+# from the Human class, but can also have its own unique properties.
-# Update the property
-i.age = 42
+# To take advantage of modularization by file you could place the classes above in their own files,
+# say, human.py
-# Get the property
-i.age # => 42
+# To import functions from other files use the following format
+# from "filename-without-extension" import "function-or-class"
-# Delete the property
-del i.age
-i.age # => raises an AttributeError
+from human import Human
-####################################################
-# 6. Modules
-####################################################
-# You can import modules
-import math
+# Specify the parent class(es) as parameters to the class definition
+class Superhero(Human):
-print math.sqrt(16) # => 4.0
+ # If the child class should inherit all of the parent's definitions without
+ # any modifications, you can just use the "pass" keyword (and nothing else)
+ # but in this case it is commented out to allow for a unique child class:
+ # pass
-# You can get specific functions from a module
-from math import ceil, floor
+ # Child classes can override their parents' attributes
+ species = 'Superhuman'
-print ceil(3.7) # => 4.0
-print floor(3.7) # => 3.0
+ # Children automatically inherit their parent class's constructor including
+ # its arguments, but can also define additional arguments or definitions
+ # and override its methods such as the class constructor.
+ # This constructor inherits the "name" argument from the "Human" class and
+ # adds the "superpower" and "movie" arguments:
+ def __init__(self, name, movie=False,
+ superpowers=["super strength", "bulletproofing"]):
-# You can import all functions from a module.
-# Warning: this is not recommended
-from math import *
+ # add additional class attributes:
+ self.fictional = True
+ self.movie = movie
+ # be aware of mutable default values, since defaults are shared
+ self.superpowers = superpowers
-# You can shorten module names
-import math as m
+ # The "super" function lets you access the parent class's methods
+ # that are overridden by the child, in this case, the __init__ method.
+ # This calls the parent class constructor:
+ super().__init__(name)
-math.sqrt(16) == m.sqrt(16) # => True
-# you can also test that the functions are equivalent
-from math import sqrt
+ # override the sing method
+ def sing(self):
+ return 'Dun, dun, DUN!'
-math.sqrt == m.sqrt == sqrt # => True
+ # add an additional instance method
+ def boast(self):
+ for power in self.superpowers:
+ print("I wield the power of {pow}!".format(pow=power))
-# Python modules are just ordinary python files. You
-# can write your own, and import them. The name of the
-# module is the same as the name of the file.
-# You can find out which functions and attributes
-# defines a module.
-import math
+if __name__ == '__main__':
+ sup = Superhero(name="Tick")
-dir(math)
+ # Instance type checks
+ if isinstance(sup, Human):
+ print('I am human')
+ if type(sup) is Superhero:
+ print('I am a superhero')
+ # Get the Method Resolution search Order used by both getattr() and super()
+ # This attribute is dynamic and can be updated
+ print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
+ # => <class 'human.Human'>, <class 'object'>)
-# If you have a Python script named math.py in the same
-# folder as your current script, the file math.py will
-# be loaded instead of the built-in Python module.
-# This happens because the local folder has priority
-# over Python's built-in libraries.
+ # Calls parent method but uses its own class attribute
+ print(sup.get_species()) # => Superhuman
+
+ # Calls overridden method
+ print(sup.sing()) # => Dun, dun, DUN!
+
+ # Calls method from Human
+ sup.say('Spoon') # => Tick: Spoon
+ # Call method that exists only in Superhero
+ sup.boast() # => I wield the power of super strength!
+ # => I wield the power of bulletproofing!
+
+ # Inherited class attribute
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Attribute that only exists within Superhero
+ print('Am I Oscar eligible? ' + str(sup.movie))
####################################################
-# 7. Advanced
+## 6.2 Multiple Inheritance
####################################################
-# Generators
-# A generator "generates" values as they are requested instead of storing
-# everything up front
+# Another class definition
+# bat.py
+class Bat:
-# The following method (*NOT* a generator) will double all values and store it
-# in `double_arr`. For large size of iterables, that might get huge!
-def double_numbers(iterable):
- double_arr = []
- for i in iterable:
- double_arr.append(i + i)
- return double_arr
+ species = 'Baty'
+ def __init__(self, can_fly=True):
+ self.fly = can_fly
-# Running the following would mean we'll double all values first and return all
-# of them back to be checked by our condition
-for value in double_numbers(range(1000000)): # `test_non_generator`
- print value
- if value > 5:
- break
+ # This class also has a say method
+ def say(self, msg):
+ msg = '... ... ...'
+ return msg
+
+ # And its own method as well
+ def sonar(self):
+ return '))) ... ((('
+
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('hello'))
+ print(b.fly)
+
+
+# And yet another class definition that inherits from Superhero and Bat
+# superhero.py
+from superhero import Superhero
+from bat import Bat
+# Define Batman as a child that inherits from both Superhero and Bat
+class Batman(Superhero, Bat):
-# We could instead use a generator to "generate" the doubled value as the item
-# is being requested
-def double_numbers_generator(iterable):
+ def __init__(self, *args, **kwargs):
+ # Typically to inherit attributes you have to call super:
+ # super(Batman, self).__init__(*args, **kwargs)
+ # However we are dealing with multiple inheritance here, and super()
+ # only works with the next base class in the MRO list.
+ # So instead we explicitly call __init__ for all ancestors.
+ # The use of *args and **kwargs allows for a clean way to pass arguments,
+ # with each parent "peeling a layer of the onion".
+ Superhero.__init__(self, 'anonymous', movie=True,
+ superpowers=['Wealthy'], *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # override the value for the name attribute
+ self.name = 'Sad Affleck'
+
+ def sing(self):
+ return 'nan nan nan nan nan batman!'
+
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # Get the Method Resolution search Order used by both getattr() and super().
+ # This attribute is dynamic and can be updated
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
+ # => <class 'bat.Bat'>, <class 'object'>)
+
+ # Calls parent method but uses its own class attribute
+ print(sup.get_species()) # => Superhuman
+
+ # Calls overridden method
+ print(sup.sing()) # => nan nan nan nan nan batman!
+
+ # Calls method from Human, because inheritance order matters
+ sup.say('I agree') # => Sad Affleck: I agree
+
+ # Call method that exists only in 2nd ancestor
+ print(sup.sonar()) # => ))) ... (((
+
+ # Inherited class attribute
+ sup.age = 100
+ print(sup.age) # => 100
+
+ # Inherited attribute from 2nd ancestor whose default value was overridden.
+ print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
+
+
+
+####################################################
+## 7. Advanced
+####################################################
+
+# Generators help you make lazy code.
+def double_numbers(iterable):
for i in iterable:
yield i + i
-
-# Running the same code as before, but with a generator, now allows us to iterate
-# over the values and doubling them one by one as they are being consumed by
-# our logic. Hence as soon as we see a value > 5, we break out of the
-# loop and don't need to double most of the values sent in (MUCH FASTER!)
-for value in double_numbers_generator(xrange(1000000)): # `test_generator`
- print value
- if value > 5:
+# Generators are memory-efficient because they only load the data needed to
+# process the next value in the iterable. This allows them to perform
+# operations on otherwise prohibitively large value ranges.
+# NOTE: `range` replaces `xrange` in Python 3.
+for i in double_numbers(range(1, 900000000)): # `range` is a generator.
+ print(i)
+ if i >= 30:
break
-# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`?
-# Just as `double_numbers_generator` is the generator version of `double_numbers`
-# We have `xrange` as the generator version of `range`
-# `range` would return back and array with 1000000 values for us to use
-# `xrange` would generate 1000000 values for us as we request / iterate over those items
-
# Just as you can create a list comprehension, you can create generator
# comprehensions as well.
-values = (-x for x in [1, 2, 3, 4, 5])
+values = (-x for x in [1,2,3,4,5])
for x in values:
print(x) # prints -1 -2 -3 -4 -5 to console/terminal
# You can also cast a generator comprehension directly to a list.
-values = (-x for x in [1, 2, 3, 4, 5])
+values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
# Decorators
-# A decorator is a higher order function, which accepts and returns a function.
-# Simple usage example – add_apples decorator will add 'Apple' element into
-# fruits list returned by get_fruits target function.
-def add_apples(func):
- def get_fruits():
- fruits = func()
- fruits.append('Apple')
- return fruits
- return get_fruits
-
-@add_apples
-def get_fruits():
- return ['Banana', 'Mango', 'Orange']
-
-# Prints out the list of fruits with 'Apple' element in it:
-# Banana, Mango, Orange, Apple
-print ', '.join(get_fruits())
-
-# in this example beg wraps say
-# Beg will call say. If say_please is True then it will change the returned
-# message
+# In this example `beg` wraps `say`. If say_please is True then it
+# will change the returned message.
from functools import wraps
@@ -801,8 +1020,8 @@ def say(say_please=False):
return msg, say_please
-print say() # Can you buy me a beer?
-print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
+print(say()) # Can you buy me a beer?
+print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
## Ready For More?
@@ -810,18 +1029,14 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
### Free Online
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [Python Course](http://www.python-course.eu/index.php)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
-* [LearnPython](http://www.learnpython.org/)
-* [Fullstack Python](https://www.fullstackpython.com/)
-
-### Dead Tree
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
+* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
+* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
+* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
diff --git a/python3.html.markdown b/python3.html.markdown
deleted file mode 100644
index f69ffb14..00000000
--- a/python3.html.markdown
+++ /dev/null
@@ -1,1042 +0,0 @@
----
-language: python3
-contributors:
- - ["Louie Dinh", "http://pythonpracticeprojects.com"]
- - ["Steven Basart", "http://github.com/xksteven"]
- - ["Andre Polykanine", "https://github.com/Oire"]
- - ["Zachary Ferguson", "http://github.com/zfergus2"]
- - ["evuez", "http://github.com/evuez"]
- - ["Rommel Martinez", "https://ebzzry.io"]
- - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"]
- - ["caminsha", "https://github.com/caminsha"]
-filename: learnpython3.py
----
-
-Python was created by Guido van Rossum in the early 90s. It is now one of the most popular
-languages in existence. I fell in love with Python for its syntactic clarity. It's basically
-executable pseudocode.
-
-Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7
-
-```python
-
-# Single line comments start with a number symbol.
-
-""" Multiline strings can be written
- using three "s, and are often used
- as documentation.
-"""
-
-####################################################
-## 1. Primitive Datatypes and Operators
-####################################################
-
-# You have numbers
-3 # => 3
-
-# Math is what you would expect
-1 + 1 # => 2
-8 - 1 # => 7
-10 * 2 # => 20
-35 / 5 # => 7.0
-
-# Integer division rounds down for both positive and negative numbers.
-5 // 3 # => 1
--5 // 3 # => -2
-5.0 // 3.0 # => 1.0 # works on floats too
--5.0 // 3.0 # => -2.0
-
-# The result of division is always a float
-10.0 / 3 # => 3.3333333333333335
-
-# Modulo operation
-7 % 3 # => 1
-
-# Exponentiation (x**y, x to the yth power)
-2**3 # => 8
-
-# Enforce precedence with parentheses
-1 + 3 * 2 # => 7
-(1 + 3) * 2 # => 8
-
-# Boolean values are primitives (Note: the capitalization)
-True # => True
-False # => False
-
-# negate with not
-not True # => False
-not False # => True
-
-# Boolean Operators
-# Note "and" and "or" are case-sensitive
-True and False # => False
-False or True # => True
-
-# True and False are actually 1 and 0 but with different keywords
-True + True # => 2
-True * 8 # => 8
-False - 5 # => -5
-
-# Comparison operators look at the numerical value of True and False
-0 == False # => True
-1 == True # => True
-2 == True # => False
--5 != False # => True
-
-# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned
-# Don't mix up with bool(ints) and bitwise and/or (&,|)
-bool(0) # => False
-bool(4) # => True
-bool(-6) # => True
-0 and 2 # => 0
--5 or 0 # => -5
-
-# Equality is ==
-1 == 1 # => True
-2 == 1 # => False
-
-# Inequality is !=
-1 != 1 # => False
-2 != 1 # => True
-
-# More comparisons
-1 < 10 # => True
-1 > 10 # => False
-2 <= 2 # => True
-2 >= 2 # => True
-
-# Seeing whether a value is in a range
-1 < 2 and 2 < 3 # => True
-2 < 3 and 3 < 2 # => False
-# Chaining makes this look nicer
-1 < 2 < 3 # => True
-2 < 3 < 2 # => False
-
-# (is vs. ==) is checks if two variables refer to the same object, but == checks
-# if the objects pointed to have the same values.
-a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
-b = a # Point b at what a is pointing to
-b is a # => True, a and b refer to the same object
-b == a # => True, a's and b's objects are equal
-b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4]
-b is a # => False, a and b do not refer to the same object
-b == a # => True, a's and b's objects are equal
-
-# Strings are created with " or '
-"This is a string."
-'This is also a string.'
-
-# Strings can be added too! But try not to do this.
-"Hello " + "world!" # => "Hello world!"
-# String literals (but not variables) can be concatenated without using '+'
-"Hello " "world!" # => "Hello world!"
-
-# A string can be treated like a list of characters
-"This is a string"[0] # => 'T'
-
-# You can find the length of a string
-len("This is a string") # => 16
-
-# You can also format using f-strings or formatted string literals (in Python 3.6+)
-name = "Reiko"
-f"She said her name is {name}." # => "She said her name is Reiko"
-# You can basically put any Python statement inside the braces and it will be output in the string.
-f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
-
-
-# None is an object
-None # => None
-
-# Don't use the equality "==" symbol to compare objects to None
-# Use "is" instead. This checks for equality of object identity.
-"etc" is None # => False
-None is None # => True
-
-# None, 0, and empty strings/lists/dicts/tuples all evaluate to False.
-# All other values are True
-bool(0) # => False
-bool("") # => False
-bool([]) # => False
-bool({}) # => False
-bool(()) # => False
-
-####################################################
-## 2. Variables and Collections
-####################################################
-
-# Python has a print function
-print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
-
-# By default the print function also prints out a newline at the end.
-# Use the optional argument end to change the end string.
-print("Hello, World", end="!") # => Hello, World!
-
-# Simple way to get input data from console
-input_string_var = input("Enter some data: ") # Returns the data as a string
-# Note: In earlier versions of Python, input() method was named as raw_input()
-
-# There are no declarations, only assignments.
-# Convention is to use lower_case_with_underscores
-some_var = 5
-some_var # => 5
-
-# Accessing a previously unassigned variable is an exception.
-# See Control Flow to learn more about exception handling.
-some_unknown_var # Raises a NameError
-
-# if can be used as an expression
-# Equivalent of C's '?:' ternary operator
-"yahoo!" if 3 > 2 else 2 # => "yahoo!"
-
-# Lists store sequences
-li = []
-# You can start with a prefilled list
-other_li = [4, 5, 6]
-
-# Add stuff to the end of a list with append
-li.append(1) # li is now [1]
-li.append(2) # li is now [1, 2]
-li.append(4) # li is now [1, 2, 4]
-li.append(3) # li is now [1, 2, 4, 3]
-# Remove from the end with pop
-li.pop() # => 3 and li is now [1, 2, 4]
-# Let's put it back
-li.append(3) # li is now [1, 2, 4, 3] again.
-
-# Access a list like you would any array
-li[0] # => 1
-# Look at the last element
-li[-1] # => 3
-
-# Looking out of bounds is an IndexError
-li[4] # Raises an IndexError
-
-# You can look at ranges with slice syntax.
-# The start index is included, the end index is not
-# (It's a closed/open range for you mathy types.)
-li[1:3] # Return list from index 1 to 3 => [2, 4]
-li[2:] # Return list starting from index 2 => [4, 3]
-li[:3] # Return list from beginning until index 3 => [1, 2, 4]
-li[::2] # Return list selecting every second entry => [1, 4]
-li[::-1] # Return list in reverse order => [3, 4, 2, 1]
-# Use any combination of these to make advanced slices
-# li[start:end:step]
-
-# Make a one layer deep copy using slices
-li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
-
-# Remove arbitrary elements from a list with "del"
-del li[2] # li is now [1, 2, 3]
-
-# Remove first occurrence of a value
-li.remove(2) # li is now [1, 3]
-li.remove(2) # Raises a ValueError as 2 is not in the list
-
-# Insert an element at a specific index
-li.insert(1, 2) # li is now [1, 2, 3] again
-
-# Get the index of the first item found matching the argument
-li.index(2) # => 1
-li.index(4) # Raises a ValueError as 4 is not in the list
-
-# You can add lists
-# Note: values for li and for other_li are not modified.
-li + other_li # => [1, 2, 3, 4, 5, 6]
-
-# Concatenate lists with "extend()"
-li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
-
-# Check for existence in a list with "in"
-1 in li # => True
-
-# Examine the length with "len()"
-len(li) # => 6
-
-
-# Tuples are like lists but are immutable.
-tup = (1, 2, 3)
-tup[0] # => 1
-tup[0] = 3 # Raises a TypeError
-
-# Note that a tuple of length one has to have a comma after the last element but
-# tuples of other lengths, even zero, do not.
-type((1)) # => <class 'int'>
-type((1,)) # => <class 'tuple'>
-type(()) # => <class 'tuple'>
-
-# You can do most of the list operations on tuples too
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
-
-# You can unpack tuples (or lists) into variables
-a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
-# You can also do extended unpacking
-a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4
-# Tuples are created by default if you leave out the parentheses
-d, e, f = 4, 5, 6 # tuple 4, 5, 6 is unpacked into variables d, e and f
-# respectively such that d = 4, e = 5 and f = 6
-# Now look how easy it is to swap two values
-e, d = d, e # d is now 5 and e is now 4
-
-
-# Dictionaries store mappings from keys to values
-empty_dict = {}
-# Here is a prefilled dictionary
-filled_dict = {"one": 1, "two": 2, "three": 3}
-
-# Note keys for dictionaries have to be immutable types. This is to ensure that
-# the key can be converted to a constant hash value for quick look-ups.
-# Immutable types include ints, floats, strings, tuples.
-invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
-valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
-
-# Look up values with []
-filled_dict["one"] # => 1
-
-# Get all keys as an iterable with "keys()". We need to wrap the call in list()
-# to turn it into a list. We'll talk about those later. Note - for Python
-# versions <3.7, dictionary key ordering is not guaranteed. Your results might
-# not match the example below exactly. However, as of Python 3.7, dictionary
-# items maintain the order at which they are inserted into the dictionary.
-list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7
-list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+
-
-
-# Get all values as an iterable with "values()". Once again we need to wrap it
-# in list() to get it out of the iterable. Note - Same as above regarding key
-# ordering.
-list(filled_dict.values()) # => [3, 2, 1] in Python <3.7
-list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+
-
-# Check for existence of keys in a dictionary with "in"
-"one" in filled_dict # => True
-1 in filled_dict # => False
-
-# Looking up a non-existing key is a KeyError
-filled_dict["four"] # KeyError
-
-# Use "get()" method to avoid the KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
-# The get method supports a default argument when the value is missing
-filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
-
-# "setdefault()" inserts into a dictionary only if the given key isn't present
-filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
-filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
-
-# Adding to a dictionary
-filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
-filled_dict["four"] = 4 # another way to add to dict
-
-# Remove keys from a dictionary with del
-del filled_dict["one"] # Removes the key "one" from filled dict
-
-# From Python 3.5 you can also use the additional unpacking options
-{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
-{'a': 1, **{'a': 2}} # => {'a': 2}
-
-
-
-# Sets store ... well sets
-empty_set = set()
-# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
-some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
-
-# Similar to keys of a dictionary, elements of a set have to be immutable.
-invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
-valid_set = {(1,), 1}
-
-# Add one more item to the set
-filled_set = some_set
-filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
-# Sets do not have duplicate elements
-filled_set.add(5) # it remains as before {1, 2, 3, 4, 5}
-
-# Do set intersection with &
-other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
-
-# Do set union with |
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-
-# Do set difference with -
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
-
-# Do set symmetric difference with ^
-{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
-
-# Check if set on the left is a superset of set on the right
-{1, 2} >= {1, 2, 3} # => False
-
-# Check if set on the left is a subset of set on the right
-{1, 2} <= {1, 2, 3} # => True
-
-# Check for existence in a set with in
-2 in filled_set # => True
-10 in filled_set # => False
-
-# Make a one layer deep copy
-filled_set = some_set.copy() # filled_set is {1, 2, 3, 4, 5}
-filled_set is some_set # => False
-
-
-####################################################
-## 3. Control Flow and Iterables
-####################################################
-
-# Let's just make a variable
-some_var = 5
-
-# Here is an if statement. Indentation is significant in Python!
-# Convention is to use four spaces, not tabs.
-# This prints "some_var is smaller than 10"
-if some_var > 10:
- print("some_var is totally bigger than 10.")
-elif some_var < 10: # This elif clause is optional.
- print("some_var is smaller than 10.")
-else: # This is optional too.
- print("some_var is indeed 10.")
-
-
-"""
-For loops iterate over lists
-prints:
- dog is a mammal
- cat is a mammal
- mouse is a mammal
-"""
-for animal in ["dog", "cat", "mouse"]:
- # You can use format() to interpolate formatted strings
- print("{} is a mammal".format(animal))
-
-"""
-"range(number)" returns an iterable of numbers
-from zero to the given number
-prints:
- 0
- 1
- 2
- 3
-"""
-for i in range(4):
- print(i)
-
-"""
-"range(lower, upper)" returns an iterable of numbers
-from the lower number to the upper number
-prints:
- 4
- 5
- 6
- 7
-"""
-for i in range(4, 8):
- print(i)
-
-"""
-"range(lower, upper, step)" returns an iterable of numbers
-from the lower number to the upper number, while incrementing
-by step. If step is not indicated, the default value is 1.
-prints:
- 4
- 6
-"""
-for i in range(4, 8, 2):
- print(i)
-
-"""
-To loop over a list, and retrieve both the index and the value of each item in the list
-prints:
- 0 dog
- 1 cat
- 2 mouse
-"""
-animals = ["dog", "cat", "mouse"]
-for i, value in enumerate(animals):
- print(i, value)
-
-"""
-While loops go until a condition is no longer met.
-prints:
- 0
- 1
- 2
- 3
-"""
-x = 0
-while x < 4:
- print(x)
- x += 1 # Shorthand for x = x + 1
-
-# Handle exceptions with a try/except block
-try:
- # Use "raise" to raise an error
- raise IndexError("This is an index error")
-except IndexError as e:
- pass # Pass is just a no-op. Usually you would do recovery here.
-except (TypeError, NameError):
- pass # Multiple exceptions can be handled together, if required.
-else: # Optional clause to the try/except block. Must follow all except blocks
- print("All good!") # Runs only if the code in try raises no exceptions
-finally: # Execute under all circumstances
- print("We can clean up resources here")
-
-# Instead of try/finally to cleanup resources you can use a with statement
-with open("myfile.txt") as f:
- for line in f:
- print(line)
-
-# Writing to a file
-contents = {"aa": 12, "bb": 21}
-with open("myfile1.txt", "w+") as file:
- file.write(str(contents)) # writes a string to a file
-
-with open("myfile2.txt", "w+") as file:
- file.write(json.dumps(contents)) # writes an object to a file
-
-# Reading from a file
-with open('myfile1.txt', "r+") as file:
- contents = file.read() # reads a string from a file
-print(contents)
-# print: {"aa": 12, "bb": 21}
-
-with open('myfile2.txt', "r+") as file:
- contents = json.load(file) # reads a json object from a file
-print(contents)
-# print: {"aa": 12, "bb": 21}
-
-
-# Python offers a fundamental abstraction called the Iterable.
-# An iterable is an object that can be treated as a sequence.
-# The object returned by the range function, is an iterable.
-
-filled_dict = {"one": 1, "two": 2, "three": 3}
-our_iterable = filled_dict.keys()
-print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.
-
-# We can loop over it.
-for i in our_iterable:
- print(i) # Prints one, two, three
-
-# However we cannot address elements by index.
-our_iterable[1] # Raises a TypeError
-
-# An iterable is an object that knows how to create an iterator.
-our_iterator = iter(our_iterable)
-
-# Our iterator is an object that can remember the state as we traverse through it.
-# We get the next object with "next()".
-next(our_iterator) # => "one"
-
-# It maintains state as we iterate.
-next(our_iterator) # => "two"
-next(our_iterator) # => "three"
-
-# After the iterator has returned all of its data, it raises a StopIteration exception
-next(our_iterator) # Raises StopIteration
-
-# We can also loop over it, in fact, "for" does this implicitly!
-our_iterator = iter(our_iterable)
-for i in our_iterator:
- print(i) # Prints one, two, three
-
-# You can grab all the elements of an iterable or iterator by calling list() on it.
-list(our_iterable) # => Returns ["one", "two", "three"]
-list(our_iterator) # => Returns [] because state is saved
-
-
-####################################################
-## 4. Functions
-####################################################
-
-# Use "def" to create new functions
-def add(x, y):
- print("x is {} and y is {}".format(x, y))
- return x + y # Return values with a return statement
-
-# Calling functions with parameters
-add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
-
-# Another way to call functions is with keyword arguments
-add(y=6, x=5) # Keyword arguments can arrive in any order.
-
-# You can define functions that take a variable number of
-# positional arguments
-def varargs(*args):
- return args
-
-varargs(1, 2, 3) # => (1, 2, 3)
-
-# You can define functions that take a variable number of
-# keyword arguments, as well
-def keyword_args(**kwargs):
- return kwargs
-
-# Let's call it to see what happens
-keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
-
-
-# You can do both at once, if you like
-def all_the_args(*args, **kwargs):
- print(args)
- print(kwargs)
-"""
-all_the_args(1, 2, a=3, b=4) prints:
- (1, 2)
- {"a": 3, "b": 4}
-"""
-
-# When calling functions, you can do the opposite of args/kwargs!
-# Use * to expand tuples and use ** to expand kwargs.
-args = (1, 2, 3, 4)
-kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4)
-all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4)
-
-# Returning multiple values (with tuple assignments)
-def swap(x, y):
- return y, x # Return multiple values as a tuple without the parenthesis.
- # (Note: parenthesis have been excluded but can be included)
-
-x = 1
-y = 2
-x, y = swap(x, y) # => x = 2, y = 1
-# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
-
-# Function Scope
-x = 5
-
-def set_x(num):
- # Local var x not the same as global variable x
- x = num # => 43
- print(x) # => 43
-
-def set_global_x(num):
- global x
- print(x) # => 5
- x = num # global var x is now set to 6
- print(x) # => 6
-
-set_x(43)
-set_global_x(6)
-
-
-# Python has first class functions
-def create_adder(x):
- def adder(y):
- return x + y
- return adder
-
-add_10 = create_adder(10)
-add_10(3) # => 13
-
-# There are also anonymous functions
-(lambda x: x > 2)(3) # => True
-(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
-
-# There are built-in higher order functions
-list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
-list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
-
-list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
-
-# We can use list comprehensions for nice maps and filters
-# List comprehension stores the output as a list which can itself be a nested list
-[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
-
-# You can construct set and dict comprehensions as well.
-{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
-{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
-
-
-####################################################
-## 5. Modules
-####################################################
-
-# You can import modules
-import math
-print(math.sqrt(16)) # => 4.0
-
-# You can get specific functions from a module
-from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
-
-# You can import all functions from a module.
-# Warning: this is not recommended
-from math import *
-
-# You can shorten module names
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
-
-# Python modules are just ordinary Python files. You
-# can write your own, and import them. The name of the
-# module is the same as the name of the file.
-
-# You can find out which functions and attributes
-# are defined in a module.
-import math
-dir(math)
-
-# If you have a Python script named math.py in the same
-# folder as your current script, the file math.py will
-# be loaded instead of the built-in Python module.
-# This happens because the local folder has priority
-# over Python's built-in libraries.
-
-
-####################################################
-## 6. Classes
-####################################################
-
-# We use the "class" statement to create a class
-class Human:
-
- # A class attribute. It is shared by all instances of this class
- species = "H. sapiens"
-
- # Basic initializer, this is called when this class is instantiated.
- # Note that the double leading and trailing underscores denote objects
- # or attributes that are used by Python but that live in user-controlled
- # namespaces. Methods(or objects or attributes) like: __init__, __str__,
- # __repr__ etc. are called special methods (or sometimes called dunder methods)
- # You should not invent such names on your own.
- def __init__(self, name):
- # Assign the argument to the instance's name attribute
- self.name = name
-
- # Initialize property
- self._age = 0
-
- # An instance method. All methods take "self" as the first argument
- def say(self, msg):
- print("{name}: {message}".format(name=self.name, message=msg))
-
- # Another instance method
- def sing(self):
- return 'yo... yo... microphone check... one two... one two...'
-
- # A class method is shared among all instances
- # They are called with the calling class as the first argument
- @classmethod
- def get_species(cls):
- return cls.species
-
- # A static method is called without a class or instance reference
- @staticmethod
- def grunt():
- return "*grunt*"
-
- # A property is just like a getter.
- # It turns the method age() into an read-only attribute of the same name.
- # There's no need to write trivial getters and setters in Python, though.
- @property
- def age(self):
- return self._age
-
- # This allows the property to be set
- @age.setter
- def age(self, age):
- self._age = age
-
- # This allows the property to be deleted
- @age.deleter
- def age(self):
- del self._age
-
-
-# When a Python interpreter reads a source file it executes all its code.
-# This __name__ check makes sure this code block is only executed when this
-# module is the main program.
-if __name__ == '__main__':
- # Instantiate a class
- i = Human(name="Ian")
- i.say("hi") # "Ian: hi"
- j = Human("Joel")
- j.say("hello") # "Joel: hello"
- # i and j are instances of type Human, or in other words: they are Human objects
-
- # Call our class method
- i.say(i.get_species()) # "Ian: H. sapiens"
- # Change the shared attribute
- Human.species = "H. neanderthalensis"
- i.say(i.get_species()) # => "Ian: H. neanderthalensis"
- j.say(j.get_species()) # => "Joel: H. neanderthalensis"
-
- # Call the static method
- print(Human.grunt()) # => "*grunt*"
-
- # Cannot call static method with instance of object
- # because i.grunt() will automatically put "self" (the object i) as an argument
- print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
-
- # Update the property for this instance
- i.age = 42
- # Get the property
- i.say(i.age) # => "Ian: 42"
- j.say(j.age) # => "Joel: 0"
- # Delete the property
- del i.age
- # i.age # => this would raise an AttributeError
-
-
-####################################################
-## 6.1 Inheritance
-####################################################
-
-# Inheritance allows new child classes to be defined that inherit methods and
-# variables from their parent class.
-
-# Using the Human class defined above as the base or parent class, we can
-# define a child class, Superhero, which inherits the class variables like
-# "species", "name", and "age", as well as methods, like "sing" and "grunt"
-# from the Human class, but can also have its own unique properties.
-
-# To take advantage of modularization by file you could place the classes above in their own files,
-# say, human.py
-
-# To import functions from other files use the following format
-# from "filename-without-extension" import "function-or-class"
-
-from human import Human
-
-
-# Specify the parent class(es) as parameters to the class definition
-class Superhero(Human):
-
- # If the child class should inherit all of the parent's definitions without
- # any modifications, you can just use the "pass" keyword (and nothing else)
- # but in this case it is commented out to allow for a unique child class:
- # pass
-
- # Child classes can override their parents' attributes
- species = 'Superhuman'
-
- # Children automatically inherit their parent class's constructor including
- # its arguments, but can also define additional arguments or definitions
- # and override its methods such as the class constructor.
- # This constructor inherits the "name" argument from the "Human" class and
- # adds the "superpower" and "movie" arguments:
- def __init__(self, name, movie=False,
- superpowers=["super strength", "bulletproofing"]):
-
- # add additional class attributes:
- self.fictional = True
- self.movie = movie
- # be aware of mutable default values, since defaults are shared
- self.superpowers = superpowers
-
- # The "super" function lets you access the parent class's methods
- # that are overridden by the child, in this case, the __init__ method.
- # This calls the parent class constructor:
- super().__init__(name)
-
- # override the sing method
- def sing(self):
- return 'Dun, dun, DUN!'
-
- # add an additional instance method
- def boast(self):
- for power in self.superpowers:
- print("I wield the power of {pow}!".format(pow=power))
-
-
-if __name__ == '__main__':
- sup = Superhero(name="Tick")
-
- # Instance type checks
- if isinstance(sup, Human):
- print('I am human')
- if type(sup) is Superhero:
- print('I am a superhero')
-
- # Get the Method Resolution search Order used by both getattr() and super()
- # This attribute is dynamic and can be updated
- print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
- # => <class 'human.Human'>, <class 'object'>)
-
- # Calls parent method but uses its own class attribute
- print(sup.get_species()) # => Superhuman
-
- # Calls overridden method
- print(sup.sing()) # => Dun, dun, DUN!
-
- # Calls method from Human
- sup.say('Spoon') # => Tick: Spoon
-
- # Call method that exists only in Superhero
- sup.boast() # => I wield the power of super strength!
- # => I wield the power of bulletproofing!
-
- # Inherited class attribute
- sup.age = 31
- print(sup.age) # => 31
-
- # Attribute that only exists within Superhero
- print('Am I Oscar eligible? ' + str(sup.movie))
-
-####################################################
-## 6.2 Multiple Inheritance
-####################################################
-
-# Another class definition
-# bat.py
-class Bat:
-
- species = 'Baty'
-
- def __init__(self, can_fly=True):
- self.fly = can_fly
-
- # This class also has a say method
- def say(self, msg):
- msg = '... ... ...'
- return msg
-
- # And its own method as well
- def sonar(self):
- return '))) ... ((('
-
-if __name__ == '__main__':
- b = Bat()
- print(b.say('hello'))
- print(b.fly)
-
-
-# And yet another class definition that inherits from Superhero and Bat
-# superhero.py
-from superhero import Superhero
-from bat import Bat
-
-# Define Batman as a child that inherits from both Superhero and Bat
-class Batman(Superhero, Bat):
-
- def __init__(self, *args, **kwargs):
- # Typically to inherit attributes you have to call super:
- # super(Batman, self).__init__(*args, **kwargs)
- # However we are dealing with multiple inheritance here, and super()
- # only works with the next base class in the MRO list.
- # So instead we explicitly call __init__ for all ancestors.
- # The use of *args and **kwargs allows for a clean way to pass arguments,
- # with each parent "peeling a layer of the onion".
- Superhero.__init__(self, 'anonymous', movie=True,
- superpowers=['Wealthy'], *args, **kwargs)
- Bat.__init__(self, *args, can_fly=False, **kwargs)
- # override the value for the name attribute
- self.name = 'Sad Affleck'
-
- def sing(self):
- return 'nan nan nan nan nan batman!'
-
-
-if __name__ == '__main__':
- sup = Batman()
-
- # Get the Method Resolution search Order used by both getattr() and super().
- # This attribute is dynamic and can be updated
- print(Batman.__mro__) # => (<class '__main__.Batman'>,
- # => <class 'superhero.Superhero'>,
- # => <class 'human.Human'>,
- # => <class 'bat.Bat'>, <class 'object'>)
-
- # Calls parent method but uses its own class attribute
- print(sup.get_species()) # => Superhuman
-
- # Calls overridden method
- print(sup.sing()) # => nan nan nan nan nan batman!
-
- # Calls method from Human, because inheritance order matters
- sup.say('I agree') # => Sad Affleck: I agree
-
- # Call method that exists only in 2nd ancestor
- print(sup.sonar()) # => ))) ... (((
-
- # Inherited class attribute
- sup.age = 100
- print(sup.age) # => 100
-
- # Inherited attribute from 2nd ancestor whose default value was overridden.
- print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
-
-
-
-####################################################
-## 7. Advanced
-####################################################
-
-# Generators help you make lazy code.
-def double_numbers(iterable):
- for i in iterable:
- yield i + i
-
-# Generators are memory-efficient because they only load the data needed to
-# process the next value in the iterable. This allows them to perform
-# operations on otherwise prohibitively large value ranges.
-# NOTE: `range` replaces `xrange` in Python 3.
-for i in double_numbers(range(1, 900000000)): # `range` is a generator.
- print(i)
- if i >= 30:
- break
-
-# Just as you can create a list comprehension, you can create generator
-# comprehensions as well.
-values = (-x for x in [1,2,3,4,5])
-for x in values:
- print(x) # prints -1 -2 -3 -4 -5 to console/terminal
-
-# You can also cast a generator comprehension directly to a list.
-values = (-x for x in [1,2,3,4,5])
-gen_to_list = list(values)
-print(gen_to_list) # => [-1, -2, -3, -4, -5]
-
-
-# Decorators
-# In this example `beg` wraps `say`. If say_please is True then it
-# will change the returned message.
-from functools import wraps
-
-
-def beg(target_function):
- @wraps(target_function)
- def wrapper(*args, **kwargs):
- msg, say_please = target_function(*args, **kwargs)
- if say_please:
- return "{} {}".format(msg, "Please! I am poor :(")
- return msg
-
- return wrapper
-
-
-@beg
-def say(say_please=False):
- msg = "Can you buy me a beer?"
- return msg, say_please
-
-
-print(say()) # Can you buy me a beer?
-print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
-```
-
-## Ready For More?
-
-### Free Online
-
-* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Course](http://www.python-course.eu/index.php)
-* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
-* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
-* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
-* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
-* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
-* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
-* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
diff --git a/pythonlegacy.html.markdown b/pythonlegacy.html.markdown
new file mode 100644
index 00000000..95d6aa63
--- /dev/null
+++ b/pythonlegacy.html.markdown
@@ -0,0 +1,827 @@
+---
+language: Python 2 (legacy)
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Amin Bandali", "https://aminb.org"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
+ - ["asyne", "https://github.com/justblah"]
+ - ["habi", "http://github.com/habi"]
+ - ["Rommel Martinez", "https://ebzzry.io"]
+filename: learnpythonlegacy.py
+---
+
+Python was created by Guido Van Rossum in the early 90s. It is now one of the
+most popular languages in existence. I fell in love with Python for its
+syntactic clarity. It's basically executable pseudocode.
+
+Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh)
+or louiedinh [at] [google's email service]
+
+Note: This article applies to Python 2.7 specifically, but should be applicable
+to Python 2.x. Python 2.7 is reaching end of life and will stop being
+maintained in 2020, it is though recommended to start learning Python with
+Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python/).
+
+It is also possible to write Python code which is compatible with Python 2.7
+and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
+allow you to write Python 3 code that will run on Python 2, so check out the
+Python 3 tutorial.
+
+```python
+
+# Single line comments start with a number symbol.
+
+""" Multiline strings can be written
+ using three "s, and are often used
+ as comments
+"""
+
+####################################################
+# 1. Primitive Datatypes and Operators
+####################################################
+
+# You have numbers
+3 # => 3
+
+# Math is what you would expect
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7
+
+# Division is a bit tricky. It is integer division and floors the results
+# automatically.
+5 / 2 # => 2
+
+# To fix division we need to learn about floats.
+2.0 # This is a float
+11.0 / 4.0 # => 2.75 ahhh...much better
+
+# Result of integer division truncated down both for positive and negative.
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Note that we can also import division module(Section 6 Modules)
+# to carry out normal division with just one '/'.
+from __future__ import division
+
+11 / 4 # => 2.75 ...normal division
+11 // 4 # => 2 ...floored division
+
+# Modulo operation
+7 % 3 # => 1
+
+# Exponentiation (x to the yth power)
+2 ** 4 # => 16
+
+# Enforce precedence with parentheses
+(1 + 3) * 2 # => 8
+
+# Boolean Operators
+# Note "and" and "or" are case-sensitive
+True and False # => False
+False or True # => True
+
+# Note using Bool operators with ints
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
+
+# negate with not
+not True # => False
+not False # => True
+
+# Equality is ==
+1 == 1 # => True
+2 == 1 # => False
+
+# Inequality is !=
+1 != 1 # => False
+2 != 1 # => True
+
+# More comparisons
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# Comparisons can be chained!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# Strings are created with " or '
+"This is a string."
+'This is also a string.'
+
+# Strings can be added too!
+"Hello " + "world!" # => "Hello world!"
+# Strings can be added without using '+'
+"Hello " "world!" # => "Hello world!"
+
+# ... or multiplied
+"Hello" * 3 # => "HelloHelloHello"
+
+# A string can be treated like a list of characters
+"This is a string"[0] # => 'T'
+
+# You can find the length of a string
+len("This is a string") # => 16
+
+# String formatting with %
+# Even though the % string operator will be deprecated on Python 3.1 and removed
+# later at some time, it may still be good to know how it works.
+x = 'apple'
+y = 'lemon'
+z = "The items in the basket are %s and %s" % (x, y)
+
+# A newer way to format strings is the format method.
+# This method is the preferred way
+"{} is a {}".format("This", "placeholder")
+"{0} can be {1}".format("strings", "formatted")
+# You can use keywords if you don't want to count.
+"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+
+# None is an object
+None # => None
+
+# Don't use the equality "==" symbol to compare objects to None
+# Use "is" instead
+"etc" is None # => False
+None is None # => True
+
+# The 'is' operator tests for object identity. This isn't
+# very useful when dealing with primitive values, but is
+# very useful when dealing with objects.
+
+# Any object can be used in a Boolean context.
+# The following values are considered falsey:
+# - None
+# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j)
+# - empty sequences (e.g., '', (), [])
+# - empty containers (e.g., {}, set())
+# - instances of user-defined classes meeting certain conditions
+# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# All other values are truthy (using the bool() function on them returns True).
+bool(0) # => False
+bool("") # => False
+
+
+####################################################
+# 2. Variables and Collections
+####################################################
+
+# Python has a print statement
+print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+
+# Simple way to get input data from console
+input_string_var = raw_input(
+ "Enter some data: ") # Returns the data as a string
+input_var = input("Enter some data: ") # Evaluates the data as python code
+# Warning: Caution is recommended for input() method usage
+# Note: In python 3, input() is deprecated and raw_input() is renamed to input()
+
+# No need to declare variables before assigning to them.
+some_var = 5 # Convention is to use lower_case_with_underscores
+some_var # => 5
+
+# Accessing a previously unassigned variable is an exception.
+# See Control Flow to learn more about exception handling.
+some_other_var # Raises a name error
+
+# if can be used as an expression
+# Equivalent of C's '?:' ternary operator
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# Lists store sequences
+li = []
+# You can start with a prefilled list
+other_li = [4, 5, 6]
+
+# Add stuff to the end of a list with append
+li.append(1) # li is now [1]
+li.append(2) # li is now [1, 2]
+li.append(4) # li is now [1, 2, 4]
+li.append(3) # li is now [1, 2, 4, 3]
+# Remove from the end with pop
+li.pop() # => 3 and li is now [1, 2, 4]
+# Let's put it back
+li.append(3) # li is now [1, 2, 4, 3] again.
+
+# Access a list like you would any array
+li[0] # => 1
+# Assign new values to indexes that have already been initialized with =
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # Note: setting it back to the original value
+# Look at the last element
+li[-1] # => 3
+
+# Looking out of bounds is an IndexError
+li[4] # Raises an IndexError
+
+# You can look at ranges with slice syntax.
+# (It's a closed/open range for you mathy types.)
+li[1:3] # => [2, 4]
+# Omit the beginning
+li[2:] # => [4, 3]
+# Omit the end
+li[:3] # => [1, 2, 4]
+# Select every second entry
+li[::2] # =>[1, 4]
+# Reverse a copy of the list
+li[::-1] # => [3, 4, 2, 1]
+# Use any combination of these to make advanced slices
+# li[start:end:step]
+
+# Remove arbitrary elements from a list with "del"
+del li[2] # li is now [1, 2, 3]
+
+# You can add lists
+li + other_li # => [1, 2, 3, 4, 5, 6]
+# Note: values for li and for other_li are not modified.
+
+# Concatenate lists with "extend()"
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+
+# Remove first occurrence of a value
+li.remove(2) # li is now [1, 3, 4, 5, 6]
+li.remove(2) # Raises a ValueError as 2 is not in the list
+
+# Insert an element at a specific index
+li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again
+
+# Get the index of the first item found
+li.index(2) # => 1
+li.index(7) # Raises a ValueError as 7 is not in the list
+
+# Check for existence in a list with "in"
+1 in li # => True
+
+# Examine the length with "len()"
+len(li) # => 6
+
+# Tuples are like lists but are immutable.
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # Raises a TypeError
+
+# You can do all those list thingies on tuples too
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# You can unpack tuples (or lists) into variables
+a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+d, e, f = 4, 5, 6 # you can leave out the parentheses
+# Tuples are created by default if you leave out the parentheses
+g = 4, 5, 6 # => (4, 5, 6)
+# Now look how easy it is to swap two values
+e, d = d, e # d is now 5 and e is now 4
+
+# Dictionaries store mappings
+empty_dict = {}
+# Here is a prefilled dictionary
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Look up values with []
+filled_dict["one"] # => 1
+
+# Get all keys as a list with "keys()"
+filled_dict.keys() # => ["three", "two", "one"]
+# Note - Dictionary key ordering is not guaranteed.
+# Your results might not match this exactly.
+
+# Get all values as a list with "values()"
+filled_dict.values() # => [3, 2, 1]
+# Note - Same as above regarding key ordering.
+
+# Get all key-value pairs as a list of tuples with "items()"
+filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)]
+
+# Check for existence of keys in a dictionary with "in"
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# Looking up a non-existing key is a KeyError
+filled_dict["four"] # KeyError
+
+# Use "get()" method to avoid the KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# The get method supports a default argument when the value is missing
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+# note that filled_dict.get("four") is still => None
+# (get doesn't set the value in the dictionary)
+
+# set the value of a key with a syntax similar to lists
+filled_dict["four"] = 4 # now, filled_dict["four"] => 4
+
+# "setdefault()" inserts into a dictionary only if the given key isn't present
+filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
+
+# You can declare sets (which are like unordered lists that cannot contain
+# duplicate values) using the set object.
+empty_set = set()
+# Initialize a "set()" with a bunch of values
+some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4])
+
+# order is not guaranteed, even though it may sometimes look sorted
+another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4])
+
+# Since Python 2.7, {} can be used to declare a set
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# Add more items to a set
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+
+# Do set intersection with &
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# Do set union with |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# Do set difference with -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# Do set symmetric difference with ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Check if set on the left is a superset of set on the right
+{1, 2} >= {1, 2, 3} # => False
+
+# Check if set on the left is a subset of set on the right
+{1, 2} <= {1, 2, 3} # => True
+
+# Check for existence in a set with in
+2 in filled_set # => True
+10 in filled_set # => False
+10 not in filled_set # => True
+
+# Check data type of variable
+type(li) # => list
+type(filled_dict) # => dict
+type(5) # => int
+
+
+####################################################
+# 3. Control Flow
+####################################################
+
+# Let's just make a variable
+some_var = 5
+
+# Here is an if statement. Indentation is significant in python!
+# prints "some_var is smaller than 10"
+if some_var > 10:
+ print "some_var is totally bigger than 10."
+elif some_var < 10: # This elif clause is optional.
+ print "some_var is smaller than 10."
+else: # This is optional too.
+ print "some_var is indeed 10."
+
+"""
+For loops iterate over lists
+prints:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ # You can use {0} to interpolate formatted strings. (See above.)
+ print "{0} is a mammal".format(animal)
+
+"""
+"range(number)" returns a list of numbers
+from zero to the given number
+prints:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+"range(lower, upper)" returns a list of numbers
+from the lower number to the upper number
+prints:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print i
+
+"""
+While loops go until a condition is no longer met.
+prints:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Shorthand for x = x + 1
+
+# Handle exceptions with a try/except block
+
+# Works on Python 2.6 and up:
+try:
+ # Use "raise" to raise an error
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # Pass is just a no-op. Usually you would do recovery here.
+except (TypeError, NameError):
+ pass # Multiple exceptions can be handled together, if required.
+else: # Optional clause to the try/except block. Must follow all except blocks
+ print "All good!" # Runs only if the code in try raises no exceptions
+finally: # Execute under all circumstances
+ print "We can clean up resources here"
+
+# Instead of try/finally to cleanup resources you can use a with statement
+with open("myfile.txt") as f:
+ for line in f:
+ print line
+
+
+####################################################
+# 4. Functions
+####################################################
+
+# Use "def" to create new functions
+def add(x, y):
+ print "x is {0} and y is {1}".format(x, y)
+ return x + y # Return values with a return statement
+
+
+# Calling functions with parameters
+add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
+
+# Another way to call functions is with keyword arguments
+add(y=6, x=5) # Keyword arguments can arrive in any order.
+
+
+# You can define functions that take a variable number of
+# positional args, which will be interpreted as a tuple by using *
+def varargs(*args):
+ return args
+
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+
+# You can define functions that take a variable number of
+# keyword args, as well, which will be interpreted as a dict by using **
+def keyword_args(**kwargs):
+ return kwargs
+
+
+# Let's call it to see what happens
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# You can do both at once, if you like
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+
+
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# When calling functions, you can do the opposite of args/kwargs!
+# Use * to expand positional args and use ** to expand keyword args.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4)
+
+
+# you can pass args and kwargs along to other functions that take args/kwargs
+# by expanding them with * and ** respectively
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
+
+# Function Scope
+x = 5
+
+
+def set_x(num):
+ # Local var x not the same as global variable x
+ x = num # => 43
+ print x # => 43
+
+
+def set_global_x(num):
+ global x
+ print x # => 5
+ x = num # global var x is now set to 6
+ print x # => 6
+
+
+set_x(43)
+set_global_x(6)
+
+
+# Python has first class functions
+def create_adder(x):
+ def adder(y):
+ return x + y
+
+ return adder
+
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# There are also anonymous functions
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# There are built-in higher order functions
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# We can use list comprehensions for nice maps and filters
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+# You can construct set and dict comprehensions as well.
+{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}
+{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
+
+####################################################
+# 5. Classes
+####################################################
+
+# We subclass from object to get a class.
+class Human(object):
+ # A class attribute. It is shared by all instances of this class
+ species = "H. sapiens"
+
+ # Basic initializer, this is called when this class is instantiated.
+ # Note that the double leading and trailing underscores denote objects
+ # or attributes that are used by python but that live in user-controlled
+ # namespaces. You should not invent such names on your own.
+ def __init__(self, name):
+ # Assign the argument to the instance's name attribute
+ self.name = name
+
+ # Initialize property
+ self.age = 0
+
+ # An instance method. All methods take "self" as the first argument
+ def say(self, msg):
+ return "{0}: {1}".format(self.name, msg)
+
+ # A class method is shared among all instances
+ # They are called with the calling class as the first argument
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # A static method is called without a class or instance reference
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # A property is just like a getter.
+ # It turns the method age() into an read-only attribute
+ # of the same name.
+ @property
+ def age(self):
+ return self._age
+
+ # This allows the property to be set
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # This allows the property to be deleted
+ @age.deleter
+ def age(self):
+ del self._age
+
+
+# Instantiate a class
+i = Human(name="Ian")
+print i.say("hi") # prints out "Ian: hi"
+
+j = Human("Joel")
+print j.say("hello") # prints out "Joel: hello"
+
+# Call our class method
+i.get_species() # => "H. sapiens"
+
+# Change the shared attribute
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# Call the static method
+Human.grunt() # => "*grunt*"
+
+# Update the property
+i.age = 42
+
+# Get the property
+i.age # => 42
+
+# Delete the property
+del i.age
+i.age # => raises an AttributeError
+
+####################################################
+# 6. Modules
+####################################################
+
+# You can import modules
+import math
+
+print math.sqrt(16) # => 4.0
+
+# You can get specific functions from a module
+from math import ceil, floor
+
+print ceil(3.7) # => 4.0
+print floor(3.7) # => 3.0
+
+# You can import all functions from a module.
+# Warning: this is not recommended
+from math import *
+
+# You can shorten module names
+import math as m
+
+math.sqrt(16) == m.sqrt(16) # => True
+# you can also test that the functions are equivalent
+from math import sqrt
+
+math.sqrt == m.sqrt == sqrt # => True
+
+# Python modules are just ordinary python files. You
+# can write your own, and import them. The name of the
+# module is the same as the name of the file.
+
+# You can find out which functions and attributes
+# defines a module.
+import math
+
+dir(math)
+
+
+# If you have a Python script named math.py in the same
+# folder as your current script, the file math.py will
+# be loaded instead of the built-in Python module.
+# This happens because the local folder has priority
+# over Python's built-in libraries.
+
+
+####################################################
+# 7. Advanced
+####################################################
+
+# Generators
+# A generator "generates" values as they are requested instead of storing
+# everything up front
+
+# The following method (*NOT* a generator) will double all values and store it
+# in `double_arr`. For large size of iterables, that might get huge!
+def double_numbers(iterable):
+ double_arr = []
+ for i in iterable:
+ double_arr.append(i + i)
+ return double_arr
+
+
+# Running the following would mean we'll double all values first and return all
+# of them back to be checked by our condition
+for value in double_numbers(range(1000000)): # `test_non_generator`
+ print value
+ if value > 5:
+ break
+
+
+# We could instead use a generator to "generate" the doubled value as the item
+# is being requested
+def double_numbers_generator(iterable):
+ for i in iterable:
+ yield i + i
+
+
+# Running the same code as before, but with a generator, now allows us to iterate
+# over the values and doubling them one by one as they are being consumed by
+# our logic. Hence as soon as we see a value > 5, we break out of the
+# loop and don't need to double most of the values sent in (MUCH FASTER!)
+for value in double_numbers_generator(xrange(1000000)): # `test_generator`
+ print value
+ if value > 5:
+ break
+
+# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`?
+# Just as `double_numbers_generator` is the generator version of `double_numbers`
+# We have `xrange` as the generator version of `range`
+# `range` would return back and array with 1000000 values for us to use
+# `xrange` would generate 1000000 values for us as we request / iterate over those items
+
+# Just as you can create a list comprehension, you can create generator
+# comprehensions as well.
+values = (-x for x in [1, 2, 3, 4, 5])
+for x in values:
+ print(x) # prints -1 -2 -3 -4 -5 to console/terminal
+
+# You can also cast a generator comprehension directly to a list.
+values = (-x for x in [1, 2, 3, 4, 5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
+# Decorators
+# A decorator is a higher order function, which accepts and returns a function.
+# Simple usage example – add_apples decorator will add 'Apple' element into
+# fruits list returned by get_fruits target function.
+def add_apples(func):
+ def get_fruits():
+ fruits = func()
+ fruits.append('Apple')
+ return fruits
+ return get_fruits
+
+@add_apples
+def get_fruits():
+ return ['Banana', 'Mango', 'Orange']
+
+# Prints out the list of fruits with 'Apple' element in it:
+# Banana, Mango, Orange, Apple
+print ', '.join(get_fruits())
+
+# in this example beg wraps say
+# Beg will call say. If say_please is True then it will change the returned
+# message
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print say() # Can you buy me a beer?
+print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
+```
+
+## Ready For More?
+
+### Free Online
+
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [LearnPython](http://www.learnpython.org/)
+* [Fullstack Python](https://www.fullstackpython.com/)
+
+### Dead Tree
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/pythonlegacy-ro.html.markdown
index ada0c034..a368ff99 100644
--- a/ro-ro/python-ro.html.markdown
+++ b/ro-ro/pythonlegacy-ro.html.markdown
@@ -1,10 +1,10 @@
---
-language: python
+language: Python 2 (legacy)
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
translators:
- ["Ovidiu Ciule", "https://github.com/ociule"]
-filename: learnpython-ro.py
+filename: learnpythonlegacy-ro.py
lang: ro-ro
---
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 6087a686..b2c00baf 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -1,23 +1,23 @@
---
-language: python
+language: Python
lang: ru-ru
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
+ - ["Steven Basart", "http://github.com/xksteven"]
translators:
- - ["Yury Timofeev", "http://twitter.com/gagar1n"]
- ["Andre Polykanine", "https://github.com/Oire"]
filename: learnpython-ru.py
---
Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из
самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это
-почти исполняемый псевдокод.
+почти что исполняемый псевдокод.
С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh)
или louiedinh [at] [почтовый сервис Google]
-Замечание: Эта статья относится к Python 2.7, но должно работать и в других версиях Python 2.x.
-Чтобы изучить Python 3.x, обратитесь к статье по Python 3.
+Замечание: Эта статья относится только к Python 3.
+Если вы хотите изучить Python 2.7, обратитесь к другой статье.
```python
# Однострочные комментарии начинаются с символа решётки.
@@ -37,16 +37,9 @@ filename: learnpython-ru.py
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
-35 / 5 #=> 7
-# А вот деление немного сложнее. В этом случае происходит деление
-# целых чисел, и результат автоматически округляется в меньшую сторону.
-5 / 2 #=> 2
-
-# Чтобы делить правильно, сначала нужно немного узнать о числах
-# с плавающей запятой.
-2.0 # Это число с плавающей запятой
-11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше
+# Кроме деления, которое по умолчанию возвращает число с плавающей запятой
+35 / 5 # => 7.0
# Результат целочисленного деления округляется в меньшую сторону
# как для положительных, так и для отрицательных чисел.
@@ -55,6 +48,10 @@ filename: learnpython-ru.py
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
+# Когда вы используете числа с плавающей запятой,
+# результатом будет также число с плавающей запятой
+3 * 2.0 # => 6.0
+
# Остаток от деления
7 % 3 # => 1
@@ -64,6 +61,14 @@ filename: learnpython-ru.py
# Приоритет операций указывается скобками
(1 + 3) * 2 #=> 8
+# Для логических (булевых) значений существует отдельный примитивный тип
+True
+False
+
+# Для отрицания используется ключевое слово not
+not True #=> False
+not False #=> True
+
# Логические операторы
# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв
True and False #=> False
@@ -76,10 +81,6 @@ False or True #=> True
2 == True #=> False
1 == True #=> True
-# Для отрицания используется ключевое слово not
-not True #=> False
-not False #=> True
-
# Равенство — это ==
1 == 1 #=> True
2 == 1 #=> False
@@ -94,7 +95,7 @@ not False #=> True
2 <= 2 #=> True
2 >= 2 #=> True
-# Сравнения могут быть записаны цепочкой!
+# Сравнения могут быть записаны цепочкой:
1 < 2 < 3 #=> True
2 < 3 < 2 #=> False
@@ -102,75 +103,70 @@ not False #=> True
"Это строка."
'Это тоже строка.'
-# И строки тоже можно складывать!
+# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим.
"Привет " + "мир!" #=> "Привет мир!"
-# ... или умножать
-"Привет" * 3 # => "ПриветПриветПривет"
+# Строки можно умножать.
+"aa" * 4 #=> "aaaaaaaa"
# Со строкой можно работать, как со списком символов
"Это строка"[0] #=> 'Э'
-# Символ % используется для форматирования строк, например:
-"%s могут быть %s" % ("строки", "интерполированы")
-
-# Новый способ форматирования строк — использование метода format.
-# Это предпочитаемый способ.
+# Метод format используется для форматирования строк:
"{0} могут быть {1}".format("строки", "форматированы")
+# Вы можете повторять аргументы форматирования, чтобы меньше печатать.
+"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак")
+#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!"
# Если вы не хотите считать, можете использовать ключевые слова.
"{name} хочет есть {food}".format(name="Боб", food="лазанью")
+# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже,
+# вы также можете использовать старый способ форматирования:
+"%s можно %s %s способом" % ("строки", "интерполировать", "старым")
+
# None является объектом
None #=> None
-# Не используйте оператор равенства '=='' для сравнения
-# объектов с None. Используйте для этого «is»
+# Не используйте оператор равенства '==' для сравнения
+# объектов с None. Используйте для этого 'is'
"etc" is None #=> False
None is None #=> True
-# Оператор 'is' проверяет идентичность объектов. Он не
+# Оператор «is» проверяет идентичность объектов. Он не
# очень полезен при работе с примитивными типами, но
# зато просто незаменим при работе с объектами.
-# None, 0 и пустые строки/списки равны False.
+# None, 0 и пустые строки/списки/словари приводятся к False.
# Все остальные значения равны True
-0 == False #=> True
-"" == False #=> True
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
####################################################
## 2. Переменные и коллекции
####################################################
-# В Python есть оператор print, доступный в версиях 2.x, но удалённый в версии 3
-print "Я Python. Приятно познакомиться!"
-# В Python также есть функция print(), доступная в версиях 2.7 и 3,
-# Но для версии 2.7 нужно добавить следующий импорт модуля (раскомментируйте)):
-# from __future__ import print_function
-print("Я тоже Python! ")
+# В Python есть функция Print
+print("Я Python. Приятно познакомиться!")
# Объявлять переменные перед инициализацией не нужно.
-some_var = 5 # По соглашению используется нижний_регистр_с_подчёркиваниями
+# По соглашению используется нижний_регистр_с_подчёркиваниями
+some_var = 5
some_var #=> 5
# При попытке доступа к неинициализированной переменной
# выбрасывается исключение.
-# См. раздел «Поток управления» для информации об исключениях.
-some_other_var # Выбрасывает ошибку именования
-
-# if может быть использован как выражение
-"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+# Об исключениях см. раздел «Поток управления и итерируемые объекты».
+some_unknown_var # Выбрасывает ошибку именования
# Списки хранят последовательности
li = []
# Можно сразу начать с заполненного списка
other_li = [4, 5, 6]
-# строка разделена в список
-a="adambard"
-list(a) #=> ['a','d','a','m','b','a','r','d']
-
# Объекты добавляются в конец списка методом append
li.append(1) # [1]
li.append(2) # [1, 2]
@@ -183,10 +179,6 @@ li.append(3) # [1, 2, 4, 3].
# Обращайтесь со списком, как с обычным массивом
li[0] #=> 1
-# Присваивайте новые значения уже инициализированным индексам с помощью =
-li[0] = 42
-li[0] # => 42
-li[0] = 1 # Обратите внимание: возвращаемся на исходное значение
# Обратимся к последнему элементу
li[-1] #=> 3
@@ -208,11 +200,11 @@ li[::-1] # => [3, 4, 2, 1]
# li[начало:конец:шаг]
# Удаляем произвольные элементы из списка оператором del
-del li[2] # li теперь [1, 2, 3]
+del li[2] # [1, 2, 3]
# Вы можете складывать, или, как ещё говорят, конкатенировать списки
-li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются
# Обратите внимание: значения li и other_li при этом не изменились.
+li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются
# Объединять списки можно методом extend
li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
@@ -242,6 +234,7 @@ d, e, f = 4, 5, 6
# Обратите внимание, как легко поменять местами значения двух переменных
e, d = d, e # теперь d == 5, а e == 4
+
# Словари содержат ассоциативные массивы
empty_dict = {}
# Вот так описывается предзаполненный словарь
@@ -251,13 +244,17 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# что индекс — у словарей он называется ключом — не обязан быть числом
filled_dict["one"] #=> 1
-# Можно получить все ключи в виде списка с помощью метода keys
-filled_dict.keys() #=> ["three", "two", "one"]
+# Все ключи в виде списка получаются с помощью метода keys().
+# Его вызов нужно обернуть в list(), так как обратно мы получаем
+# итерируемый объект, о которых поговорим позднее.
+list(filled_dict.keys()) # => ["three", "two", "one"]
# Замечание: сохранение порядка ключей в словаре не гарантируется
# Ваши результаты могут не совпадать с этими.
-# Можно получить и все значения в виде списка, используйте метод values
-filled_dict.values() #=> [3, 2, 1]
+# Все значения в виде списка можно получить с помощью values().
+# И снова нам нужно обернуть вызов в list(), чтобы превратить
+# итерируемый объект в список.
+list(filled_dict.values()) # => [3, 2, 1]
# То же самое замечание насчёт порядка ключей справедливо и здесь
# При помощи оператора in можно проверять ключи на вхождение в словарь
@@ -274,29 +271,28 @@ filled_dict.get("four") #=> None
# возвращено при отсутствии указанного ключа
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
-# Обратите внимание, что filled_dict.get("four") всё ещё => None
-# (get не устанавливает значение элемента словаря)
-
-# Присваивайте значение ключам так же, как и в списках
-filled_dict["four"] = 4 # теперь filled_dict["four"] => 4
-# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет
+# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет
filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
+# Добавление элементов в словарь
+filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 # Другой способ добавления элементов
-# Множества содержат... ну, в общем, множества
-# (которые похожи на списки, только в них не может быть дублирующихся элементов)
-empty_set = set()
-# Инициализация множества набором значений
-some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4])
+# Удаляйте ключи из словаря с помощью оператора del
+del filled_dict["one"] # Удаляет ключ «one» из словаря
-# Порядок сортировки не гарантируется, хотя иногда они выглядят отсортированными
-another_set = set([4, 3, 2, 2, 1]) # another_set теперь set([1, 2, 3, 4])
-# Начиная с Python 2.7, вы можете использовать {}, чтобы объявить множество
+# Множества содержат... ну, в общем, множества
+empty_set = set()
+# Инициализация множества набором значений.
+# Да, оно выглядит примерно как словарь… ну извините, так уж вышло.
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+# Множеству можно назначать новую переменную
+filled_set = some_set
+
# Добавление новых элементов в множество
filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5}
@@ -316,7 +312,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
####################################################
-## 3. Поток управления
+## 3. Поток управления и итерируемые объекты
####################################################
# Для начала заведём переменную
@@ -332,17 +328,13 @@ else: # Это тоже необязательно.
print("some_var равно 10.")
-"""
-Циклы For проходят по спискам
-
-Результат:
- собака — это млекопитающее
- кошка — это млекопитающее
- мышь — это млекопитающее
-"""
+# Циклы For проходят по спискам. Результат:
+ # собака — это млекопитающее
+ # кошка — это млекопитающее
+ # мышь — это млекопитающее
for animal in ["собака", "кошка", "мышь"]:
- # Можете использовать оператор % для интерполяции форматированных строк
- print("%s — это млекопитающее" % animal)
+ # Можете использовать format() для интерполяции форматированных строк
+ print("{} — это млекопитающее".format(animal))
"""
«range(число)» возвращает список чисел
@@ -370,8 +362,6 @@ while x < 4:
x += 1 # Краткая запись для x = x + 1
# Обрабатывайте исключения блоками try/except
-
-# Работает в Python 2.6 и выше:
try:
# Чтобы выбросить ошибку, используется raise
raise IndexError("Это ошибка индекса")
@@ -384,6 +374,37 @@ except (TypeError, NameError):
else: # Необязательное выражение. Должно следовать за последним блоком except
print("Всё хорошо!") # Выполнится, только если не было никаких исключений
+# Python предоставляет фундаментальную абстракцию,
+# которая называется итерируемым объектом (an iterable).
+# Итерируемый объект — это объект, который воспринимается как последовательность.
+# Объект, который возвратила функция range(), итерируемый.
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable
+
+# Мы можем проходить по нему циклом.
+for i in our_iterable:
+ print(i) # Выводит one, two, three
+
+# Но мы не можем обращаться к элементу по индексу.
+our_iterable[1] # Выбрасывает ошибку типа
+
+# Итерируемый объект знает, как создавать итератор.
+our_iterator = iter(our_iterable)
+
+# Итератор может запоминать состояние при проходе по объекту.
+# Мы получаем следующий объект, вызывая функцию __next__.
+our_iterator.__next__() #=> "one"
+
+# Он сохраняет состояние при вызове __next__.
+our_iterator.__next__() #=> "two"
+our_iterator.__next__() #=> "three"
+
+# Возвратив все данные, итератор выбрасывает исключение StopIterator
+our_iterator.__next__() # Выбрасывает исключение остановки итератора
+
+# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list().
+list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"]
####################################################
@@ -401,8 +422,7 @@ add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвр
# Другой способ вызова функции — вызов с именованными аргументами
add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке.
-# Вы можете определить функцию, принимающую переменное число аргументов,
-# которые будут интерпретированы как кортеж, если вы не используете *
+# Вы можете определить функцию, принимающую переменное число аргументов
def varargs(*args):
return args
@@ -410,8 +430,7 @@ varargs(1, 2, 3) #=> (1,2,3)
# А также можете определить функцию, принимающую переменное число
-# именованных аргументов, которые будут интерпретированы как словарь,
-# если вы не используете **
+# именованных аргументов
def keyword_args(**kwargs):
return kwargs
@@ -436,14 +455,6 @@ all_the_args(*args) # эквивалентно foo(1, 2, 3, 4)
all_the_args(**kwargs) # эквивалентно foo(a=3, b=4)
all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4)
-# вы можете передавать переменное число позиционных или именованных аргументов
-# другим функциям, которые их принимают, распаковывая их с помощью
-# * или ** соответственно
-def pass_all_the_args(*args, **kwargs):
- all_the_args(*args, **kwargs)
- print varargs(*args)
- print keyword_args(**kwargs)
-
# Область определения функций
x = 5
@@ -502,7 +513,7 @@ class Human(object):
# Метод экземпляра. Все методы принимают self в качестве первого аргумента
def say(self, msg):
- return "%s: %s" % (self.name, msg)
+ return "{name}: {message}".format(name=self.name, message=msg)
# Метод класса разделяется между всеми экземплярами
# Они вызываются с указыванием вызывающего класса в качестве первого аргумента
@@ -555,9 +566,6 @@ from math import *
# Можете сокращать имена модулей
import math as m
math.sqrt(16) == m.sqrt(16) #=> True
-# Вы также можете убедиться, что функции эквивалентны
-from math import sqrt
-math.sqrt == m.sqrt == sqrt # => True
# Модули в Python — это обычные Python-файлы. Вы
# можете писать свои модули и импортировать их. Название
@@ -581,15 +589,14 @@ def double_numbers(iterable):
# Он не возвращает все значения разом, а создаёт каждое из них при каждой
# итерации. Это значит, что значения больше 15 в double_numbers
# обработаны не будут.
-# Обратите внимание: xrange — это генератор, который делает то же, что и range.
+# Обратите внимание: range — это тоже генератор.
# Создание списка чисел от 1 до 900000000 требует много места и времени.
-# xrange создаёт объект генератора, а не список сразу, как это делает range.
# Если нам нужно имя переменной, совпадающее с ключевым словом Python,
# мы используем подчёркивание в конце
-xrange_ = xrange(1, 900000000)
+range_ = range(1, 900000000)
# Будет удваивать все числа, пока результат не превысит 30
-for i in double_numbers(xrange_):
+for i in double_numbers(range_):
print(i)
if i >= 30:
break
@@ -630,9 +637,10 @@ print(say(say_please=True)) # Вы не купите мне пива? Пожал
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [Официальная документация](http://docs.python.org/2.6/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [Официальная документация](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
+* [Python Module of the Week](http://pymotw.com/3/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
### Платные
diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/pythonlegacy-ru.html.markdown
index bf80fed2..ead2af3d 100644
--- a/ru-ru/python3-ru.html.markdown
+++ b/ru-ru/pythonlegacy-ru.html.markdown
@@ -1,23 +1,23 @@
---
-language: python3
+language: Python 2 (legacy)
lang: ru-ru
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- - ["Steven Basart", "http://github.com/xksteven"]
translators:
+ - ["Yury Timofeev", "http://twitter.com/gagar1n"]
- ["Andre Polykanine", "https://github.com/Oire"]
-filename: learnpython3-ru.py
+filename: learnpythonlegacy-ru.py
---
Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из
самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это
-почти что исполняемый псевдокод.
+почти исполняемый псевдокод.
С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh)
или louiedinh [at] [почтовый сервис Google]
-Замечание: Эта статья относится только к Python 3.
-Если вы хотите изучить Python 2.7, обратитесь к другой статье.
+Замечание: Эта статья относится к Python 2.7, но должно работать и в других версиях Python 2.x.
+Чтобы изучить Python 3.x, обратитесь к статье по Python 3.
```python
# Однострочные комментарии начинаются с символа решётки.
@@ -37,9 +37,16 @@ filename: learnpython3-ru.py
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
+35 / 5 #=> 7
-# Кроме деления, которое по умолчанию возвращает число с плавающей запятой
-35 / 5 # => 7.0
+# А вот деление немного сложнее. В этом случае происходит деление
+# целых чисел, и результат автоматически округляется в меньшую сторону.
+5 / 2 #=> 2
+
+# Чтобы делить правильно, сначала нужно немного узнать о числах
+# с плавающей запятой.
+2.0 # Это число с плавающей запятой
+11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше
# Результат целочисленного деления округляется в меньшую сторону
# как для положительных, так и для отрицательных чисел.
@@ -48,10 +55,6 @@ filename: learnpython3-ru.py
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
-# Когда вы используете числа с плавающей запятой,
-# результатом будет также число с плавающей запятой
-3 * 2.0 # => 6.0
-
# Остаток от деления
7 % 3 # => 1
@@ -61,14 +64,6 @@ filename: learnpython3-ru.py
# Приоритет операций указывается скобками
(1 + 3) * 2 #=> 8
-# Для логических (булевых) значений существует отдельный примитивный тип
-True
-False
-
-# Для отрицания используется ключевое слово not
-not True #=> False
-not False #=> True
-
# Логические операторы
# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв
True and False #=> False
@@ -81,6 +76,10 @@ False or True #=> True
2 == True #=> False
1 == True #=> True
+# Для отрицания используется ключевое слово not
+not True #=> False
+not False #=> True
+
# Равенство — это ==
1 == 1 #=> True
2 == 1 #=> False
@@ -95,7 +94,7 @@ False or True #=> True
2 <= 2 #=> True
2 >= 2 #=> True
-# Сравнения могут быть записаны цепочкой:
+# Сравнения могут быть записаны цепочкой!
1 < 2 < 3 #=> True
2 < 3 < 2 #=> False
@@ -103,70 +102,75 @@ False or True #=> True
"Это строка."
'Это тоже строка.'
-# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим.
+# И строки тоже можно складывать!
"Привет " + "мир!" #=> "Привет мир!"
-# Строки можно умножать.
-"aa" * 4 #=> "aaaaaaaa"
+# ... или умножать
+"Привет" * 3 # => "ПриветПриветПривет"
# Со строкой можно работать, как со списком символов
"Это строка"[0] #=> 'Э'
-# Метод format используется для форматирования строк:
+# Символ % используется для форматирования строк, например:
+"%s могут быть %s" % ("строки", "интерполированы")
+
+# Новый способ форматирования строк — использование метода format.
+# Это предпочитаемый способ.
"{0} могут быть {1}".format("строки", "форматированы")
-# Вы можете повторять аргументы форматирования, чтобы меньше печатать.
-"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак")
-#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!"
# Если вы не хотите считать, можете использовать ключевые слова.
"{name} хочет есть {food}".format(name="Боб", food="лазанью")
-# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже,
-# вы также можете использовать старый способ форматирования:
-"%s можно %s %s способом" % ("строки", "интерполировать", "старым")
-
# None является объектом
None #=> None
-# Не используйте оператор равенства '==' для сравнения
-# объектов с None. Используйте для этого 'is'
+# Не используйте оператор равенства '=='' для сравнения
+# объектов с None. Используйте для этого «is»
"etc" is None #=> False
None is None #=> True
-# Оператор «is» проверяет идентичность объектов. Он не
+# Оператор 'is' проверяет идентичность объектов. Он не
# очень полезен при работе с примитивными типами, но
# зато просто незаменим при работе с объектами.
-# None, 0 и пустые строки/списки/словари приводятся к False.
+# None, 0 и пустые строки/списки равны False.
# Все остальные значения равны True
-bool(0) # => False
-bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
+0 == False #=> True
+"" == False #=> True
####################################################
## 2. Переменные и коллекции
####################################################
-# В Python есть функция Print
-print("Я Python. Приятно познакомиться!")
+# В Python есть оператор print, доступный в версиях 2.x, но удалённый в версии 3
+print "Я Python. Приятно познакомиться!"
+# В Python также есть функция print(), доступная в версиях 2.7 и 3,
+# Но для версии 2.7 нужно добавить следующий импорт модуля (раскомментируйте)):
+# from __future__ import print_function
+print("Я тоже Python! ")
# Объявлять переменные перед инициализацией не нужно.
-# По соглашению используется нижний_регистр_с_подчёркиваниями
-some_var = 5
+some_var = 5 # По соглашению используется нижний_регистр_с_подчёркиваниями
some_var #=> 5
# При попытке доступа к неинициализированной переменной
# выбрасывается исключение.
-# Об исключениях см. раздел «Поток управления и итерируемые объекты».
-some_unknown_var # Выбрасывает ошибку именования
+# См. раздел «Поток управления» для информации об исключениях.
+some_other_var # Выбрасывает ошибку именования
+
+# if может быть использован как выражение
+"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
# Списки хранят последовательности
li = []
# Можно сразу начать с заполненного списка
other_li = [4, 5, 6]
+# строка разделена в список
+a="adambard"
+list(a) #=> ['a','d','a','m','b','a','r','d']
+
# Объекты добавляются в конец списка методом append
li.append(1) # [1]
li.append(2) # [1, 2]
@@ -179,6 +183,10 @@ li.append(3) # [1, 2, 4, 3].
# Обращайтесь со списком, как с обычным массивом
li[0] #=> 1
+# Присваивайте новые значения уже инициализированным индексам с помощью =
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # Обратите внимание: возвращаемся на исходное значение
# Обратимся к последнему элементу
li[-1] #=> 3
@@ -200,11 +208,11 @@ li[::-1] # => [3, 4, 2, 1]
# li[начало:конец:шаг]
# Удаляем произвольные элементы из списка оператором del
-del li[2] # [1, 2, 3]
+del li[2] # li теперь [1, 2, 3]
# Вы можете складывать, или, как ещё говорят, конкатенировать списки
-# Обратите внимание: значения li и other_li при этом не изменились.
li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются
+# Обратите внимание: значения li и other_li при этом не изменились.
# Объединять списки можно методом extend
li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
@@ -234,7 +242,6 @@ d, e, f = 4, 5, 6
# Обратите внимание, как легко поменять местами значения двух переменных
e, d = d, e # теперь d == 5, а e == 4
-
# Словари содержат ассоциативные массивы
empty_dict = {}
# Вот так описывается предзаполненный словарь
@@ -244,17 +251,13 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# что индекс — у словарей он называется ключом — не обязан быть числом
filled_dict["one"] #=> 1
-# Все ключи в виде списка получаются с помощью метода keys().
-# Его вызов нужно обернуть в list(), так как обратно мы получаем
-# итерируемый объект, о которых поговорим позднее.
-list(filled_dict.keys()) # => ["three", "two", "one"]
+# Можно получить все ключи в виде списка с помощью метода keys
+filled_dict.keys() #=> ["three", "two", "one"]
# Замечание: сохранение порядка ключей в словаре не гарантируется
# Ваши результаты могут не совпадать с этими.
-# Все значения в виде списка можно получить с помощью values().
-# И снова нам нужно обернуть вызов в list(), чтобы превратить
-# итерируемый объект в список.
-list(filled_dict.values()) # => [3, 2, 1]
+# Можно получить и все значения в виде списка, используйте метод values
+filled_dict.values() #=> [3, 2, 1]
# То же самое замечание насчёт порядка ключей справедливо и здесь
# При помощи оператора in можно проверять ключи на вхождение в словарь
@@ -271,27 +274,28 @@ filled_dict.get("four") #=> None
# возвращено при отсутствии указанного ключа
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
+# Обратите внимание, что filled_dict.get("four") всё ещё => None
+# (get не устанавливает значение элемента словаря)
+
+# Присваивайте значение ключам так же, как и в списках
+filled_dict["four"] = 4 # теперь filled_dict["four"] => 4
-# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет
+# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет
filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
-# Добавление элементов в словарь
-filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
-#filled_dict["four"] = 4 # Другой способ добавления элементов
-
-# Удаляйте ключи из словаря с помощью оператора del
-del filled_dict["one"] # Удаляет ключ «one» из словаря
-
# Множества содержат... ну, в общем, множества
+# (которые похожи на списки, только в них не может быть дублирующихся элементов)
empty_set = set()
-# Инициализация множества набором значений.
-# Да, оно выглядит примерно как словарь… ну извините, так уж вышло.
-filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+# Инициализация множества набором значений
+some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4])
-# Множеству можно назначать новую переменную
-filled_set = some_set
+# Порядок сортировки не гарантируется, хотя иногда они выглядят отсортированными
+another_set = set([4, 3, 2, 2, 1]) # another_set теперь set([1, 2, 3, 4])
+
+# Начиная с Python 2.7, вы можете использовать {}, чтобы объявить множество
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
# Добавление новых элементов в множество
filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5}
@@ -312,7 +316,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
####################################################
-## 3. Поток управления и итерируемые объекты
+## 3. Поток управления
####################################################
# Для начала заведём переменную
@@ -328,13 +332,17 @@ else: # Это тоже необязательно.
print("some_var равно 10.")
-# Циклы For проходят по спискам. Результат:
- # собака — это млекопитающее
- # кошка — это млекопитающее
- # мышь — это млекопитающее
+"""
+Циклы For проходят по спискам
+
+Результат:
+ собака — это млекопитающее
+ кошка — это млекопитающее
+ мышь — это млекопитающее
+"""
for animal in ["собака", "кошка", "мышь"]:
- # Можете использовать format() для интерполяции форматированных строк
- print("{} — это млекопитающее".format(animal))
+ # Можете использовать оператор % для интерполяции форматированных строк
+ print("%s — это млекопитающее" % animal)
"""
«range(число)» возвращает список чисел
@@ -362,6 +370,8 @@ while x < 4:
x += 1 # Краткая запись для x = x + 1
# Обрабатывайте исключения блоками try/except
+
+# Работает в Python 2.6 и выше:
try:
# Чтобы выбросить ошибку, используется raise
raise IndexError("Это ошибка индекса")
@@ -374,37 +384,6 @@ except (TypeError, NameError):
else: # Необязательное выражение. Должно следовать за последним блоком except
print("Всё хорошо!") # Выполнится, только если не было никаких исключений
-# Python предоставляет фундаментальную абстракцию,
-# которая называется итерируемым объектом (an iterable).
-# Итерируемый объект — это объект, который воспринимается как последовательность.
-# Объект, который возвратила функция range(), итерируемый.
-filled_dict = {"one": 1, "two": 2, "three": 3}
-our_iterable = filled_dict.keys()
-print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable
-
-# Мы можем проходить по нему циклом.
-for i in our_iterable:
- print(i) # Выводит one, two, three
-
-# Но мы не можем обращаться к элементу по индексу.
-our_iterable[1] # Выбрасывает ошибку типа
-
-# Итерируемый объект знает, как создавать итератор.
-our_iterator = iter(our_iterable)
-
-# Итератор может запоминать состояние при проходе по объекту.
-# Мы получаем следующий объект, вызывая функцию __next__.
-our_iterator.__next__() #=> "one"
-
-# Он сохраняет состояние при вызове __next__.
-our_iterator.__next__() #=> "two"
-our_iterator.__next__() #=> "three"
-
-# Возвратив все данные, итератор выбрасывает исключение StopIterator
-our_iterator.__next__() # Выбрасывает исключение остановки итератора
-
-# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list().
-list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"]
####################################################
@@ -422,7 +401,8 @@ add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвр
# Другой способ вызова функции — вызов с именованными аргументами
add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке.
-# Вы можете определить функцию, принимающую переменное число аргументов
+# Вы можете определить функцию, принимающую переменное число аргументов,
+# которые будут интерпретированы как кортеж, если вы не используете *
def varargs(*args):
return args
@@ -430,7 +410,8 @@ varargs(1, 2, 3) #=> (1,2,3)
# А также можете определить функцию, принимающую переменное число
-# именованных аргументов
+# именованных аргументов, которые будут интерпретированы как словарь,
+# если вы не используете **
def keyword_args(**kwargs):
return kwargs
@@ -455,6 +436,14 @@ all_the_args(*args) # эквивалентно foo(1, 2, 3, 4)
all_the_args(**kwargs) # эквивалентно foo(a=3, b=4)
all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4)
+# вы можете передавать переменное число позиционных или именованных аргументов
+# другим функциям, которые их принимают, распаковывая их с помощью
+# * или ** соответственно
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
# Область определения функций
x = 5
@@ -513,7 +502,7 @@ class Human(object):
# Метод экземпляра. Все методы принимают self в качестве первого аргумента
def say(self, msg):
- return "{name}: {message}".format(name=self.name, message=msg)
+ return "%s: %s" % (self.name, msg)
# Метод класса разделяется между всеми экземплярами
# Они вызываются с указыванием вызывающего класса в качестве первого аргумента
@@ -566,6 +555,9 @@ from math import *
# Можете сокращать имена модулей
import math as m
math.sqrt(16) == m.sqrt(16) #=> True
+# Вы также можете убедиться, что функции эквивалентны
+from math import sqrt
+math.sqrt == m.sqrt == sqrt # => True
# Модули в Python — это обычные Python-файлы. Вы
# можете писать свои модули и импортировать их. Название
@@ -589,14 +581,15 @@ def double_numbers(iterable):
# Он не возвращает все значения разом, а создаёт каждое из них при каждой
# итерации. Это значит, что значения больше 15 в double_numbers
# обработаны не будут.
-# Обратите внимание: range — это тоже генератор.
+# Обратите внимание: xrange — это генератор, который делает то же, что и range.
# Создание списка чисел от 1 до 900000000 требует много места и времени.
+# xrange создаёт объект генератора, а не список сразу, как это делает range.
# Если нам нужно имя переменной, совпадающее с ключевым словом Python,
# мы используем подчёркивание в конце
-range_ = range(1, 900000000)
+xrange_ = xrange(1, 900000000)
# Будет удваивать все числа, пока результат не превысит 30
-for i in double_numbers(range_):
+for i in double_numbers(xrange_):
print(i)
if i >= 30:
break
@@ -637,10 +630,9 @@ print(say(say_please=True)) # Вы не купите мне пива? Пожал
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [Официальная документация](http://docs.python.org/3/)
+* [Официальная документация](http://docs.python.org/2.6/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/3/)
+* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
### Платные
diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown
index 99a3eb4e..6d9cdcbe 100644
--- a/tr-tr/python-tr.html.markdown
+++ b/tr-tr/python-tr.html.markdown
@@ -1,316 +1,344 @@
---
-language: python
-filename: learnpython-tr.py
+language: Python
contributors:
- - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Batuhan Osman T.", "https://github.com/BTaskaya"]
translators:
- - ["Haydar KULEKCI", "http://scanf.info/"]
+ - ["Eray AYDIN", "http://erayaydin.me/"]
lang: tr-tr
+filename: learnpython-tr.py
---
-Python Guido Van Rossum tarafından 90'ların başında yaratılmıştır. Şu anda
-varolanlar arasında en iyi dillerden birisidir. Ben (Louie Dinh) Python
-dilinin syntax'ının belirginliğine aşığım. O basit olarak çalıştırılabilir
-pseudocode'dur.
-Geri bildirimlerden son derece mutluluk duyarım! Bana [@louiedinh](http://twitter.com/louiedinh)
-adresinden ya da louiedinh [at] [google's email service] adresinden ulaşabilirsiniz.
+Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur.
-Çeviri için geri bildirimleri de [@kulekci](http://twitter.com/kulekci)
-adresine yapabilirsiniz.
+Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/pythonlegacy/) kontrol edebilirsiniz.
-Not: Bu yazıdaki özellikler Python 2.7 için geçerlidir, ama Python 2.x için de
-uygulanabilir. Python 3 için başka bir zaman tekrar bakınız.
+```python
+# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır.
-```python
-# Tek satır yorum hash işareti ile başlar.
-""" Çoklu satır diziler üç tane çift tırnak
- arasında yazılır. Ve yorum olarak da
- kullanılabilir
+""" Çok satırlı olmasını istediğiniz yorumlar
+ üç adet tırnak(") işareti ile
+ yapılmaktadır
"""
-
####################################################
-## 1. İlkel Veri Tipleri ve Operatörler
+## 1. Temel Veri Türleri ve Operatörler
####################################################
# Sayılar
-3 #=> 3
+3 # => 3
+
+# Tahmin edebileceğiniz gibi matematik
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+
+# Bölme işlemi varsayılan olarak onluk döndürür
+35 / 5 # => 7.0
+
+# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
-# Matematik beklediğiniz gibi
-1 + 1 #=> 2
-8 - 1 #=> 7
-10 * 2 #=> 20
-35 / 5 #=> 7
+# Onluk kullanırsanız, sonuç da onluk olur
+3 * 2.0 # => 6.0
-# Bölünme biraz ilginç. EĞer tam sayılar üzerinde bölünme işlemi yapıyorsanız
-# sonuç otomatik olarak kırpılır.
-5 / 2 #=> 2
+# Kalan operatörü
+7 % 3 # => 1
-# Bölünme işlemini düzenlemek için kayan noktalı sayıları bilmeniz gerekir.
-2.0 # Bu bir kayan noktalı sayı
-11.0 / 4.0 #=> 2.75 ahhh...daha iyi
+# Üs (2 üzeri 4)
+2**4 # => 16
-# İşlem önceliğini parantezler ile sağlayabilirsiniz.
-(1 + 3) * 2 #=> 8
+# Parantez ile önceliği değiştirebilirsiniz
+(1 + 3) * 2 # => 8
-# Boolean değerleri bilindiği gibi
+# Boolean(Doğru-Yanlış) değerleri standart
True
False
-# not ile nagatif(mantıksal) değerini alma
-not True #=> False
-not False #=> True
+# 'değil' ile terse çevirme
+not True # => False
+not False # => True
-# Eşitlik ==
-1 == 1 #=> True
-2 == 1 #=> False
+# Boolean Operatörleri
+# "and" ve "or" büyük küçük harf duyarlıdır
+True and False #=> False
+False or True #=> True
-# Eşitsizlik !=
-1 != 1 #=> False
-2 != 1 #=> True
+# Bool operatörleri ile sayı kullanımı
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
-# Daha fazla karşılaştırma
-1 < 10 #=> True
-1 > 10 #=> False
-2 <= 2 #=> True
-2 >= 2 #=> True
+# Eşitlik kontrolü ==
+1 == 1 # => True
+2 == 1 # => False
-# Karşılaştırma zincirleme yapılabilir!
-1 < 2 < 3 #=> True
-2 < 3 < 2 #=> False
+# Eşitsizlik Kontrolü !=
+1 != 1 # => False
+2 != 1 # => True
-# Karakter dizisi " veya ' ile oluşturulabilir
-"This is a string."
-'This is also a string.'
+# Diğer karşılaştırmalar
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
-# Karakter dizileri birbirleri ile eklenebilir
-"Hello " + "world!" #=> "Hello world!"
+# Zincirleme şeklinde karşılaştırma da yapabilirsiniz!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
-# A string can be treated like a list of characters
-# Bir string'e karakter listesi gibi davranabilirsiniz.
-"This is a string"[0] #=> 'T'
+# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir
+"Bu bir yazı."
+'Bu da bir yazı.'
-# % karakter dizisini(string) formatlamak için kullanılır, bunun gibi:
-"%s can be %s" % ("strings", "interpolated")
+# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem.
+"Merhaba " + "dünya!" # => "Merhaba dünya!"
-# String'leri formatlamanın yeni bir yöntem ise format metodudur.
-# Bu metod tercih edilen yöntemdir.
-"{0} can be {1}".format("strings", "formatted")
-# Eğer saymak istemiyorsanız anahtar kelime kullanabilirsiniz.
-"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+# Bir yazı(string) karakter listesi gibi işlenebilir
+"Bu bir yazı"[0] # => 'B'
-# None bir objedir
-None #=> None
+# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde:
+"{} da ayrıca {}".format("yazılar", "işlenebilir")
-# "==" eşitliğini non objesi ile karşılaştırmak için kullanmayın.
-# Onun yerine "is" kullanın.
-"etc" is None #=> False
-None is None #=> True
+# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz.
+"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu")
+#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir"
-# 'is' operatörü obje kimliği için test etmektedir. Bu ilkel değerler
-# için kullanışlı değildir, ama objeleri karşılaştırmak için kullanışlıdır.
+# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz.
+"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor"
-# None, 0 ve boş string/list'ler False olarak değerlendirilir.
-# Tüm eşitlikler True döner
-0 == False #=> True
-"" == False #=> True
+# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız,
+# eski stil formatlamayı kullanabilirsiniz:
+"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir")
-####################################################
-## 2. Değişkenler ve Kolleksiyonlar
-####################################################
+# Hiçbir şey(none) da bir objedir
+None # => None
-# Ekrana yazdırma oldukça kolaydır.
-print "I'm Python. Nice to meet you!"
+# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın
+# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir.
+"vb" is None # => False
+None is None # => True
+# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü.
+# Diğer veriler ise True değeri döndürür
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
-# Değişkenlere bir değer atamadan önce tanımlamaya gerek yoktur.
-some_var = 5 # Değişken isimlerinde gelenek küçük karakter ve alt çizgi
- # kullanmaktır.
-some_var #=> 5
-# Daha önceden tanımlanmamış ya da assign edilmemeiş bir değişkene erişmeye
-# çalıştığınızda bir hata fırlatılacaktır. Hata ayıklama hakkında daha fazla
-# bilgi için kontrol akışı kısmına göz atınız.
-some_other_var # isim hatası fırlatılır
+####################################################
+## 2. Değişkenler ve Koleksiyonlar
+####################################################
-# isterseniz "if"i bir ifade gibi kullanabilirsiniz.
-"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+# Python bir yazdırma fonksiyonuna sahip
+print("Ben Python. Tanıştığıma memnun oldum!")
-# Listeler
+# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok.
+# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin
+bir_degisken = 5
+bir_degisken # => 5
+
+# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır.
+# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz.
+bir_bilinmeyen_degisken # NameError hatası oluşturur
+
+# Listeler ile sıralamaları tutabilirsiniz
li = []
-# Önceden değerleri tanımlanmış listeler
-other_li = [4, 5, 6]
-
-# Bir listenin sonuna birşeyler eklemek
-li.append(1) #li şu anda [1]
-li.append(2) #li şu anda [1, 2]
-li.append(4) #li şu anda [1, 2, 4]
-li.append(3) #li şu anda [1, 2, 4, 3]
-# pop ile sondan birşeyler silmek
-li.pop() #=> 3 and li is now [1, 2, 4]
-# Tekrar sonuna eklemek
-li.append(3) # li is now [1, 2, 4, 3] again.
-
-# Dizi gibi listenin elemanlarına erişmek
-li[0] #=> 1
-# Son elemanın değerine ulaşmak
-li[-1] #=> 3
-
-# Listede bulunmayan bir index'teki elemana erişirken "IndexError" hatası
-# fırlatılır
-li[4] # IndexError fırlatılır
-
-# slice syntax'ı ile belli aralıktakı değerlere bakabilirsiniz.
-# (Açık ve kapalı aralıklıdır.)
-li[1:3] #=> [2, 4]
-# Başlangıcı ihmal etme
-li[2:] #=> [4, 3]
-# Sonu ihmal etme
-li[:3] #=> [1, 2, 4]
-
-# "del" ile istenilen bir elemanı listeden silmek
-del li[2] # li is now [1, 2, 3]
-
-# Listeleri birbiri ile birleştirebilirsiniz.
-li + other_li #=> [1, 2, 3, 4, 5, 6] - Not: li ve other_li yanlız bırakılır
-
-# extend ile listeleri birleştirmek
-li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
-
-# bir değerin liste içerisinde varlığını "in" ile kontrol etmek
-1 in li #=> True
-
-# "len" ile listenin uzunluğunu bulmak
-len(li) #=> 6
-
-# Tüpler listeler gibidir sadece değişmezler(immutable)
+# Önceden doldurulmuş listeler ile başlayabilirsiniz
+diger_li = [4, 5, 6]
+
+# 'append' ile listenin sonuna ekleme yapabilirsiniz
+li.append(1) # li artık [1] oldu
+li.append(2) # li artık [1, 2] oldu
+li.append(4) # li artık [1, 2, 4] oldu
+li.append(3) # li artık [1, 2, 4, 3] oldu
+# 'pop' ile listenin son elementini kaldırabilirsiniz
+li.pop() # => 3 ve li artık [1, 2, 4]
+# Çıkarttığımız tekrardan ekleyelim
+li.append(3) # li yeniden [1, 2, 4, 3] oldu.
+
+# Dizi gibi listeye erişim sağlayın
+li[0] # => 1
+# Son elemente bakın
+li[-1] # => 3
+
+# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur
+li[4] # IndexError hatası oluşturur
+
+# Bir kısmını almak isterseniz.
+li[1:3] # => [2, 4]
+# Başlangıç belirtmezseniz
+li[2:] # => [4, 3]
+# Sonu belirtmesseniz
+li[:3] # => [1, 2, 4]
+# Her ikişer objeyi seçme
+li[::2] # =>[1, 4]
+# Listeyi tersten almak
+li[::-1] # => [3, 4, 2, 1]
+# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz
+# li[baslangic:son:adim]
+
+# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz
+del li[2] # li artık [1, 2, 3] oldu
+
+# Listelerde de ekleme yapabilirsiniz
+# Not: değerler üzerinde değişiklik yapılmaz.
+li + diger_li # => [1, 2, 3, 4, 5, 6]
+
+# Listeleri birbirine bağlamak için "extend()" kullanılabilir
+li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu
+
+# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir
+1 in li # => True
+
+# Uzunluğu öğrenmek için "len()" kullanılabilir
+len(li) # => 6
+
+
+# Tüpler listeler gibidir fakat değiştirilemez.
tup = (1, 2, 3)
-tup[0] #=> 1
-tup[0] = 3 # TypeError fırlatılır.
-
-# Litelerde yapılanların hepsini tüplerde de yapılabilir
-len(tup) #=> 3
-tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
-tup[:2] #=> (1, 2)
-2 in tup #=> True
-
-# Tüplerin(veya listelerin) içerisindeki değerleri değişkenelere
-# atanabilir
-a, b, c = (1, 2, 3) # a şu anda 1, b şu anda 2 ve c şu anda 3
-# Eğer parantez kullanmaz iseniz tüpler varsayılan olarak oluşturulur
+tup[0] # => 1
+tup[0] = 3 # TypeError hatası oluşturur
+
+# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Tüpleri(veya listeleri) değişkenlere açabilirsiniz
+a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3
+# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur
d, e, f = 4, 5, 6
-# şimdi iki değeri değiş tokuş etmek çok kolaydır.
-e, d = d, e # d şimdi 5 ve e şimdi 4
+# 2 değeri birbirine değiştirmek bu kadar kolay
+e, d = d, e # 'd' artık 5 ve 'e' artık 4
+
+# Sözlükler anahtar kodlarla verileri tutar
+bos_sozl = {}
+# Önceden doldurulmuş sözlük oluşturma
+dolu_sozl = {"bir": 1, "iki": 2, "uc": 3}
-# Sözlükler (Dictionaries) key-value saklanır.
-empty_dict = {}
-# Sözlüklere önceden değer atama örneği
-filled_dict = {"one": 1, "two": 2, "three": 3}
+# Değere bakmak için [] kullanalım
+dolu_sozl["bir"] # => 1
-# Değere ulaşmak için [] kullanılır
-filled_dict["one"] #=> 1
+# Bütün anahtarları almak için "keys()" kullanılabilir.
+# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz.
+# Not - Sözlük anahtarlarının sıralaması kesin değildir.
+# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir.
+list(dolu_sozl.keys()) # => ["uc", "iki", "bir"]
-# Tüm anahtarlara(key) "keys()" metodu ile ulaşılır
-filled_dict.keys() #=> ["three", "two", "one"]
-# Not - Sözlüklerin anahtarlarının sıralı geleceği garanti değildir
-# Sonuçlarınız değer listesini aldığınızda tamamen eşleşmeyebilir
-# Tüm değerleri almak için "values()" kullanabilirsiniz.
-filled_dict.values() #=> [3, 2, 1]
-# Not - Sıralama ile ilgili anahtarlar ile aynı durum geçerlidir.
+# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor
+# Not - Sıralama değişebilir.
+list(dolu_sozl.values()) # => [3, 2, 1]
-# Bir anahtarın sözlükte oluş olmadığını "in" ile kontrol edilebilir
-"one" in filled_dict #=> True
-1 in filled_dict #=> False
-# Olmayan bir anahtar çağrıldığında KeyError fırlatılır.
-filled_dict["four"] # KeyError
+# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz
+"bir" in dolu_sozl # => True
+1 in dolu_sozl # => False
-# "get()" metodu KeyError fırlatılmasını önler
-filled_dict.get("one") #=> 1
-filled_dict.get("four") #=> None
-# get() metodu eğer anahtar mevcut değilse varsayılan bir değer atama
-# imknaı sağlar.
-filled_dict.get("one", 4) #=> 1
-filled_dict.get("four", 4) #=> 4
+# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır.
+dolu_sozl["dort"] # KeyError hatası oluşturur
-# "setdefault()" metodu sözlüğe yeni bir key-value eşleşmesi eklemenin
-# güvenli bir yoludur.
-filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5
-filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5
+# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz
+dolu_sozl.get("bir") # => 1
+dolu_sozl.get("dort") # => None
+# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz.
+dolu_sozl.get("bir", 4) # => 1
+dolu_sozl.get("dort", 4) # => 4
+# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır
+dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip
+dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip
-# Sets store ... well sets
-empty_set = set()
-# Bir demek değer ile bir "set" oluşturmak
-some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4])
+# Sözlüğe ekleme
+dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4}
+#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu
-# Python 2.7'den beri {}'ler bir "set" tanımlaman için kullanılabilir
-filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+# Sözlükten anahtar silmek için 'del' kullanılabilir
+del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir
-# Bir set'e daha fazla eleman eklemek
-filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
-# "&" işareti ile iki set'in kesişimlerini alınabilir
-other_set = {3, 4, 5, 6}
-filled_set & other_set #=> {3, 4, 5}
+# Setler ... set işte :D
+bos_set = set()
+# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm.
+bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4}
-# | işareti ile
-filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+# Sete yeni setler ekleyebilirsiniz
+dolu_set = bir_set
-# "-" işareti ile iki set'in farkları alınabilir
-{1,2,3,4} - {2,3,5} #=> {1, 4}
+# Sete bir diğer öğe ekleme
+dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu
-# "in" ile değerin set içerisinde olup olmadığını kontrol edebilirsiniz
-2 in filled_set #=> True
-10 in filled_set #=> False
+# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz
+diger_set = {3, 4, 5, 6}
+dolu_set & diger_set # => {3, 4, 5}
+
+# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz
+dolu_set | diger_set # => {1, 2, 3, 4, 5, 6}
+
+# Farklılıkları almak için "-" kullanabilirsiniz
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir
+2 in dolu_set # => True
+10 in dolu_set # => False
####################################################
-## 3. Akış Denetimi
+## 3. Kontrol Akışları ve Temel Soyutlandırma
####################################################
-# Bir değişken oluşturmak
-some_var = 5
+# Bir değişken oluşturalım
+bir_degisken = 5
-# Buradaki bir if ifadesi. Girintiler(Intentation) Python'da önemlidir!
-# "some_var is smaller than 10" yazdırılır.
-if some_var > 10:
- print "some_var is totally bigger than 10."
-elif some_var < 10: # elif ifadesi isteğe bağlıdır
- print "some_var is smaller than 10."
-else: # Bu da isteğe bağlıdır.
- print "some_var is indeed 10."
+# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir!
+# çıktı olarak "bir_degisken 10 dan küçük" yazar
+if bir_degisken > 10:
+ print("bir_degisken 10 dan büyük")
+elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir.
+ print("bir_degisken 10 dan küçük")
+else: # Bu ifade de zorunlu değil.
+ print("bir_degisken değeri 10")
"""
-For döngüleri listeler üzerinde iterasyon yapar
-Ekrana yazdırılan:
- dog is a mammal
- cat is a mammal
- mouse is a mammal
+Döngülerle lsiteleri döngüye alabilirsiniz
+çıktı:
+ köpek bir memeli hayvandır
+ kedi bir memeli hayvandır
+ fare bir memeli hayvandır
"""
-for animal in ["dog", "cat", "mouse"]:
- # Biçimlendirmeleri string'e katmak için % kullanabilirsiniz
- print "%s is a mammal" % animal
-
+for hayvan in ["köpek", "kedi, "fare"]:
+ # format ile kolayca yazıyı biçimlendirelim
+ print("{} bir memeli hayvandır".format(hayvan))
+
"""
-"range(number)" ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner
-Ekrana yazdırılan:
+"range(sayi)" bir sayı listesi döndür
+0'dan belirttiğiniz sayıyıa kadar
+çıktı:
0
1
2
3
"""
for i in range(4):
- print i
+ print(i)
"""
-While döngüsü koşul sağlanmayana kadar devam eder
-Ekrana yazdırılan:
+'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir.
+çıktı:
0
1
2
@@ -318,185 +346,295 @@ Ekrana yazdırılan:
"""
x = 0
while x < 4:
- print x
- x += 1 # Shorthand for x = x + 1
-
-# try/except bloğu ile hatalar ayıklanabilir
+ print(x)
+ x += 1 # Uzun hali x = x + 1
-# Python 2.6 ve üstü için çalışacaktır:
+# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz
try:
- # "raise" bir hata fırlatmak için kullanılabilir
- raise IndexError("This is an index error")
+ # Bir hata oluşturmak için "raise" kullanabilirsiniz
+ raise IndexError("Bu bir index hatası")
except IndexError as e:
- pass # Pass is just a no-op. Usually you would do recovery here.
+ pass # Önemsiz, devam et.
+except (TypeError, NameError):
+ pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse.
+else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır
+ print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı
+
+# Temel Soyutlandırma, bir objenin işlenmiş halidir.
+# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi.
+
+dolu_sozl = {"bir": 1, "iki": 2, "uc": 3}
+temel_soyut = dolu_sozl.keys()
+print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu
+
+# Temel Soyutlandırılmış objeyi döngüye sokabiliriz.
+for i in temel_soyut:
+ print(i) # Çıktısı: bir, iki, uc
+
+# Fakat, elementin anahtarına değerine.
+temel_soyut[1] # TypeError hatası!
+
+# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır.
+iterator = iter(temel_soyut)
+
+# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır
+# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz.
+iterator.__next__() #=> "bir"
+
+# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir
+iterator.__next__() #=> "iki"
+iterator.__next__() #=> "uc"
+
+# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır.
+iterator.__next__() # StopIteration hatası
+
+# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz.
+list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"]
####################################################
## 4. Fonksiyonlar
####################################################
+# "def" ile yeni fonksiyonlar oluşturabilirsiniz
+def topla(x, y):
+ print("x = {} ve y = {}".format(x, y))
+ return x + y # Değer döndürmek için 'return' kullanmalısınız
-# Yeni bir fonksiyon oluşturmak için "def" kullanılır
-def add(x, y):
- print "x is %s and y is %s" % (x, y)
- return x + y # Return values with a return statement
+# Fonksiyonu parametleri ile çağırıyoruz
+topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür
-# Fonksiyonu parametre ile çağırmak
-add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11
+# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek
+topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz.
-# Diğer bir yol fonksiyonları anahtar argümanları ile çağırmak
-add(y=6, x=5) # Anahtar argümanlarının sırası farklı da olabilir
+# Sınırsız sayıda argüman da alabilirsiniz
+def argumanlar(*argumanlar):
+ return argumanlar
-# Değişken sayıda parametresi olan bir fonksiyon tanımlayabilirsiniz
-def varargs(*args):
- return args
+argumanlar(1, 2, 3) # => (1, 2, 3)
-varargs(1, 2, 3) #=> (1,2,3)
+# Parametrelerin anahtar değerlerini almak isterseniz
+def anahtar_par(**anahtarlar):
+ return anahtar
-# Değişken sayıda anahtar argümanlı parametre alan fonksiyonlar da
-# tanımlayabilirsiniz.
-def keyword_args(**kwargs):
- return kwargs
+# Çalıştırdığımızda
+anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"}
-# Şu şekilde kullanılacaktır
-keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
-# Eğer isterseniz ikisini aynı anda da yapabilirsiniz
-def all_the_args(*args, **kwargs):
- print args
- print kwargs
+# İsterseniz, bu ikisini birden kullanabilirsiniz
+def tum_argumanlar(*argumanlar, **anahtarla):
+ print(argumanlar)
+ print(anahtarla)
"""
-all_the_args(1, 2, a=3, b=4) prints:
+tum_argumanlar(1, 2, a=3, b=4) çıktı:
(1, 2)
{"a": 3, "b": 4}
"""
-# Fonksiyonu çağırırken, args/kwargs'ın tam tersini de yapabilirsiniz!
-# Tüpü yaymak için * ve kwargs'ı yaymak için ** kullanın.
-args = (1, 2, 3, 4)
-kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # foo(1, 2, 3, 4) ile eşit
-all_the_args(**kwargs) # foo(a=3, b=4) ile eşit
-all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4) ile eşit
-
-# Python first-class fonksiyonlara sahiptir
-def create_adder(x):
- def adder(y):
- return x + y
- return adder
+# Fonksiyonu çağırırken de aynısını kullanabilirsiniz
+argumanlar = (1, 2, 3, 4)
+anahtarla = {"a": 3, "b": 4}
+tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4)
+tum_argumanlar(**anahtarla) # = foo(a=3, b=4)
+tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4)
+
+
+# Fonksiyonlarda kullanacağımız bir değişken oluşturalım
+x = 5
+
+def belirleX(sayi):
+ # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil
+ x = sayi # => 43
+ print (x) # => 43
+
+def globalBelirleX(sayi):
+ global x
+ print (x) # => 5
+ x = sayi # global olan x değişkeni artık 6
+ print (x) # => 6
+
+belirleX(43)
+globalBelirleX(6)
-add_10 = create_adder(10)
-add_10(3) #=> 13
-# Anonymous fonksiyonlar da vardır
-(lambda x: x > 2)(3) #=> True
+# Sınıf fonksiyonları oluşturma
+def toplama_olustur(x):
+ def topla(y):
+ return x + y
+ return topla
+
+ekle_10 = toplama_olustur(10)
+ekle_10(3) # => 13
-# Dahili yüksek seviye fonksiyonlar vardır
-map(add_10, [1,2,3]) #=> [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+# Bilinmeyen fonksiyon
+(lambda x: x > 2)(3) # => True
-# Map etme(maps) ve filtreleme(filtres) için liste kullanabiliriz.
-[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+# TODO - Fix for iterables
+# Belirli sayıdan yükseğini alma fonksiyonu
+map(ekle_10, [1, 2, 3]) # => [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+# Filtreleme işlemi için liste comprehensions da kullanabiliriz
+[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Sınıflar
####################################################
-# We subclass from object to get a class.
-class Human(object):
-
- # Bir sınıf özelliği. Bu sınıfın tüm "instance"larına paylaşılmıştır.
- species = "H. sapiens"
-
- # Basic initializer
- def __init__(self, name):
- # Metoda gelen argümanın değerini sınıfın elemanı olan "name"
- # değişkenine atama
- self.name = name
-
- # Bir instance metodu. Tüm metodlar ilk argüman olarak "self"
- # parametresini alır
- def say(self, msg):
- return "%s: %s" % (self.name, msg)
-
- # Bir sınıf metodu tüm "instance"lar arasında paylaşılır
- # İlk argüman olarak sınıfı çağırarak çağrılırlar
+
+# Sınıf oluşturmak için objeden alt sınıf oluşturacağız.
+class Insan(object):
+
+ # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir
+ tur = "H. sapiens"
+
+ # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir.
+ # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar
+ # python tarafından tanımlanan isimlerdir.
+ # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız!
+ def __init__(self, isim):
+ # Parametreyi sınıfın değerine atayalım
+ self.isim = isim
+
+ # Bir metot. Bütün metotlar ilk parametre olarak "self "alır.
+ def soyle(self, mesaj):
+ return "{isim}: {mesaj}".format(isim=self.isim, mesaj=mesaj)
+
+ # Bir sınıf metotu bütün nesnelere paylaştırılır
+ # İlk parametre olarak sınıf alırlar
@classmethod
- def get_species(cls):
- return cls.species
+ def getir_tur(snf):
+ return snf.tur
- # Bir statik metod bir sınıf ya da instance referansı olmadan çağrılır
+ # Bir statik metot, sınıf ve nesnesiz çağrılır
@staticmethod
def grunt():
return "*grunt*"
-# Bir sınıf örneği oluşturmak
-i = Human(name="Ian")
-print i.say("hi") # "Ian: hi" çıktısı verir
+# Sınıfı çağıralım
+i = Insan(isim="Ahmet")
+print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba"
-j = Human("Joel")
-print j.say("hello") # "Joel: hello" çıktısı verir
+j = Insan("Ali")
+print(j.soyle("selam")) # çıktı "Ali: selam"
-# Sınıf metodunu çağıralım
-i.get_species() #=> "H. sapiens"
+# Sınıf metodumuzu çağıraim
+i.getir_tur() # => "H. sapiens"
-# Paylaşılan sınıf özellik değiştirelim.
-Human.species = "H. neanderthalensis"
-i.get_species() #=> "H. neanderthalensis"
-j.get_species() #=> "H. neanderthalensis"
+# Paylaşılan değeri değiştirelim
+Insan.tur = "H. neanderthalensis"
+i.getir_tur() # => "H. neanderthalensis"
+j.getir_tur() # => "H. neanderthalensis"
-# Statik metodu çağırma
-Human.grunt() #=> "*grunt*"
+# Statik metodumuzu çağıralım
+Insan.grunt() # => "*grunt*"
####################################################
-## 6. Modüller
+## 6. Moduller
####################################################
-# Modülleri sayfaya dahil edebilirsiniz
+# Modülleri içe aktarabilirsiniz
import math
-print math.sqrt(16) #=> 4.0
+print(math.sqrt(16)) # => 4.0
-# Modül içerisinden spesifik bir fonksiyonu getirebilirsiniz
+# Modülden belirli bir fonksiyonları alabilirsiniz
from math import ceil, floor
-print ceil(3.7) #=> 4.0
-print floor(3.7) #=> 3.0
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
-# Modüldeki tüm fonksiyonları dahil edebilirsiniz
-# Uyarı: bu önerilmez
+# Modüldeki tüm fonksiyonları içe aktarabilirsiniz
+# Dikkat: bunu yapmanızı önermem.
from math import *
-# Modülün adını kısaltabilirsiniz
+# Modül isimlerini değiştirebilirsiniz.
+# Not: Modül ismini kısaltmanız çok daha iyi olacaktır
import math as m
-math.sqrt(16) == m.sqrt(16) #=> True
+math.sqrt(16) == m.sqrt(16) # => True
-# Python modülleri sıradan python dosyalarıdır. Kendinize bir modül
-# yazabilirsiniz, ve dahil edebilirsiniz. Modülün adı ile dosya adı
-# aynı olmalıdır.
+# Python modulleri aslında birer python dosyalarıdır.
+# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün
+# ismi ile dosyanın ismi aynı olacaktır.
-# Modüllerde tanımlanmış fonksiyon ve metodları öğrenebilirsiniz.
+# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz.
import math
dir(math)
+####################################################
+## 7. Gelişmiş
+####################################################
+
+# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır
+def kare_sayilar(nesne):
+ for i in nesne:
+ yield i + i
+
+# Bir oluşturucu(generator) değerleri anında oluşturur.
+# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan
+# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük
+# değerler işlenmeyecektir.
+# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda
+# çok fazla vakit alacaktır.
+# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir.
+range_ = range(1, 900000000)
+# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım
+for i in kare_sayilar(range_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# Dekoratörler
+# Bu örnekte,
+# Eğer lutfen_soyle True ise dönen değer değişecektir.
+from functools import wraps
+
+def yalvar(hedef_fonksiyon):
+ @wraps(hedef_fonksiyon)
+ def metot(*args, **kwargs):
+ msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs)
+ if lutfen_soyle:
+ return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(")
+ return msj
+
+ return metot
+
+
+@yalvar
+def soyle(lutfen_soyle=False):
+ msj = "Bana soda alır mısın?"
+ return msj, lutfen_soyle
+
+
+print(soyle()) # Bana soda alır mısın?
+print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :(
```
-## Daha fazlası için hazır mısınız?
+## Daha Fazlasına Hazır Mısınız?
-### Ücretsiz Dökümanlar
+### Ücretsiz Online
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2.6/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [Python Course](http://www.python-course.eu/index.php)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
+* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
-### Dead Tree
+### Kitaplar
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown
deleted file mode 100644
index b78d517f..00000000
--- a/tr-tr/python3-tr.html.markdown
+++ /dev/null
@@ -1,640 +0,0 @@
----
-language: python3
-contributors:
- - ["Louie Dinh", "http://pythonpracticeprojects.com"]
- - ["Steven Basart", "http://github.com/xksteven"]
- - ["Andre Polykanine", "https://github.com/Oire"]
- - ["Batuhan Osman T.", "https://github.com/BTaskaya"]
-translators:
- - ["Eray AYDIN", "http://erayaydin.me/"]
-lang: tr-tr
-filename: learnpython3-tr.py
----
-
-Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur.
-
-Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz.
-
-```python
-
-# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır.
-
-""" Çok satırlı olmasını istediğiniz yorumlar
- üç adet tırnak(") işareti ile
- yapılmaktadır
-"""
-
-####################################################
-## 1. Temel Veri Türleri ve Operatörler
-####################################################
-
-# Sayılar
-3 # => 3
-
-# Tahmin edebileceğiniz gibi matematik
-1 + 1 # => 2
-8 - 1 # => 7
-10 * 2 # => 20
-
-# Bölme işlemi varsayılan olarak onluk döndürür
-35 / 5 # => 7.0
-
-# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
-
-# Onluk kullanırsanız, sonuç da onluk olur
-3 * 2.0 # => 6.0
-
-# Kalan operatörü
-7 % 3 # => 1
-
-# Üs (2 üzeri 4)
-2**4 # => 16
-
-# Parantez ile önceliği değiştirebilirsiniz
-(1 + 3) * 2 # => 8
-
-# Boolean(Doğru-Yanlış) değerleri standart
-True
-False
-
-# 'değil' ile terse çevirme
-not True # => False
-not False # => True
-
-# Boolean Operatörleri
-# "and" ve "or" büyük küçük harf duyarlıdır
-True and False #=> False
-False or True #=> True
-
-# Bool operatörleri ile sayı kullanımı
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
-
-# Eşitlik kontrolü ==
-1 == 1 # => True
-2 == 1 # => False
-
-# Eşitsizlik Kontrolü !=
-1 != 1 # => False
-2 != 1 # => True
-
-# Diğer karşılaştırmalar
-1 < 10 # => True
-1 > 10 # => False
-2 <= 2 # => True
-2 >= 2 # => True
-
-# Zincirleme şeklinde karşılaştırma da yapabilirsiniz!
-1 < 2 < 3 # => True
-2 < 3 < 2 # => False
-
-# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir
-"Bu bir yazı."
-'Bu da bir yazı.'
-
-# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem.
-"Merhaba " + "dünya!" # => "Merhaba dünya!"
-
-# Bir yazı(string) karakter listesi gibi işlenebilir
-"Bu bir yazı"[0] # => 'B'
-
-# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde:
-"{} da ayrıca {}".format("yazılar", "işlenebilir")
-
-# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz.
-"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu")
-#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir"
-
-# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz.
-"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor"
-
-# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız,
-# eski stil formatlamayı kullanabilirsiniz:
-"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir")
-
-
-# Hiçbir şey(none) da bir objedir
-None # => None
-
-# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın
-# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir.
-"vb" is None # => False
-None is None # => True
-
-# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü.
-# Diğer veriler ise True değeri döndürür
-bool(0) # => False
-bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
-
-
-####################################################
-## 2. Değişkenler ve Koleksiyonlar
-####################################################
-
-# Python bir yazdırma fonksiyonuna sahip
-print("Ben Python. Tanıştığıma memnun oldum!")
-
-# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok.
-# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin
-bir_degisken = 5
-bir_degisken # => 5
-
-# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır.
-# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz.
-bir_bilinmeyen_degisken # NameError hatası oluşturur
-
-# Listeler ile sıralamaları tutabilirsiniz
-li = []
-# Önceden doldurulmuş listeler ile başlayabilirsiniz
-diger_li = [4, 5, 6]
-
-# 'append' ile listenin sonuna ekleme yapabilirsiniz
-li.append(1) # li artık [1] oldu
-li.append(2) # li artık [1, 2] oldu
-li.append(4) # li artık [1, 2, 4] oldu
-li.append(3) # li artık [1, 2, 4, 3] oldu
-# 'pop' ile listenin son elementini kaldırabilirsiniz
-li.pop() # => 3 ve li artık [1, 2, 4]
-# Çıkarttığımız tekrardan ekleyelim
-li.append(3) # li yeniden [1, 2, 4, 3] oldu.
-
-# Dizi gibi listeye erişim sağlayın
-li[0] # => 1
-# Son elemente bakın
-li[-1] # => 3
-
-# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur
-li[4] # IndexError hatası oluşturur
-
-# Bir kısmını almak isterseniz.
-li[1:3] # => [2, 4]
-# Başlangıç belirtmezseniz
-li[2:] # => [4, 3]
-# Sonu belirtmesseniz
-li[:3] # => [1, 2, 4]
-# Her ikişer objeyi seçme
-li[::2] # =>[1, 4]
-# Listeyi tersten almak
-li[::-1] # => [3, 4, 2, 1]
-# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz
-# li[baslangic:son:adim]
-
-# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz
-del li[2] # li artık [1, 2, 3] oldu
-
-# Listelerde de ekleme yapabilirsiniz
-# Not: değerler üzerinde değişiklik yapılmaz.
-li + diger_li # => [1, 2, 3, 4, 5, 6]
-
-# Listeleri birbirine bağlamak için "extend()" kullanılabilir
-li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu
-
-# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir
-1 in li # => True
-
-# Uzunluğu öğrenmek için "len()" kullanılabilir
-len(li) # => 6
-
-
-# Tüpler listeler gibidir fakat değiştirilemez.
-tup = (1, 2, 3)
-tup[0] # => 1
-tup[0] = 3 # TypeError hatası oluşturur
-
-# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
-
-# Tüpleri(veya listeleri) değişkenlere açabilirsiniz
-a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3
-# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur
-d, e, f = 4, 5, 6
-# 2 değeri birbirine değiştirmek bu kadar kolay
-e, d = d, e # 'd' artık 5 ve 'e' artık 4
-
-
-# Sözlükler anahtar kodlarla verileri tutar
-bos_sozl = {}
-# Önceden doldurulmuş sözlük oluşturma
-dolu_sozl = {"bir": 1, "iki": 2, "uc": 3}
-
-# Değere bakmak için [] kullanalım
-dolu_sozl["bir"] # => 1
-
-# Bütün anahtarları almak için "keys()" kullanılabilir.
-# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz.
-# Not - Sözlük anahtarlarının sıralaması kesin değildir.
-# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir.
-list(dolu_sozl.keys()) # => ["uc", "iki", "bir"]
-
-
-# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor
-# Not - Sıralama değişebilir.
-list(dolu_sozl.values()) # => [3, 2, 1]
-
-
-# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz
-"bir" in dolu_sozl # => True
-1 in dolu_sozl # => False
-
-# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır.
-dolu_sozl["dort"] # KeyError hatası oluşturur
-
-# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz
-dolu_sozl.get("bir") # => 1
-dolu_sozl.get("dort") # => None
-# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz.
-dolu_sozl.get("bir", 4) # => 1
-dolu_sozl.get("dort", 4) # => 4
-
-# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır
-dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip
-dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip
-
-# Sözlüğe ekleme
-dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4}
-#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu
-
-# Sözlükten anahtar silmek için 'del' kullanılabilir
-del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir
-
-
-# Setler ... set işte :D
-bos_set = set()
-# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm.
-bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4}
-
-# Sete yeni setler ekleyebilirsiniz
-dolu_set = bir_set
-
-# Sete bir diğer öğe ekleme
-dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu
-
-# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz
-diger_set = {3, 4, 5, 6}
-dolu_set & diger_set # => {3, 4, 5}
-
-# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz
-dolu_set | diger_set # => {1, 2, 3, 4, 5, 6}
-
-# Farklılıkları almak için "-" kullanabilirsiniz
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
-
-# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir
-2 in dolu_set # => True
-10 in dolu_set # => False
-
-
-####################################################
-## 3. Kontrol Akışları ve Temel Soyutlandırma
-####################################################
-
-# Bir değişken oluşturalım
-bir_degisken = 5
-
-# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir!
-# çıktı olarak "bir_degisken 10 dan küçük" yazar
-if bir_degisken > 10:
- print("bir_degisken 10 dan büyük")
-elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir.
- print("bir_degisken 10 dan küçük")
-else: # Bu ifade de zorunlu değil.
- print("bir_degisken değeri 10")
-
-
-"""
-Döngülerle lsiteleri döngüye alabilirsiniz
-çıktı:
- köpek bir memeli hayvandır
- kedi bir memeli hayvandır
- fare bir memeli hayvandır
-"""
-for hayvan in ["köpek", "kedi, "fare"]:
- # format ile kolayca yazıyı biçimlendirelim
- print("{} bir memeli hayvandır".format(hayvan))
-
-"""
-"range(sayi)" bir sayı listesi döndür
-0'dan belirttiğiniz sayıyıa kadar
-çıktı:
- 0
- 1
- 2
- 3
-"""
-for i in range(4):
- print(i)
-
-"""
-'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir.
-çıktı:
- 0
- 1
- 2
- 3
-"""
-x = 0
-while x < 4:
- print(x)
- x += 1 # Uzun hali x = x + 1
-
-# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz
-try:
- # Bir hata oluşturmak için "raise" kullanabilirsiniz
- raise IndexError("Bu bir index hatası")
-except IndexError as e:
- pass # Önemsiz, devam et.
-except (TypeError, NameError):
- pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse.
-else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır
- print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı
-
-# Temel Soyutlandırma, bir objenin işlenmiş halidir.
-# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi.
-
-dolu_sozl = {"bir": 1, "iki": 2, "uc": 3}
-temel_soyut = dolu_sozl.keys()
-print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu
-
-# Temel Soyutlandırılmış objeyi döngüye sokabiliriz.
-for i in temel_soyut:
- print(i) # Çıktısı: bir, iki, uc
-
-# Fakat, elementin anahtarına değerine.
-temel_soyut[1] # TypeError hatası!
-
-# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır.
-iterator = iter(temel_soyut)
-
-# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır
-# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz.
-iterator.__next__() #=> "bir"
-
-# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir
-iterator.__next__() #=> "iki"
-iterator.__next__() #=> "uc"
-
-# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır.
-iterator.__next__() # StopIteration hatası
-
-# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz.
-list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"]
-
-
-####################################################
-## 4. Fonksiyonlar
-####################################################
-
-# "def" ile yeni fonksiyonlar oluşturabilirsiniz
-def topla(x, y):
- print("x = {} ve y = {}".format(x, y))
- return x + y # Değer döndürmek için 'return' kullanmalısınız
-
-# Fonksiyonu parametleri ile çağırıyoruz
-topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür
-
-# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek
-topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz.
-
-# Sınırsız sayıda argüman da alabilirsiniz
-def argumanlar(*argumanlar):
- return argumanlar
-
-argumanlar(1, 2, 3) # => (1, 2, 3)
-
-# Parametrelerin anahtar değerlerini almak isterseniz
-def anahtar_par(**anahtarlar):
- return anahtar
-
-# Çalıştırdığımızda
-anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"}
-
-
-# İsterseniz, bu ikisini birden kullanabilirsiniz
-def tum_argumanlar(*argumanlar, **anahtarla):
- print(argumanlar)
- print(anahtarla)
-"""
-tum_argumanlar(1, 2, a=3, b=4) çıktı:
- (1, 2)
- {"a": 3, "b": 4}
-"""
-
-# Fonksiyonu çağırırken de aynısını kullanabilirsiniz
-argumanlar = (1, 2, 3, 4)
-anahtarla = {"a": 3, "b": 4}
-tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4)
-tum_argumanlar(**anahtarla) # = foo(a=3, b=4)
-tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4)
-
-
-# Fonksiyonlarda kullanacağımız bir değişken oluşturalım
-x = 5
-
-def belirleX(sayi):
- # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil
- x = sayi # => 43
- print (x) # => 43
-
-def globalBelirleX(sayi):
- global x
- print (x) # => 5
- x = sayi # global olan x değişkeni artık 6
- print (x) # => 6
-
-belirleX(43)
-globalBelirleX(6)
-
-
-# Sınıf fonksiyonları oluşturma
-def toplama_olustur(x):
- def topla(y):
- return x + y
- return topla
-
-ekle_10 = toplama_olustur(10)
-ekle_10(3) # => 13
-
-# Bilinmeyen fonksiyon
-(lambda x: x > 2)(3) # => True
-
-# TODO - Fix for iterables
-# Belirli sayıdan yükseğini alma fonksiyonu
-map(ekle_10, [1, 2, 3]) # => [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-
-# Filtreleme işlemi için liste comprehensions da kullanabiliriz
-[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
-
-####################################################
-## 5. Sınıflar
-####################################################
-
-
-# Sınıf oluşturmak için objeden alt sınıf oluşturacağız.
-class Insan(object):
-
- # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir
- tur = "H. sapiens"
-
- # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir.
- # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar
- # python tarafından tanımlanan isimlerdir.
- # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız!
- def __init__(self, isim):
- # Parametreyi sınıfın değerine atayalım
- self.isim = isim
-
- # Bir metot. Bütün metotlar ilk parametre olarak "self "alır.
- def soyle(self, mesaj):
- return "{isim}: {mesaj}".format(isim=self.isim, mesaj=mesaj)
-
- # Bir sınıf metotu bütün nesnelere paylaştırılır
- # İlk parametre olarak sınıf alırlar
- @classmethod
- def getir_tur(snf):
- return snf.tur
-
- # Bir statik metot, sınıf ve nesnesiz çağrılır
- @staticmethod
- def grunt():
- return "*grunt*"
-
-
-# Sınıfı çağıralım
-i = Insan(isim="Ahmet")
-print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba"
-
-j = Insan("Ali")
-print(j.soyle("selam")) # çıktı "Ali: selam"
-
-# Sınıf metodumuzu çağıraim
-i.getir_tur() # => "H. sapiens"
-
-# Paylaşılan değeri değiştirelim
-Insan.tur = "H. neanderthalensis"
-i.getir_tur() # => "H. neanderthalensis"
-j.getir_tur() # => "H. neanderthalensis"
-
-# Statik metodumuzu çağıralım
-Insan.grunt() # => "*grunt*"
-
-
-####################################################
-## 6. Moduller
-####################################################
-
-# Modülleri içe aktarabilirsiniz
-import math
-print(math.sqrt(16)) # => 4.0
-
-# Modülden belirli bir fonksiyonları alabilirsiniz
-from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
-
-# Modüldeki tüm fonksiyonları içe aktarabilirsiniz
-# Dikkat: bunu yapmanızı önermem.
-from math import *
-
-# Modül isimlerini değiştirebilirsiniz.
-# Not: Modül ismini kısaltmanız çok daha iyi olacaktır
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
-
-# Python modulleri aslında birer python dosyalarıdır.
-# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün
-# ismi ile dosyanın ismi aynı olacaktır.
-
-# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz.
-import math
-dir(math)
-
-
-####################################################
-## 7. Gelişmiş
-####################################################
-
-# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır
-def kare_sayilar(nesne):
- for i in nesne:
- yield i + i
-
-# Bir oluşturucu(generator) değerleri anında oluşturur.
-# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan
-# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük
-# değerler işlenmeyecektir.
-# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda
-# çok fazla vakit alacaktır.
-# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir.
-range_ = range(1, 900000000)
-# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım
-for i in kare_sayilar(range_):
- print(i)
- if i >= 30:
- break
-
-
-# Dekoratörler
-# Bu örnekte,
-# Eğer lutfen_soyle True ise dönen değer değişecektir.
-from functools import wraps
-
-
-def yalvar(hedef_fonksiyon):
- @wraps(hedef_fonksiyon)
- def metot(*args, **kwargs):
- msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs)
- if lutfen_soyle:
- return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(")
- return msj
-
- return metot
-
-
-@yalvar
-def soyle(lutfen_soyle=False):
- msj = "Bana soda alır mısın?"
- return msj, lutfen_soyle
-
-
-print(soyle()) # Bana soda alır mısın?
-print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :(
-```
-
-## Daha Fazlasına Hazır Mısınız?
-
-### Ücretsiz Online
-
-* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
-* [Python Course](http://www.python-course.eu/index.php)
-* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
-* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
-* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
-* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
-* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
-
-### Kitaplar
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
-
diff --git a/tr-tr/pythonlegacy-tr.html.markdown b/tr-tr/pythonlegacy-tr.html.markdown
new file mode 100644
index 00000000..cd757625
--- /dev/null
+++ b/tr-tr/pythonlegacy-tr.html.markdown
@@ -0,0 +1,502 @@
+---
+language: Python 2 (legacy)
+filename: learnpythonlegacy-tr.py
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+translators:
+ - ["Haydar KULEKCI", "http://scanf.info/"]
+lang: tr-tr
+---
+Python Guido Van Rossum tarafından 90'ların başında yaratılmıştır. Şu anda
+varolanlar arasında en iyi dillerden birisidir. Ben (Louie Dinh) Python
+dilinin syntax'ının belirginliğine aşığım. O basit olarak çalıştırılabilir
+pseudocode'dur.
+
+Geri bildirimlerden son derece mutluluk duyarım! Bana [@louiedinh](http://twitter.com/louiedinh)
+adresinden ya da louiedinh [at] [google's email service] adresinden ulaşabilirsiniz.
+
+Çeviri için geri bildirimleri de [@kulekci](http://twitter.com/kulekci)
+adresine yapabilirsiniz.
+
+Not: Bu yazıdaki özellikler Python 2.7 için geçerlidir, ama Python 2.x için de
+uygulanabilir. Python 3 için başka bir zaman tekrar bakınız.
+
+
+```python
+# Tek satır yorum hash işareti ile başlar.
+""" Çoklu satır diziler üç tane çift tırnak
+ arasında yazılır. Ve yorum olarak da
+ kullanılabilir
+"""
+
+
+####################################################
+## 1. İlkel Veri Tipleri ve Operatörler
+####################################################
+
+# Sayılar
+3 #=> 3
+
+# Matematik beklediğiniz gibi
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# Bölünme biraz ilginç. EĞer tam sayılar üzerinde bölünme işlemi yapıyorsanız
+# sonuç otomatik olarak kırpılır.
+5 / 2 #=> 2
+
+# Bölünme işlemini düzenlemek için kayan noktalı sayıları bilmeniz gerekir.
+2.0 # Bu bir kayan noktalı sayı
+11.0 / 4.0 #=> 2.75 ahhh...daha iyi
+
+# İşlem önceliğini parantezler ile sağlayabilirsiniz.
+(1 + 3) * 2 #=> 8
+
+# Boolean değerleri bilindiği gibi
+True
+False
+
+# not ile nagatif(mantıksal) değerini alma
+not True #=> False
+not False #=> True
+
+# Eşitlik ==
+1 == 1 #=> True
+2 == 1 #=> False
+
+# Eşitsizlik !=
+1 != 1 #=> False
+2 != 1 #=> True
+
+# Daha fazla karşılaştırma
+1 < 10 #=> True
+1 > 10 #=> False
+2 <= 2 #=> True
+2 >= 2 #=> True
+
+# Karşılaştırma zincirleme yapılabilir!
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
+
+# Karakter dizisi " veya ' ile oluşturulabilir
+"This is a string."
+'This is also a string.'
+
+# Karakter dizileri birbirleri ile eklenebilir
+"Hello " + "world!" #=> "Hello world!"
+
+# A string can be treated like a list of characters
+# Bir string'e karakter listesi gibi davranabilirsiniz.
+"This is a string"[0] #=> 'T'
+
+# % karakter dizisini(string) formatlamak için kullanılır, bunun gibi:
+"%s can be %s" % ("strings", "interpolated")
+
+# String'leri formatlamanın yeni bir yöntem ise format metodudur.
+# Bu metod tercih edilen yöntemdir.
+"{0} can be {1}".format("strings", "formatted")
+# Eğer saymak istemiyorsanız anahtar kelime kullanabilirsiniz.
+"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+
+# None bir objedir
+None #=> None
+
+# "==" eşitliğini non objesi ile karşılaştırmak için kullanmayın.
+# Onun yerine "is" kullanın.
+"etc" is None #=> False
+None is None #=> True
+
+# 'is' operatörü obje kimliği için test etmektedir. Bu ilkel değerler
+# için kullanışlı değildir, ama objeleri karşılaştırmak için kullanışlıdır.
+
+# None, 0 ve boş string/list'ler False olarak değerlendirilir.
+# Tüm eşitlikler True döner
+0 == False #=> True
+"" == False #=> True
+
+
+####################################################
+## 2. Değişkenler ve Kolleksiyonlar
+####################################################
+
+# Ekrana yazdırma oldukça kolaydır.
+print "I'm Python. Nice to meet you!"
+
+
+# Değişkenlere bir değer atamadan önce tanımlamaya gerek yoktur.
+some_var = 5 # Değişken isimlerinde gelenek küçük karakter ve alt çizgi
+ # kullanmaktır.
+some_var #=> 5
+
+# Daha önceden tanımlanmamış ya da assign edilmemeiş bir değişkene erişmeye
+# çalıştığınızda bir hata fırlatılacaktır. Hata ayıklama hakkında daha fazla
+# bilgi için kontrol akışı kısmına göz atınız.
+some_other_var # isim hatası fırlatılır
+
+# isterseniz "if"i bir ifade gibi kullanabilirsiniz.
+"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+
+# Listeler
+li = []
+# Önceden değerleri tanımlanmış listeler
+other_li = [4, 5, 6]
+
+# Bir listenin sonuna birşeyler eklemek
+li.append(1) #li şu anda [1]
+li.append(2) #li şu anda [1, 2]
+li.append(4) #li şu anda [1, 2, 4]
+li.append(3) #li şu anda [1, 2, 4, 3]
+# pop ile sondan birşeyler silmek
+li.pop() #=> 3 and li is now [1, 2, 4]
+# Tekrar sonuna eklemek
+li.append(3) # li is now [1, 2, 4, 3] again.
+
+# Dizi gibi listenin elemanlarına erişmek
+li[0] #=> 1
+# Son elemanın değerine ulaşmak
+li[-1] #=> 3
+
+# Listede bulunmayan bir index'teki elemana erişirken "IndexError" hatası
+# fırlatılır
+li[4] # IndexError fırlatılır
+
+# slice syntax'ı ile belli aralıktakı değerlere bakabilirsiniz.
+# (Açık ve kapalı aralıklıdır.)
+li[1:3] #=> [2, 4]
+# Başlangıcı ihmal etme
+li[2:] #=> [4, 3]
+# Sonu ihmal etme
+li[:3] #=> [1, 2, 4]
+
+# "del" ile istenilen bir elemanı listeden silmek
+del li[2] # li is now [1, 2, 3]
+
+# Listeleri birbiri ile birleştirebilirsiniz.
+li + other_li #=> [1, 2, 3, 4, 5, 6] - Not: li ve other_li yanlız bırakılır
+
+# extend ile listeleri birleştirmek
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+
+# bir değerin liste içerisinde varlığını "in" ile kontrol etmek
+1 in li #=> True
+
+# "len" ile listenin uzunluğunu bulmak
+len(li) #=> 6
+
+# Tüpler listeler gibidir sadece değişmezler(immutable)
+tup = (1, 2, 3)
+tup[0] #=> 1
+tup[0] = 3 # TypeError fırlatılır.
+
+# Litelerde yapılanların hepsini tüplerde de yapılabilir
+len(tup) #=> 3
+tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
+tup[:2] #=> (1, 2)
+2 in tup #=> True
+
+# Tüplerin(veya listelerin) içerisindeki değerleri değişkenelere
+# atanabilir
+a, b, c = (1, 2, 3) # a şu anda 1, b şu anda 2 ve c şu anda 3
+# Eğer parantez kullanmaz iseniz tüpler varsayılan olarak oluşturulur
+d, e, f = 4, 5, 6
+# şimdi iki değeri değiş tokuş etmek çok kolaydır.
+e, d = d, e # d şimdi 5 ve e şimdi 4
+
+
+# Sözlükler (Dictionaries) key-value saklanır.
+empty_dict = {}
+# Sözlüklere önceden değer atama örneği
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Değere ulaşmak için [] kullanılır
+filled_dict["one"] #=> 1
+
+# Tüm anahtarlara(key) "keys()" metodu ile ulaşılır
+filled_dict.keys() #=> ["three", "two", "one"]
+# Not - Sözlüklerin anahtarlarının sıralı geleceği garanti değildir
+# Sonuçlarınız değer listesini aldığınızda tamamen eşleşmeyebilir
+
+# Tüm değerleri almak için "values()" kullanabilirsiniz.
+filled_dict.values() #=> [3, 2, 1]
+# Not - Sıralama ile ilgili anahtarlar ile aynı durum geçerlidir.
+
+# Bir anahtarın sözlükte oluş olmadığını "in" ile kontrol edilebilir
+"one" in filled_dict #=> True
+1 in filled_dict #=> False
+
+# Olmayan bir anahtar çağrıldığında KeyError fırlatılır.
+filled_dict["four"] # KeyError
+
+# "get()" metodu KeyError fırlatılmasını önler
+filled_dict.get("one") #=> 1
+filled_dict.get("four") #=> None
+# get() metodu eğer anahtar mevcut değilse varsayılan bir değer atama
+# imknaı sağlar.
+filled_dict.get("one", 4) #=> 1
+filled_dict.get("four", 4) #=> 4
+
+# "setdefault()" metodu sözlüğe yeni bir key-value eşleşmesi eklemenin
+# güvenli bir yoludur.
+filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5
+filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5
+
+
+# Sets store ... well sets
+empty_set = set()
+# Bir demek değer ile bir "set" oluşturmak
+some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4])
+
+# Python 2.7'den beri {}'ler bir "set" tanımlaman için kullanılabilir
+filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+
+# Bir set'e daha fazla eleman eklemek
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+
+# "&" işareti ile iki set'in kesişimlerini alınabilir
+other_set = {3, 4, 5, 6}
+filled_set & other_set #=> {3, 4, 5}
+
+# | işareti ile
+filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+
+# "-" işareti ile iki set'in farkları alınabilir
+{1,2,3,4} - {2,3,5} #=> {1, 4}
+
+# "in" ile değerin set içerisinde olup olmadığını kontrol edebilirsiniz
+2 in filled_set #=> True
+10 in filled_set #=> False
+
+
+####################################################
+## 3. Akış Denetimi
+####################################################
+
+# Bir değişken oluşturmak
+some_var = 5
+
+# Buradaki bir if ifadesi. Girintiler(Intentation) Python'da önemlidir!
+# "some_var is smaller than 10" yazdırılır.
+if some_var > 10:
+ print "some_var is totally bigger than 10."
+elif some_var < 10: # elif ifadesi isteğe bağlıdır
+ print "some_var is smaller than 10."
+else: # Bu da isteğe bağlıdır.
+ print "some_var is indeed 10."
+
+
+"""
+For döngüleri listeler üzerinde iterasyon yapar
+Ekrana yazdırılan:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ # Biçimlendirmeleri string'e katmak için % kullanabilirsiniz
+ print "%s is a mammal" % animal
+
+"""
+"range(number)" ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner
+Ekrana yazdırılan:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+While döngüsü koşul sağlanmayana kadar devam eder
+Ekrana yazdırılan:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Shorthand for x = x + 1
+
+# try/except bloğu ile hatalar ayıklanabilir
+
+# Python 2.6 ve üstü için çalışacaktır:
+try:
+ # "raise" bir hata fırlatmak için kullanılabilir
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # Pass is just a no-op. Usually you would do recovery here.
+
+
+####################################################
+## 4. Fonksiyonlar
+####################################################
+
+
+# Yeni bir fonksiyon oluşturmak için "def" kullanılır
+def add(x, y):
+ print "x is %s and y is %s" % (x, y)
+ return x + y # Return values with a return statement
+
+# Fonksiyonu parametre ile çağırmak
+add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11
+
+# Diğer bir yol fonksiyonları anahtar argümanları ile çağırmak
+add(y=6, x=5) # Anahtar argümanlarının sırası farklı da olabilir
+
+# Değişken sayıda parametresi olan bir fonksiyon tanımlayabilirsiniz
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) #=> (1,2,3)
+
+# Değişken sayıda anahtar argümanlı parametre alan fonksiyonlar da
+# tanımlayabilirsiniz.
+def keyword_args(**kwargs):
+ return kwargs
+
+# Şu şekilde kullanılacaktır
+keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+
+# Eğer isterseniz ikisini aynı anda da yapabilirsiniz
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Fonksiyonu çağırırken, args/kwargs'ın tam tersini de yapabilirsiniz!
+# Tüpü yaymak için * ve kwargs'ı yaymak için ** kullanın.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # foo(1, 2, 3, 4) ile eşit
+all_the_args(**kwargs) # foo(a=3, b=4) ile eşit
+all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4) ile eşit
+
+# Python first-class fonksiyonlara sahiptir
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) #=> 13
+
+# Anonymous fonksiyonlar da vardır
+(lambda x: x > 2)(3) #=> True
+
+# Dahili yüksek seviye fonksiyonlar vardır
+map(add_10, [1,2,3]) #=> [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+
+# Map etme(maps) ve filtreleme(filtres) için liste kullanabiliriz.
+[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+
+
+####################################################
+## 5. Sınıflar
+####################################################
+
+# We subclass from object to get a class.
+class Human(object):
+
+ # Bir sınıf özelliği. Bu sınıfın tüm "instance"larına paylaşılmıştır.
+ species = "H. sapiens"
+
+ # Basic initializer
+ def __init__(self, name):
+ # Metoda gelen argümanın değerini sınıfın elemanı olan "name"
+ # değişkenine atama
+ self.name = name
+
+ # Bir instance metodu. Tüm metodlar ilk argüman olarak "self"
+ # parametresini alır
+ def say(self, msg):
+ return "%s: %s" % (self.name, msg)
+
+ # Bir sınıf metodu tüm "instance"lar arasında paylaşılır
+ # İlk argüman olarak sınıfı çağırarak çağrılırlar
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Bir statik metod bir sınıf ya da instance referansı olmadan çağrılır
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# Bir sınıf örneği oluşturmak
+i = Human(name="Ian")
+print i.say("hi") # "Ian: hi" çıktısı verir
+
+j = Human("Joel")
+print j.say("hello") # "Joel: hello" çıktısı verir
+
+# Sınıf metodunu çağıralım
+i.get_species() #=> "H. sapiens"
+
+# Paylaşılan sınıf özellik değiştirelim.
+Human.species = "H. neanderthalensis"
+i.get_species() #=> "H. neanderthalensis"
+j.get_species() #=> "H. neanderthalensis"
+
+# Statik metodu çağırma
+Human.grunt() #=> "*grunt*"
+
+
+####################################################
+## 6. Modüller
+####################################################
+
+# Modülleri sayfaya dahil edebilirsiniz
+import math
+print math.sqrt(16) #=> 4.0
+
+# Modül içerisinden spesifik bir fonksiyonu getirebilirsiniz
+from math import ceil, floor
+print ceil(3.7) #=> 4.0
+print floor(3.7) #=> 3.0
+
+# Modüldeki tüm fonksiyonları dahil edebilirsiniz
+# Uyarı: bu önerilmez
+from math import *
+
+# Modülün adını kısaltabilirsiniz
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Python modülleri sıradan python dosyalarıdır. Kendinize bir modül
+# yazabilirsiniz, ve dahil edebilirsiniz. Modülün adı ile dosya adı
+# aynı olmalıdır.
+
+# Modüllerde tanımlanmış fonksiyon ve metodları öğrenebilirsiniz.
+import math
+dir(math)
+
+
+
+```
+
+## Daha fazlası için hazır mısınız?
+
+### Ücretsiz Dökümanlar
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+
+### Dead Tree
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/uk-ua/python-ua.html.markdown b/uk-ua/pythonlegacy-ua.html.markdown
index 4091e433..e2a6d19e 100644
--- a/uk-ua/python-ua.html.markdown
+++ b/uk-ua/pythonlegacy-ua.html.markdown
@@ -1,5 +1,5 @@
---
-language: python
+language: Python 2 (legacy)
lang: uk-ua
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
@@ -10,7 +10,7 @@ contributors:
- ["habi", "http://github.com/habi"]
translators:
- ["Oleh Hromiak", "https://github.com/ogroleg"]
-filename: learnpython-ua.py
+filename: learnpythonlegacy-ua.py
---
Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з
diff --git a/vi-vn/python3-vi.html.markdown b/vi-vn/python-vi.html.markdown
index f6cce1a3..89e51d5d 100644
--- a/vi-vn/python3-vi.html.markdown
+++ b/vi-vn/python-vi.html.markdown
@@ -1,6 +1,6 @@
---
-language: python3
-filename: learnpython3-vi.py
+language: Python
+filename: learnpython-vi.py
contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
- ["Steven Basart", "http://github.com/xksteven"]
@@ -19,7 +19,7 @@ như một loại mã giả (pseudocode) có thể thực thi được.
Mọi phản hồi đều sẽ được tích cực ghi nhận! Bạn có thể liên lạc với tôi qua Twitter [@louiedinh](http://twitter.com/louiedinh) hoặc louiedinh [at] [google's email service]
-Lưu ý: Bài viết này áp dụng riêng cho Python 3. Truy cập [vào đây](http://learnxinyminutes.com/docs/python/) nếu bạn muốn học phiên bản cũ Python 2.7
+Lưu ý: Bài viết này áp dụng riêng cho Python 3. Truy cập [vào đây](http://learnxinyminutes.com/docs/pythonlegacy/) nếu bạn muốn học phiên bản cũ Python 2.7
```python
diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown
index 65f125d1..da13275b 100644
--- a/zh-cn/python-cn.html.markdown
+++ b/zh-cn/python-cn.html.markdown
@@ -1,302 +1,342 @@
---
-language: python
+language: Python
contributors:
- - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
translators:
- - ["Chenbo Li", "http://binarythink.net"]
-filename: learnpython-zh.py
+ - ["Geoff Liu", "http://geoffliu.me"]
+filename: learnpython-cn.py
lang: zh-cn
---
-Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语言之一
-我喜爱python是因为它有极为清晰的语法,甚至可以说,它就是可以执行的伪代码
+Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。
+它是如今最常用的编程语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。
-很欢迎来自您的反馈,你可以在[@louiedinh](http://twitter.com/louiedinh) 和 louiedinh [at] [google's email service] 这里找到我
+欢迎大家斧正。英文版原作 Louie Dinh [@louiedinh](http://twitter.com/louiedinh)
+邮箱 louiedinh [at] [谷歌的信箱服务]。中文翻译 Geoff Liu。
-注意: 这篇文章针对的版本是Python 2.7,但大多也可使用于其他Python 2的版本
-如果是Python 3,请在网络上寻找其他教程
+注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/pythonlegacy/)。
```python
-# 单行注释
-""" 多行字符串可以用
- 三个引号包裹,不过这也可以被当做
- 多行注释
+# 用井字符开头的是单行注释
+
+""" 多行字符串用三个引号
+ 包裹,也常被用来做多
+ 行注释
"""
####################################################
-## 1. 原始数据类型和操作符
+## 1. 原始数据类型和运算符
####################################################
-# 数字类型
+# 整数
3 # => 3
-# 简单的算数
+# 算术没有什么出乎意料的
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
-35 / 5 # => 7
-# 整数的除法会自动取整
-5 / 2 # => 2
+# 但是除法例外,会自动转换成浮点数
+35 / 5 # => 7.0
+5 / 3 # => 1.6666666666666667
+
+# 整数除法的结果都是向下取整
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # 浮点数也可以
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# 浮点数的运算结果也是浮点数
+3 * 2.0 # => 6.0
+
+# 模除
+7 % 3 # => 1
-# 要做精确的除法,我们需要引入浮点数
-2.0 # 浮点数
-11.0 / 4.0 # => 2.75 精确多了
+# x的y次方
+2**4 # => 16
-# 括号具有最高优先级
+# 用括号决定优先级
(1 + 3) * 2 # => 8
-# 布尔值也是基本的数据类型
+# 布尔值
True
False
-# 用 not 来取非
+# 用not取非
not True # => False
not False # => True
-# 相等
+# 逻辑运算符,注意and和or都是小写
+True and False # => False
+False or True # => True
+
+# 整数也可以当作布尔值
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
+
+# 用==判断相等
1 == 1 # => True
2 == 1 # => False
-# 不等
+# 用!=判断不等
1 != 1 # => False
2 != 1 # => True
-# 更多的比较操作符
+# 比较大小
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
-# 比较运算可以连起来写!
+# 大小比较可以连起来!
1 < 2 < 3 # => True
2 < 3 < 2 # => False
-# 字符串通过 " 或 ' 括起来
-"This is a string."
-'This is also a string.'
+# 字符串用单引双引都可以
+"这是个字符串"
+'这也是个字符串'
-# 字符串通过加号拼接
+# 用加号连接字符串
"Hello " + "world!" # => "Hello world!"
-# 字符串可以被视为字符的列表
+# 字符串可以被当作字符列表
"This is a string"[0] # => 'T'
-# % 可以用来格式化字符串
-"%s can be %s" % ("strings", "interpolated")
+# 用.format来格式化字符串
+"{} can be {}".format("strings", "interpolated")
+
+# 可以重复参数以节省时间
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
-# 也可以用 format 方法来格式化字符串
-# 推荐使用这个方法
-"{0} can be {1}".format("strings", "formatted")
-# 也可以用变量名代替数字
-"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+# 如果不想数参数,可以用关键字
+"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+# => "Bob wants to eat lasagna"
-# None 是对象
+# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法
+"%s can be %s the %s way" % ("strings", "interpolated", "old")
+
+# None是一个对象
None # => None
-# 不要用相等 `==` 符号来和None进行比较
-# 要用 `is`
+# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。
"etc" is None # => False
None is None # => True
-# 'is' 可以用来比较对象的相等性
-# 这个操作符在比较原始数据时没多少用,但是比较对象时必不可少
-
-# None, 0, 和空字符串都被算作 False
-# 其他的均为 True
-0 == False # => True
-"" == False # => True
+# None,0,空字符串,空列表,空字典都算是False
+# 所有其他值都是True
+bool(0) # => False
+bool("") # => False
+bool([]) # => False
+bool({}) # => False
####################################################
## 2. 变量和集合
####################################################
-# 很方便的输出
-print "I'm Python. Nice to meet you!"
+# print是内置的打印函数
+print("I'm Python. Nice to meet you!")
-
-# 给变量赋值前不需要事先声明
-some_var = 5 # 一般建议使用小写字母和下划线组合来做为变量名
+# 在给变量赋值前不用提前声明
+# 传统的变量命名是小写,用下划线分隔单词
+some_var = 5
some_var # => 5
# 访问未赋值的变量会抛出异常
-# 可以查看控制流程一节来了解如何异常处理
-some_other_var # 抛出 NameError
+# 参考流程控制一段来学习异常处理
+some_unknown_var # 抛出NameError
-# if 语句可以作为表达式来使用
-"yahoo!" if 3 > 2 else 2 # => "yahoo!"
-
-# 列表用来保存序列
+# 用列表(list)储存序列
li = []
-# 可以直接初始化列表
+# 创建列表时也可以同时赋给元素
other_li = [4, 5, 6]
-# 在列表末尾添加元素
-li.append(1) # li 现在是 [1]
-li.append(2) # li 现在是 [1, 2]
-li.append(4) # li 现在是 [1, 2, 4]
-li.append(3) # li 现在是 [1, 2, 4, 3]
-# 移除列表末尾元素
-li.pop() # => 3 li 现在是 [1, 2, 4]
-# 重新加进去
-li.append(3) # li is now [1, 2, 4, 3] again.
-
-# 像其他语言访问数组一样访问列表
+# 用append在列表最后追加元素
+li.append(1) # li现在是[1]
+li.append(2) # li现在是[1, 2]
+li.append(4) # li现在是[1, 2, 4]
+li.append(3) # li现在是[1, 2, 4, 3]
+# 用pop从列表尾部删除
+li.pop() # => 3 且li现在是[1, 2, 4]
+# 把3再放回去
+li.append(3) # li变回[1, 2, 4, 3]
+
+# 列表存取跟数组一样
li[0] # => 1
-# 访问最后一个元素
+# 取出最后一个元素
li[-1] # => 3
-# 越界会抛出异常
-li[4] # 抛出越界异常
+# 越界存取会造成IndexError
+li[4] # 抛出IndexError
-# 切片语法需要用到列表的索引访问
-# 可以看做数学之中左闭右开区间
+# 列表有切割语法
li[1:3] # => [2, 4]
-# 省略开头的元素
+# 取尾
li[2:] # => [4, 3]
-# 省略末尾的元素
+# 取头
li[:3] # => [1, 2, 4]
+# 隔一个取一个
+li[::2] # =>[1, 4]
+# 倒排列表
+li[::-1] # => [3, 4, 2, 1]
+# 可以用三个参数的任何组合来构建切割
+# li[始:终:步伐]
-# 删除特定元素
-del li[2] # li 现在是 [1, 2, 3]
+# 用del删除任何一个元素
+del li[2] # li is now [1, 2, 3]
-# 合并列表
-li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会不改变这两个列表
+# 列表可以相加
+# 注意:li和other_li的值都不变
+li + other_li # => [1, 2, 3, 4, 5, 6]
-# 通过拼接来合并列表
-li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6]
+# 用extend拼接列表
+li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6]
-# 用 in 来返回元素是否在列表中
-1 in li # => True
+# 用in测试列表是否包含值
+1 in li # => True
-# 返回列表长度
-len(li) # => 6
+# 用len取列表长度
+len(li) # => 6
-# 元组类似于列表,但它是不可改变的
+# 元组是不可改变的序列
tup = (1, 2, 3)
-tup[0] # => 1
-tup[0] = 3 # 类型错误
-
-# 对于大多数的列表操作,也适用于元组
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
-
-# 你可以将元组解包赋给多个变量
-a, b, c = (1, 2, 3) # a 是 1,b 是 2,c 是 3
-# 如果不加括号,将会被自动视为元组
+tup[0] # => 1
+tup[0] = 3 # 抛出TypeError
+
+# 列表允许的操作元组大都可以
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# 可以把元组合列表解包,赋值给变量
+a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3
+# 元组周围的括号是可以省略的
d, e, f = 4, 5, 6
-# 现在我们可以看看交换两个数字是多么容易的事
-e, d = d, e # d 是 5,e 是 4
+# 交换两个变量的值就这么简单
+e, d = d, e # 现在d是5,e是4
-# 字典用来储存映射关系
+# 用字典表达映射关系
empty_dict = {}
-# 字典初始化
+# 初始化的字典
filled_dict = {"one": 1, "two": 2, "three": 3}
-# 字典也用中括号访问元素
-filled_dict["one"] # => 1
+# 用[]取值
+filled_dict["one"] # => 1
+
+
+# 用 keys 获得所有的键。
+# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。
+# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。
+list(filled_dict.keys()) # => ["three", "two", "one"]
-# 把所有的键保存在列表中
-filled_dict.keys() # => ["three", "two", "one"]
-# 键的顺序并不是唯一的,得到的不一定是这个顺序
-# 把所有的值保存在列表中
-filled_dict.values() # => [3, 2, 1]
-# 和键的顺序相同
+# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。
+list(filled_dict.values()) # => [3, 2, 1]
-# 判断一个键是否存在
-"one" in filled_dict # => True
-1 in filled_dict # => False
-# 查询一个不存在的键会抛出 KeyError
-filled_dict["four"] # KeyError
+# 用in测试一个字典是否包含一个键
+"one" in filled_dict # => True
+1 in filled_dict # => False
-# 用 get 方法来避免 KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
-# get 方法支持在不存在的时候返回一个默认值
-filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
+# 访问不存在的键会导致KeyError
+filled_dict["four"] # KeyError
-# setdefault 是一个更安全的添加字典元素的方法
-filled_dict.setdefault("five", 5) # filled_dict["five"] 的值为 5
-filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5
+# 用get来避免KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# 当键不存在的时候get方法可以返回默认值
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+# setdefault方法只有当键不存在的时候插入新值
+filled_dict.setdefault("five", 5) # filled_dict["five"]设为5
+filled_dict.setdefault("five", 6) # filled_dict["five"]还是5
-# 集合储存无顺序的元素
+# 字典赋值
+filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
+filled_dict["four"] = 4 # 另一种赋值方法
+
+# 用del删除
+del filled_dict["one"] # 从filled_dict中把one删除
+
+
+# 用set表达集合
empty_set = set()
-# 初始化一个集合
-some_set = set([1, 2, 2, 3, 4]) # some_set 现在是 set([1, 2, 3, 4])
+# 初始化一个集合,语法跟字典相似。
+some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4}
-# Python 2.7 之后,大括号可以用来表示集合
-filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+# 可以把集合赋值于变量
+filled_set = some_set
-# 向集合添加元素
-filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5}
+# 为集合添加元素
+filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5}
-# 用 & 来计算集合的交
+# & 取交集
other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
+filled_set & other_set # => {3, 4, 5}
-# 用 | 来计算集合的并
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+# | 取并集
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-# 用 - 来计算集合的差
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+# - 取补集
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
-# 用 in 来判断元素是否存在于集合中
-2 in filled_set # => True
-10 in filled_set # => False
+# in 测试集合是否包含元素
+2 in filled_set # => True
+10 in filled_set # => False
####################################################
-## 3. 控制流程
+## 3. 流程控制和迭代器
####################################################
-# 新建一个变量
+# 先随便定义一个变量
some_var = 5
-# 这是个 if 语句,在 python 中缩进是很重要的。
-# 下面的代码片段将会输出 "some var is smaller than 10"
+# 这是个if语句。注意缩进在Python里是有意义的
+# 印出"some_var比10小"
if some_var > 10:
- print "some_var is totally bigger than 10."
-elif some_var < 10: # 这个 elif 语句是不必须的
- print "some_var is smaller than 10."
-else: # 这个 else 也不是必须的
- print "some_var is indeed 10."
+ print("some_var比10大")
+elif some_var < 10: # elif句是可选的
+ print("some_var比10小")
+else: # else也是可选的
+ print("some_var就是10")
"""
-用for循环遍历列表
-输出:
+用for循环语句遍历列表
+打印:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
- # 你可以用 % 来格式化字符串
- print "%s is a mammal" % animal
+ print("{} is a mammal".format(animal))
"""
-`range(number)` 返回从0到给定数字的列表
-输出:
+"range(number)"返回数字列表从0到给的数字
+打印:
0
1
2
3
"""
for i in range(4):
- print i
+ print(i)
"""
-while 循环
-输出:
+while循环直到条件不满足
+打印:
0
1
2
@@ -304,173 +344,289 @@ while 循环
"""
x = 0
while x < 4:
- print x
- x += 1 # x = x + 1 的简写
-
-# 用 try/except 块来处理异常
+ print(x)
+ x += 1 # x = x + 1 的简写
-# Python 2.6 及以上适用:
+# 用try/except块处理异常状况
try:
- # 用 raise 来抛出异常
+ # 用raise抛出异常
raise IndexError("This is an index error")
except IndexError as e:
- pass # pass 就是什么都不做,不过通常这里会做一些恢复工作
+ pass # pass是无操作,但是应该在这里处理错误
+except (TypeError, NameError):
+ pass # 可以同时处理不同类的错误
+else: # else语句是可选的,必须在所有的except之后
+ print("All good!") # 只有当try运行完没有错误的时候这句才会运行
+
+
+# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列
+# 的对象。比如说上面range返回的对象就是可迭代的。
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一个实现可迭代接口的对象
+
+# 可迭代对象可以遍历
+for i in our_iterable:
+ print(i) # 打印 one, two, three
+
+# 但是不可以随机访问
+our_iterable[1] # 抛出TypeError
+
+# 可迭代对象知道怎么生成迭代器
+our_iterator = iter(our_iterable)
+
+# 迭代器是一个可以记住遍历的位置的对象
+# 用__next__可以取得下一个元素
+our_iterator.__next__() # => "one"
+
+# 再一次调取__next__时会记得位置
+our_iterator.__next__() # => "two"
+our_iterator.__next__() # => "three"
+
+# 当迭代器所有元素都取出后,会抛出StopIteration
+our_iterator.__next__() # 抛出StopIteration
+
+# 可以用list一次取出迭代器所有的元素
+list(filled_dict.keys()) # => Returns ["one", "two", "three"]
+
####################################################
## 4. 函数
####################################################
-# 用 def 来新建函数
+# 用def定义新函数
def add(x, y):
- print "x is %s and y is %s" % (x, y)
- return x + y # 通过 return 来返回值
+ print("x is {} and y is {}".format(x, y))
+ return x + y # 用return语句返回
-# 调用带参数的函数
-add(5, 6) # => 输出 "x is 5 and y is 6" 返回 11
+# 调用函数
+add(5, 6) # => 印出"x is 5 and y is 6"并且返回11
-# 通过关键字赋值来调用函数
-add(y=6, x=5) # 顺序是无所谓的
+# 也可以用关键字参数来调用函数
+add(y=6, x=5) # 关键字参数可以用任何顺序
-# 我们也可以定义接受多个变量的函数,这些变量是按照顺序排列的
+
+# 我们可以定义一个可变参数函数
def varargs(*args):
return args
-varargs(1, 2, 3) # => (1,2,3)
+varargs(1, 2, 3) # => (1, 2, 3)
-# 我们也可以定义接受多个变量的函数,这些变量是按照关键字排列的
+# 我们也可以定义一个关键字可变参数函数
def keyword_args(**kwargs):
return kwargs
-# 实际效果:
-keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+# 我们来看看结果是什么:
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
-# 你也可以同时将一个函数定义成两种形式
+# 这两种可变参数可以混着用
def all_the_args(*args, **kwargs):
- print args
- print kwargs
+ print(args)
+ print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a": 3, "b": 4}
"""
-# 当调用函数的时候,我们也可以进行相反的操作,把元组和字典展开为参数
+# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # 等价于 foo(1, 2, 3, 4)
-all_the_args(**kwargs) # 等价于 foo(a=3, b=4)
-all_the_args(*args, **kwargs) # 等价于 foo(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # 相当于 foo(1, 2, 3, 4)
+all_the_args(**kwargs) # 相当于 foo(a=3, b=4)
+all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4)
+
+
+# 函数作用域
+x = 5
+
+def setX(num):
+ # 局部作用域的x和全局域的x是不同的
+ x = num # => 43
+ print (x) # => 43
-# 函数在 python 中是一等公民
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # 现在全局域的x被赋值
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
+# 函数在Python是一等公民
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
-add_10(3) # => 13
+add_10(3) # => 13
-# 匿名函数
-(lambda x: x > 2)(3) # => True
+# 也有匿名函数
+(lambda x: x > 2)(3) # => True
-# 内置高阶函数
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+# 内置的高阶函数
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-# 可以用列表方法来对高阶函数进行更巧妙的引用
+# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. 类
####################################################
-# 我们新建的类是从 object 类中继承的
+
+# 定义一个继承object的类
class Human(object):
- # 类属性,由所有类的对象共享
+ # 类属性,被所有此类的实例共用。
species = "H. sapiens"
- # 基本构造函数
+ # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属
+ # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这
+ # 种格式。
def __init__(self, name):
- # 将参数赋给对象成员属性
+ # Assign the argument to the instance's name attribute
self.name = name
- # 成员方法,参数要有 self
+ # 实例方法,第一个参数总是self,就是这个实例对象
def say(self, msg):
- return "%s: %s" % (self.name, msg)
+ return "{name}: {message}".format(name=self.name, message=msg)
- # 类方法由所有类的对象共享
- # 这类方法在调用时,会把类本身传给第一个参数
+ # 类方法,被所有此类的实例共用。第一个参数是这个类对象。
@classmethod
def get_species(cls):
return cls.species
- # 静态方法是不需要类和对象的引用就可以调用的方法
+ # 静态方法。调用时没有实例或类的绑定。
@staticmethod
def grunt():
return "*grunt*"
-# 实例化一个类
+# 构造一个实例
i = Human(name="Ian")
-print i.say("hi") # 输出 "Ian: hi"
+print(i.say("hi")) # 印出 "Ian: hi"
j = Human("Joel")
-print j.say("hello") # 输出 "Joel: hello"
+print(j.say("hello")) # 印出 "Joel: hello"
-# 访问类的方法
-i.get_species() # => "H. sapiens"
+# 调用一个类方法
+i.get_species() # => "H. sapiens"
-# 改变共享属性
+# 改一个共用的类属性
Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
-# 访问静态变量
-Human.grunt() # => "*grunt*"
+# 调用静态方法
+Human.grunt() # => "*grunt*"
####################################################
## 6. 模块
####################################################
-# 我们可以导入其他模块
+# 用import导入模块
import math
-print math.sqrt(16) # => 4.0
+print(math.sqrt(16)) # => 4.0
-# 我们也可以从一个模块中导入特定的函数
+# 也可以从模块中导入个别值
from math import ceil, floor
-print ceil(3.7) # => 4.0
-print floor(3.7) # => 3.0
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
-# 从模块中导入所有的函数
-# 警告:不推荐使用
+# 可以导入一个模块中所有值
+# 警告:不建议这么做
from math import *
-# 简写模块名
+# 如此缩写模块名字
import math as m
-math.sqrt(16) == m.sqrt(16) # => True
+math.sqrt(16) == m.sqrt(16) # => True
-# Python的模块其实只是普通的python文件
-# 你也可以创建自己的模块,并且导入它们
-# 模块的名字就和文件的名字相同
+# Python模块其实就是普通的Python文件。你可以自己写,然后导入,
+# 模块的名字就是文件的名字。
-# 也可以通过下面的方法查看模块中有什么属性和方法
+# 你可以这样列出一个模块里所有的值
import math
dir(math)
+####################################################
+## 7. 高级用法
+####################################################
+
+# 用生成器(generators)方便地写惰性运算
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的
+# 值全部算好。
+#
+# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。
+#
+# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。
+range_ = range(1, 900000000)
+# 当找到一个 >=30 的结果就会停
+# 这意味着 `double_numbers` 不会生成大于30的数。
+for i in double_numbers(range_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# 装饰器(decorators)
+# 这个例子中,beg装饰say
+# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print(say()) # Can you buy me a beer?
+print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
-## 更多阅读
+## 想继续学吗?
-希望学到更多?试试下面的链接:
+### 线上免费材料(英文)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2.6/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+
+* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/2/)
+* [Python Module of the Week](http://pymotw.com/3/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+
+### 书籍(也是英文)
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown
deleted file mode 100644
index fd962305..00000000
--- a/zh-cn/python3-cn.html.markdown
+++ /dev/null
@@ -1,632 +0,0 @@
----
-language: python3
-contributors:
- - ["Louie Dinh", "http://pythonpracticeprojects.com"]
- - ["Steven Basart", "http://github.com/xksteven"]
- - ["Andre Polykanine", "https://github.com/Oire"]
-translators:
- - ["Geoff Liu", "http://geoffliu.me"]
-filename: learnpython3-cn.py
-lang: zh-cn
----
-
-Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。
-它是如今最常用的编程语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。
-
-欢迎大家斧正。英文版原作 Louie Dinh [@louiedinh](http://twitter.com/louiedinh)
-邮箱 louiedinh [at] [谷歌的信箱服务]。中文翻译 Geoff Liu。
-
-注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/python/)。
-
-```python
-
-# 用井字符开头的是单行注释
-
-""" 多行字符串用三个引号
- 包裹,也常被用来做多
- 行注释
-"""
-
-####################################################
-## 1. 原始数据类型和运算符
-####################################################
-
-# 整数
-3 # => 3
-
-# 算术没有什么出乎意料的
-1 + 1 # => 2
-8 - 1 # => 7
-10 * 2 # => 20
-
-# 但是除法例外,会自动转换成浮点数
-35 / 5 # => 7.0
-5 / 3 # => 1.6666666666666667
-
-# 整数除法的结果都是向下取整
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # 浮点数也可以
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
-
-# 浮点数的运算结果也是浮点数
-3 * 2.0 # => 6.0
-
-# 模除
-7 % 3 # => 1
-
-# x的y次方
-2**4 # => 16
-
-# 用括号决定优先级
-(1 + 3) * 2 # => 8
-
-# 布尔值
-True
-False
-
-# 用not取非
-not True # => False
-not False # => True
-
-# 逻辑运算符,注意and和or都是小写
-True and False # => False
-False or True # => True
-
-# 整数也可以当作布尔值
-0 and 2 # => 0
--5 or 0 # => -5
-0 == False # => True
-2 == True # => False
-1 == True # => True
-
-# 用==判断相等
-1 == 1 # => True
-2 == 1 # => False
-
-# 用!=判断不等
-1 != 1 # => False
-2 != 1 # => True
-
-# 比较大小
-1 < 10 # => True
-1 > 10 # => False
-2 <= 2 # => True
-2 >= 2 # => True
-
-# 大小比较可以连起来!
-1 < 2 < 3 # => True
-2 < 3 < 2 # => False
-
-# 字符串用单引双引都可以
-"这是个字符串"
-'这也是个字符串'
-
-# 用加号连接字符串
-"Hello " + "world!" # => "Hello world!"
-
-# 字符串可以被当作字符列表
-"This is a string"[0] # => 'T'
-
-# 用.format来格式化字符串
-"{} can be {}".format("strings", "interpolated")
-
-# 可以重复参数以节省时间
-"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
-# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
-
-# 如果不想数参数,可以用关键字
-"{name} wants to eat {food}".format(name="Bob", food="lasagna")
-# => "Bob wants to eat lasagna"
-
-# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法
-"%s can be %s the %s way" % ("strings", "interpolated", "old")
-
-# None是一个对象
-None # => None
-
-# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。
-"etc" is None # => False
-None is None # => True
-
-# None,0,空字符串,空列表,空字典都算是False
-# 所有其他值都是True
-bool(0) # => False
-bool("") # => False
-bool([]) # => False
-bool({}) # => False
-
-
-####################################################
-## 2. 变量和集合
-####################################################
-
-# print是内置的打印函数
-print("I'm Python. Nice to meet you!")
-
-# 在给变量赋值前不用提前声明
-# 传统的变量命名是小写,用下划线分隔单词
-some_var = 5
-some_var # => 5
-
-# 访问未赋值的变量会抛出异常
-# 参考流程控制一段来学习异常处理
-some_unknown_var # 抛出NameError
-
-# 用列表(list)储存序列
-li = []
-# 创建列表时也可以同时赋给元素
-other_li = [4, 5, 6]
-
-# 用append在列表最后追加元素
-li.append(1) # li现在是[1]
-li.append(2) # li现在是[1, 2]
-li.append(4) # li现在是[1, 2, 4]
-li.append(3) # li现在是[1, 2, 4, 3]
-# 用pop从列表尾部删除
-li.pop() # => 3 且li现在是[1, 2, 4]
-# 把3再放回去
-li.append(3) # li变回[1, 2, 4, 3]
-
-# 列表存取跟数组一样
-li[0] # => 1
-# 取出最后一个元素
-li[-1] # => 3
-
-# 越界存取会造成IndexError
-li[4] # 抛出IndexError
-
-# 列表有切割语法
-li[1:3] # => [2, 4]
-# 取尾
-li[2:] # => [4, 3]
-# 取头
-li[:3] # => [1, 2, 4]
-# 隔一个取一个
-li[::2] # =>[1, 4]
-# 倒排列表
-li[::-1] # => [3, 4, 2, 1]
-# 可以用三个参数的任何组合来构建切割
-# li[始:终:步伐]
-
-# 用del删除任何一个元素
-del li[2] # li is now [1, 2, 3]
-
-# 列表可以相加
-# 注意:li和other_li的值都不变
-li + other_li # => [1, 2, 3, 4, 5, 6]
-
-# 用extend拼接列表
-li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6]
-
-# 用in测试列表是否包含值
-1 in li # => True
-
-# 用len取列表长度
-len(li) # => 6
-
-
-# 元组是不可改变的序列
-tup = (1, 2, 3)
-tup[0] # => 1
-tup[0] = 3 # 抛出TypeError
-
-# 列表允许的操作元组大都可以
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
-
-# 可以把元组合列表解包,赋值给变量
-a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3
-# 元组周围的括号是可以省略的
-d, e, f = 4, 5, 6
-# 交换两个变量的值就这么简单
-e, d = d, e # 现在d是5,e是4
-
-
-# 用字典表达映射关系
-empty_dict = {}
-# 初始化的字典
-filled_dict = {"one": 1, "two": 2, "three": 3}
-
-# 用[]取值
-filled_dict["one"] # => 1
-
-
-# 用 keys 获得所有的键。
-# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。
-# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。
-list(filled_dict.keys()) # => ["three", "two", "one"]
-
-
-# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。
-list(filled_dict.values()) # => [3, 2, 1]
-
-
-# 用in测试一个字典是否包含一个键
-"one" in filled_dict # => True
-1 in filled_dict # => False
-
-# 访问不存在的键会导致KeyError
-filled_dict["four"] # KeyError
-
-# 用get来避免KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
-# 当键不存在的时候get方法可以返回默认值
-filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
-
-# setdefault方法只有当键不存在的时候插入新值
-filled_dict.setdefault("five", 5) # filled_dict["five"]设为5
-filled_dict.setdefault("five", 6) # filled_dict["five"]还是5
-
-# 字典赋值
-filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
-filled_dict["four"] = 4 # 另一种赋值方法
-
-# 用del删除
-del filled_dict["one"] # 从filled_dict中把one删除
-
-
-# 用set表达集合
-empty_set = set()
-# 初始化一个集合,语法跟字典相似。
-some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4}
-
-# 可以把集合赋值于变量
-filled_set = some_set
-
-# 为集合添加元素
-filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5}
-
-# & 取交集
-other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
-
-# | 取并集
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-
-# - 取补集
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
-
-# in 测试集合是否包含元素
-2 in filled_set # => True
-10 in filled_set # => False
-
-
-####################################################
-## 3. 流程控制和迭代器
-####################################################
-
-# 先随便定义一个变量
-some_var = 5
-
-# 这是个if语句。注意缩进在Python里是有意义的
-# 印出"some_var比10小"
-if some_var > 10:
- print("some_var比10大")
-elif some_var < 10: # elif句是可选的
- print("some_var比10小")
-else: # else也是可选的
- print("some_var就是10")
-
-
-"""
-用for循环语句遍历列表
-打印:
- dog is a mammal
- cat is a mammal
- mouse is a mammal
-"""
-for animal in ["dog", "cat", "mouse"]:
- print("{} is a mammal".format(animal))
-
-"""
-"range(number)"返回数字列表从0到给的数字
-打印:
- 0
- 1
- 2
- 3
-"""
-for i in range(4):
- print(i)
-
-"""
-while循环直到条件不满足
-打印:
- 0
- 1
- 2
- 3
-"""
-x = 0
-while x < 4:
- print(x)
- x += 1 # x = x + 1 的简写
-
-# 用try/except块处理异常状况
-try:
- # 用raise抛出异常
- raise IndexError("This is an index error")
-except IndexError as e:
- pass # pass是无操作,但是应该在这里处理错误
-except (TypeError, NameError):
- pass # 可以同时处理不同类的错误
-else: # else语句是可选的,必须在所有的except之后
- print("All good!") # 只有当try运行完没有错误的时候这句才会运行
-
-
-# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列
-# 的对象。比如说上面range返回的对象就是可迭代的。
-
-filled_dict = {"one": 1, "two": 2, "three": 3}
-our_iterable = filled_dict.keys()
-print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一个实现可迭代接口的对象
-
-# 可迭代对象可以遍历
-for i in our_iterable:
- print(i) # 打印 one, two, three
-
-# 但是不可以随机访问
-our_iterable[1] # 抛出TypeError
-
-# 可迭代对象知道怎么生成迭代器
-our_iterator = iter(our_iterable)
-
-# 迭代器是一个可以记住遍历的位置的对象
-# 用__next__可以取得下一个元素
-our_iterator.__next__() # => "one"
-
-# 再一次调取__next__时会记得位置
-our_iterator.__next__() # => "two"
-our_iterator.__next__() # => "three"
-
-# 当迭代器所有元素都取出后,会抛出StopIteration
-our_iterator.__next__() # 抛出StopIteration
-
-# 可以用list一次取出迭代器所有的元素
-list(filled_dict.keys()) # => Returns ["one", "two", "three"]
-
-
-
-####################################################
-## 4. 函数
-####################################################
-
-# 用def定义新函数
-def add(x, y):
- print("x is {} and y is {}".format(x, y))
- return x + y # 用return语句返回
-
-# 调用函数
-add(5, 6) # => 印出"x is 5 and y is 6"并且返回11
-
-# 也可以用关键字参数来调用函数
-add(y=6, x=5) # 关键字参数可以用任何顺序
-
-
-# 我们可以定义一个可变参数函数
-def varargs(*args):
- return args
-
-varargs(1, 2, 3) # => (1, 2, 3)
-
-
-# 我们也可以定义一个关键字可变参数函数
-def keyword_args(**kwargs):
- return kwargs
-
-# 我们来看看结果是什么:
-keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
-
-
-# 这两种可变参数可以混着用
-def all_the_args(*args, **kwargs):
- print(args)
- print(kwargs)
-"""
-all_the_args(1, 2, a=3, b=4) prints:
- (1, 2)
- {"a": 3, "b": 4}
-"""
-
-# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。
-args = (1, 2, 3, 4)
-kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # 相当于 foo(1, 2, 3, 4)
-all_the_args(**kwargs) # 相当于 foo(a=3, b=4)
-all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4)
-
-
-# 函数作用域
-x = 5
-
-def setX(num):
- # 局部作用域的x和全局域的x是不同的
- x = num # => 43
- print (x) # => 43
-
-def setGlobalX(num):
- global x
- print (x) # => 5
- x = num # 现在全局域的x被赋值
- print (x) # => 6
-
-setX(43)
-setGlobalX(6)
-
-
-# 函数在Python是一等公民
-def create_adder(x):
- def adder(y):
- return x + y
- return adder
-
-add_10 = create_adder(10)
-add_10(3) # => 13
-
-# 也有匿名函数
-(lambda x: x > 2)(3) # => True
-
-# 内置的高阶函数
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-
-# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。
-[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
-
-####################################################
-## 5. 类
-####################################################
-
-
-# 定义一个继承object的类
-class Human(object):
-
- # 类属性,被所有此类的实例共用。
- species = "H. sapiens"
-
- # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属
- # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这
- # 种格式。
- def __init__(self, name):
- # Assign the argument to the instance's name attribute
- self.name = name
-
- # 实例方法,第一个参数总是self,就是这个实例对象
- def say(self, msg):
- return "{name}: {message}".format(name=self.name, message=msg)
-
- # 类方法,被所有此类的实例共用。第一个参数是这个类对象。
- @classmethod
- def get_species(cls):
- return cls.species
-
- # 静态方法。调用时没有实例或类的绑定。
- @staticmethod
- def grunt():
- return "*grunt*"
-
-
-# 构造一个实例
-i = Human(name="Ian")
-print(i.say("hi")) # 印出 "Ian: hi"
-
-j = Human("Joel")
-print(j.say("hello")) # 印出 "Joel: hello"
-
-# 调用一个类方法
-i.get_species() # => "H. sapiens"
-
-# 改一个共用的类属性
-Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
-
-# 调用静态方法
-Human.grunt() # => "*grunt*"
-
-
-####################################################
-## 6. 模块
-####################################################
-
-# 用import导入模块
-import math
-print(math.sqrt(16)) # => 4.0
-
-# 也可以从模块中导入个别值
-from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
-
-# 可以导入一个模块中所有值
-# 警告:不建议这么做
-from math import *
-
-# 如此缩写模块名字
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
-
-# Python模块其实就是普通的Python文件。你可以自己写,然后导入,
-# 模块的名字就是文件的名字。
-
-# 你可以这样列出一个模块里所有的值
-import math
-dir(math)
-
-
-####################################################
-## 7. 高级用法
-####################################################
-
-# 用生成器(generators)方便地写惰性运算
-def double_numbers(iterable):
- for i in iterable:
- yield i + i
-
-# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的
-# 值全部算好。
-#
-# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。
-#
-# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。
-range_ = range(1, 900000000)
-# 当找到一个 >=30 的结果就会停
-# 这意味着 `double_numbers` 不会生成大于30的数。
-for i in double_numbers(range_):
- print(i)
- if i >= 30:
- break
-
-
-# 装饰器(decorators)
-# 这个例子中,beg装饰say
-# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。
-from functools import wraps
-
-
-def beg(target_function):
- @wraps(target_function)
- def wrapper(*args, **kwargs):
- msg, say_please = target_function(*args, **kwargs)
- if say_please:
- return "{} {}".format(msg, "Please! I am poor :(")
- return msg
-
- return wrapper
-
-
-@beg
-def say(say_please=False):
- msg = "Can you buy me a beer?"
- return msg, say_please
-
-
-print(say()) # Can you buy me a beer?
-print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
-```
-
-## 想继续学吗?
-
-### 线上免费材料(英文)
-
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/3/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
-
-### 书籍(也是英文)
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
-
diff --git a/zh-cn/pythonlegacy-cn.html.markdown b/zh-cn/pythonlegacy-cn.html.markdown
new file mode 100644
index 00000000..756081d6
--- /dev/null
+++ b/zh-cn/pythonlegacy-cn.html.markdown
@@ -0,0 +1,476 @@
+---
+language: Python 2 (legacy)
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+translators:
+ - ["Chenbo Li", "http://binarythink.net"]
+filename: learnpythonlegacy-zh.py
+lang: zh-cn
+---
+
+Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语言之一
+我喜爱python是因为它有极为清晰的语法,甚至可以说,它就是可以执行的伪代码
+
+很欢迎来自您的反馈,你可以在[@louiedinh](http://twitter.com/louiedinh) 和 louiedinh [at] [google's email service] 这里找到我
+
+注意: 这篇文章针对的版本是Python 2.7,但大多也可使用于其他Python 2的版本
+如果是Python 3,请在网络上寻找其他教程
+
+```python
+
+# 单行注释
+""" 多行字符串可以用
+ 三个引号包裹,不过这也可以被当做
+ 多行注释
+"""
+
+####################################################
+## 1. 原始数据类型和操作符
+####################################################
+
+# 数字类型
+3 # => 3
+
+# 简单的算数
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7
+
+# 整数的除法会自动取整
+5 / 2 # => 2
+
+# 要做精确的除法,我们需要引入浮点数
+2.0 # 浮点数
+11.0 / 4.0 # => 2.75 精确多了
+
+# 括号具有最高优先级
+(1 + 3) * 2 # => 8
+
+# 布尔值也是基本的数据类型
+True
+False
+
+# 用 not 来取非
+not True # => False
+not False # => True
+
+# 相等
+1 == 1 # => True
+2 == 1 # => False
+
+# 不等
+1 != 1 # => False
+2 != 1 # => True
+
+# 更多的比较操作符
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# 比较运算可以连起来写!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# 字符串通过 " 或 ' 括起来
+"This is a string."
+'This is also a string.'
+
+# 字符串通过加号拼接
+"Hello " + "world!" # => "Hello world!"
+
+# 字符串可以被视为字符的列表
+"This is a string"[0] # => 'T'
+
+# % 可以用来格式化字符串
+"%s can be %s" % ("strings", "interpolated")
+
+# 也可以用 format 方法来格式化字符串
+# 推荐使用这个方法
+"{0} can be {1}".format("strings", "formatted")
+# 也可以用变量名代替数字
+"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+
+# None 是对象
+None # => None
+
+# 不要用相等 `==` 符号来和None进行比较
+# 要用 `is`
+"etc" is None # => False
+None is None # => True
+
+# 'is' 可以用来比较对象的相等性
+# 这个操作符在比较原始数据时没多少用,但是比较对象时必不可少
+
+# None, 0, 和空字符串都被算作 False
+# 其他的均为 True
+0 == False # => True
+"" == False # => True
+
+
+####################################################
+## 2. 变量和集合
+####################################################
+
+# 很方便的输出
+print "I'm Python. Nice to meet you!"
+
+
+# 给变量赋值前不需要事先声明
+some_var = 5 # 一般建议使用小写字母和下划线组合来做为变量名
+some_var # => 5
+
+# 访问未赋值的变量会抛出异常
+# 可以查看控制流程一节来了解如何异常处理
+some_other_var # 抛出 NameError
+
+# if 语句可以作为表达式来使用
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# 列表用来保存序列
+li = []
+# 可以直接初始化列表
+other_li = [4, 5, 6]
+
+# 在列表末尾添加元素
+li.append(1) # li 现在是 [1]
+li.append(2) # li 现在是 [1, 2]
+li.append(4) # li 现在是 [1, 2, 4]
+li.append(3) # li 现在是 [1, 2, 4, 3]
+# 移除列表末尾元素
+li.pop() # => 3 li 现在是 [1, 2, 4]
+# 重新加进去
+li.append(3) # li is now [1, 2, 4, 3] again.
+
+# 像其他语言访问数组一样访问列表
+li[0] # => 1
+# 访问最后一个元素
+li[-1] # => 3
+
+# 越界会抛出异常
+li[4] # 抛出越界异常
+
+# 切片语法需要用到列表的索引访问
+# 可以看做数学之中左闭右开区间
+li[1:3] # => [2, 4]
+# 省略开头的元素
+li[2:] # => [4, 3]
+# 省略末尾的元素
+li[:3] # => [1, 2, 4]
+
+# 删除特定元素
+del li[2] # li 现在是 [1, 2, 3]
+
+# 合并列表
+li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会不改变这两个列表
+
+# 通过拼接来合并列表
+li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6]
+
+# 用 in 来返回元素是否在列表中
+1 in li # => True
+
+# 返回列表长度
+len(li) # => 6
+
+
+# 元组类似于列表,但它是不可改变的
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # 类型错误
+
+# 对于大多数的列表操作,也适用于元组
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# 你可以将元组解包赋给多个变量
+a, b, c = (1, 2, 3) # a 是 1,b 是 2,c 是 3
+# 如果不加括号,将会被自动视为元组
+d, e, f = 4, 5, 6
+# 现在我们可以看看交换两个数字是多么容易的事
+e, d = d, e # d 是 5,e 是 4
+
+
+# 字典用来储存映射关系
+empty_dict = {}
+# 字典初始化
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# 字典也用中括号访问元素
+filled_dict["one"] # => 1
+
+# 把所有的键保存在列表中
+filled_dict.keys() # => ["three", "two", "one"]
+# 键的顺序并不是唯一的,得到的不一定是这个顺序
+
+# 把所有的值保存在列表中
+filled_dict.values() # => [3, 2, 1]
+# 和键的顺序相同
+
+# 判断一个键是否存在
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# 查询一个不存在的键会抛出 KeyError
+filled_dict["four"] # KeyError
+
+# 用 get 方法来避免 KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# get 方法支持在不存在的时候返回一个默认值
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+
+# setdefault 是一个更安全的添加字典元素的方法
+filled_dict.setdefault("five", 5) # filled_dict["five"] 的值为 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5
+
+
+# 集合储存无顺序的元素
+empty_set = set()
+# 初始化一个集合
+some_set = set([1, 2, 2, 3, 4]) # some_set 现在是 set([1, 2, 3, 4])
+
+# Python 2.7 之后,大括号可以用来表示集合
+filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+
+# 向集合添加元素
+filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5}
+
+# 用 & 来计算集合的交
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# 用 | 来计算集合的并
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# 用 - 来计算集合的差
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# 用 in 来判断元素是否存在于集合中
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+## 3. 控制流程
+####################################################
+
+# 新建一个变量
+some_var = 5
+
+# 这是个 if 语句,在 python 中缩进是很重要的。
+# 下面的代码片段将会输出 "some var is smaller than 10"
+if some_var > 10:
+ print "some_var is totally bigger than 10."
+elif some_var < 10: # 这个 elif 语句是不必须的
+ print "some_var is smaller than 10."
+else: # 这个 else 也不是必须的
+ print "some_var is indeed 10."
+
+
+"""
+用for循环遍历列表
+输出:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ # 你可以用 % 来格式化字符串
+ print "%s is a mammal" % animal
+
+"""
+`range(number)` 返回从0到给定数字的列表
+输出:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+while 循环
+输出:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # x = x + 1 的简写
+
+# 用 try/except 块来处理异常
+
+# Python 2.6 及以上适用:
+try:
+ # 用 raise 来抛出异常
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # pass 就是什么都不做,不过通常这里会做一些恢复工作
+
+
+####################################################
+## 4. 函数
+####################################################
+
+# 用 def 来新建函数
+def add(x, y):
+ print "x is %s and y is %s" % (x, y)
+ return x + y # 通过 return 来返回值
+
+# 调用带参数的函数
+add(5, 6) # => 输出 "x is 5 and y is 6" 返回 11
+
+# 通过关键字赋值来调用函数
+add(y=6, x=5) # 顺序是无所谓的
+
+# 我们也可以定义接受多个变量的函数,这些变量是按照顺序排列的
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1,2,3)
+
+
+# 我们也可以定义接受多个变量的函数,这些变量是按照关键字排列的
+def keyword_args(**kwargs):
+ return kwargs
+
+# 实际效果:
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+# 你也可以同时将一个函数定义成两种形式
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# 当调用函数的时候,我们也可以进行相反的操作,把元组和字典展开为参数
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # 等价于 foo(1, 2, 3, 4)
+all_the_args(**kwargs) # 等价于 foo(a=3, b=4)
+all_the_args(*args, **kwargs) # 等价于 foo(1, 2, 3, 4, a=3, b=4)
+
+# 函数在 python 中是一等公民
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# 匿名函数
+(lambda x: x > 2)(3) # => True
+
+# 内置高阶函数
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# 可以用列表方法来对高阶函数进行更巧妙的引用
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+####################################################
+## 5. 类
+####################################################
+
+# 我们新建的类是从 object 类中继承的
+class Human(object):
+
+ # 类属性,由所有类的对象共享
+ species = "H. sapiens"
+
+ # 基本构造函数
+ def __init__(self, name):
+ # 将参数赋给对象成员属性
+ self.name = name
+
+ # 成员方法,参数要有 self
+ def say(self, msg):
+ return "%s: %s" % (self.name, msg)
+
+ # 类方法由所有类的对象共享
+ # 这类方法在调用时,会把类本身传给第一个参数
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # 静态方法是不需要类和对象的引用就可以调用的方法
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# 实例化一个类
+i = Human(name="Ian")
+print i.say("hi") # 输出 "Ian: hi"
+
+j = Human("Joel")
+print j.say("hello") # 输出 "Joel: hello"
+
+# 访问类的方法
+i.get_species() # => "H. sapiens"
+
+# 改变共享属性
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# 访问静态变量
+Human.grunt() # => "*grunt*"
+
+
+####################################################
+## 6. 模块
+####################################################
+
+# 我们可以导入其他模块
+import math
+print math.sqrt(16) # => 4.0
+
+# 我们也可以从一个模块中导入特定的函数
+from math import ceil, floor
+print ceil(3.7) # => 4.0
+print floor(3.7) # => 3.0
+
+# 从模块中导入所有的函数
+# 警告:不推荐使用
+from math import *
+
+# 简写模块名
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Python的模块其实只是普通的python文件
+# 你也可以创建自己的模块,并且导入它们
+# 模块的名字就和文件的名字相同
+
+# 也可以通过下面的方法查看模块中有什么属性和方法
+import math
+dir(math)
+
+
+```
+
+## 更多阅读
+
+希望学到更多?试试下面的链接:
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/pythonlegacy-tw.html.markdown
index cd7481d7..575897e2 100644
--- a/zh-tw/python-tw.html.markdown
+++ b/zh-tw/pythonlegacy-tw.html.markdown
@@ -1,5 +1,5 @@
---
-language: python
+language: Python 2 (legacy)
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
@@ -7,7 +7,7 @@ contributors:
- ["evuez", "http://github.com/evuez"]
translators:
- ["Michael Yeh", "https://hinet60613.github.io/"]
-filename: learnpython-tw.py
+filename: learnpythonlegacy-tw.py
lang: zh-tw
---
@@ -16,7 +16,7 @@ Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行
非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。
註: 本篇文章適用的版本為Python 2.7,但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護,因此建議您可以從Python 3開始學Python。
-Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/).
+Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python/).
讓程式碼同時支援Python 2.7和3.X是可以做到的,只要引入
[`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組.