From 1adab9bc3f80d82123987ff34083568030735db7 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 04:49:56 +0100 Subject: Rename Python 2 markdown files into 'pythonlegacy' ``` for f in $(find . -iname "*python*" | grep -vE 'python3|git|statcomp'); do flegacy=$(echo "$f" | sed 's/python/pythonlegacy/') git mv "$f" "$flegacy" done ``` --- de-de/python-de.html.markdown | 766 --------------------------------- de-de/pythonlegacy-de.html.markdown | 766 +++++++++++++++++++++++++++++++++ es-es/python-es.html.markdown | 562 ------------------------ es-es/pythonlegacy-es.html.markdown | 562 ++++++++++++++++++++++++ fr-fr/python-fr.html.markdown | 488 --------------------- fr-fr/pythonlegacy-fr.html.markdown | 488 +++++++++++++++++++++ hu-hu/python-hu.html.markdown | 816 ----------------------------------- hu-hu/pythonlegacy-hu.html.markdown | 816 +++++++++++++++++++++++++++++++++++ it-it/python-it.html.markdown | 778 --------------------------------- it-it/pythonlegacy-it.html.markdown | 778 +++++++++++++++++++++++++++++++++ ko-kr/python-kr.html.markdown | 484 --------------------- ko-kr/pythonlegacy-kr.html.markdown | 484 +++++++++++++++++++++ pl-pl/python-pl.html.markdown | 640 ---------------------------- pl-pl/pythonlegacy-pl.html.markdown | 640 ++++++++++++++++++++++++++++ pt-br/python-pt.html.markdown | 509 ---------------------- pt-br/pythonlegacy-pt.html.markdown | 509 ++++++++++++++++++++++ python.html.markdown | 827 ------------------------------------ pythonlegacy.html.markdown | 827 ++++++++++++++++++++++++++++++++++++ ro-ro/python-ro.html.markdown | 493 --------------------- ro-ro/pythonlegacy-ro.html.markdown | 493 +++++++++++++++++++++ ru-ru/python-ru.html.markdown | 643 ---------------------------- ru-ru/pythonlegacy-ru.html.markdown | 643 ++++++++++++++++++++++++++++ tr-tr/python-tr.html.markdown | 502 ---------------------- tr-tr/pythonlegacy-tr.html.markdown | 502 ++++++++++++++++++++++ uk-ua/python-ua.html.markdown | 818 ----------------------------------- uk-ua/pythonlegacy-ua.html.markdown | 818 +++++++++++++++++++++++++++++++++++ zh-cn/python-cn.html.markdown | 476 --------------------- zh-cn/pythonlegacy-cn.html.markdown | 476 +++++++++++++++++++++ zh-tw/python-tw.html.markdown | 727 ------------------------------- zh-tw/pythonlegacy-tw.html.markdown | 727 +++++++++++++++++++++++++++++++ 30 files changed, 9529 insertions(+), 9529 deletions(-) delete mode 100644 de-de/python-de.html.markdown create mode 100644 de-de/pythonlegacy-de.html.markdown delete mode 100644 es-es/python-es.html.markdown create mode 100644 es-es/pythonlegacy-es.html.markdown delete mode 100644 fr-fr/python-fr.html.markdown create mode 100644 fr-fr/pythonlegacy-fr.html.markdown delete mode 100644 hu-hu/python-hu.html.markdown create mode 100644 hu-hu/pythonlegacy-hu.html.markdown delete mode 100644 it-it/python-it.html.markdown create mode 100644 it-it/pythonlegacy-it.html.markdown delete mode 100644 ko-kr/python-kr.html.markdown create mode 100644 ko-kr/pythonlegacy-kr.html.markdown delete mode 100644 pl-pl/python-pl.html.markdown create mode 100644 pl-pl/pythonlegacy-pl.html.markdown delete mode 100644 pt-br/python-pt.html.markdown create mode 100644 pt-br/pythonlegacy-pt.html.markdown delete mode 100644 python.html.markdown create mode 100644 pythonlegacy.html.markdown delete mode 100644 ro-ro/python-ro.html.markdown create mode 100644 ro-ro/pythonlegacy-ro.html.markdown delete mode 100644 ru-ru/python-ru.html.markdown create mode 100644 ru-ru/pythonlegacy-ru.html.markdown delete mode 100644 tr-tr/python-tr.html.markdown create mode 100644 tr-tr/pythonlegacy-tr.html.markdown delete mode 100644 uk-ua/python-ua.html.markdown create mode 100644 uk-ua/pythonlegacy-ua.html.markdown delete mode 100644 zh-cn/python-cn.html.markdown create mode 100644 zh-cn/pythonlegacy-cn.html.markdown delete mode 100644 zh-tw/python-tw.html.markdown create mode 100644 zh-tw/pythonlegacy-tw.html.markdown diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown deleted file mode 100644 index ee77683e..00000000 --- a/de-de/python-de.html.markdown +++ /dev/null @@ -1,766 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["kultprok", "http:/www.kulturproktologie.de"] -filename: learnpython-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__) # => (, - # => , ) - - # 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__) # => (, - # => , - # => , - # => , ) - - # 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/de-de/pythonlegacy-de.html.markdown b/de-de/pythonlegacy-de.html.markdown new file mode 100644 index 00000000..ee77683e --- /dev/null +++ b/de-de/pythonlegacy-de.html.markdown @@ -0,0 +1,766 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["kultprok", "http:/www.kulturproktologie.de"] +filename: learnpython-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__) # => (, + # => , ) + + # 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__) # => (, + # => , + # => , + # => , ) + + # 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/es-es/python-es.html.markdown b/es-es/python-es.html.markdown deleted file mode 100644 index 2b8f498a..00000000 --- a/es-es/python-es.html.markdown +++ /dev/null @@ -1,562 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Camilo Garrido", "http://www.twitter.com/hirohope"] - - ["Fabio Souto", "http://fabiosouto.me"] -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. -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 - como comentarios. -""" - -#################################################### -## 1. Tipos de datos primitivos y operadores. -#################################################### - -# 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 - -# 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 - -# 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 - -# 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 - -# Niega con 'not' -not True #=> False -not False #=> True - -# Igualdad es == -1 == 1 #=> True -2 == 1 #=> False - -# Desigualdad es != -1 != 1 #=> False -2 != 1 #=> True - -# Más comparaciones -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 - -# Strings se crean con " o ' -"Esto es un string." -'Esto también es un string' - -# ¡Strings también pueden ser sumados! -"Hola " + "mundo!" #=> "Hola mundo!" - -# 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") - -# 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 - -# No uses el símbolo de igualdad `==` para comparar objetos con None -# Usa `is` en lugar de -"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. -# Todos los otros valores son True -bool(0) #=> False -bool("") #=> False - - -#################################################### -## 2. Variables y Colecciones -#################################################### - -# 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 -una_variable #=> 5 - -# Acceder a variables no asignadas previamente es una excepción. -# 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 -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] -# Remueve del final de la lista con 'pop' -lista.pop() #=> 3 y lista ahora es [1, 2, 4] -# Pongámoslo de vuelta -lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. - -# Accede a una lista como lo harías con cualquier arreglo -lista[0] #=> 1 -# Mira el último elemento -lista[-1] #=> 3 - -# Mirar fuera de los límites es un error 'IndexError' -lista[4] # Levanta la excepción IndexError - -# Puedes mirar por rango con la sintáxis de trozo. -# (Es un rango cerrado/abierto para ustedes los matemáticos.) -lista[1:3] #=> [2, 4] -# Omite el inicio -lista[2:] #=> [4, 3] -# Omite el final -lista[:3] #=> [1, 2, 4] - -# Remueve elementos arbitrarios de una lista con 'del' -del lista[2] # lista ahora es [1, 2, 3] - -# Puedes sumar listas -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 -1 in lista #=> True - -# Examina el tamaño de una lista con 'len' -len(lista) #=> 6 - - -# Las tuplas son como las listas, pero son inmutables. -tupla = (1, 2, 3) -tupla[0] #=> 1 -tupla[0] = 3 # Levanta un error TypeError - -# También puedes hacer todas esas cosas que haces con listas -len(tupla) #=> 3 -tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tupla[:2] #=> (1, 2) -2 in tupla #=> True - -# Puedes desempacar tuplas (o listas) en variables -a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 -# Tuplas son creadas por defecto si omites los paréntesis -d, e, f = 4, 5, 6 -# Ahora mira que fácil es intercambiar dos valores -e, d = d, e # d ahora es 5 y e ahora es 4 - - -# Diccionarios almacenan mapeos -dicc_vacio = {} -# Aquí está un diccionario prellenado -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"] -# 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] -# Nota - Lo mismo que con las llaves, no se garantiza el orden. - -# Chequea la existencia de una llave en el diccionario con 'in' -"uno" in dicc_lleno #=> True -1 in dicc_lleno #=> False - -# Buscar una llave inexistente deriva en KeyError -dicc_lleno["cuatro"] # KeyError - -# Usa el método 'get' para evitar la excepción KeyError -dicc_lleno.get("uno") #=> 1 -dicc_lleno.get("cuatro") #=> None -# El método 'get' soporta un argumento por defecto cuando el valor no existe. -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 -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 - - -# 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} - -# Añade más valores a un conjunto -conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} - -# Haz intersección de conjuntos con & -otro_conjunto = {3, 4, 5, 6} -conjunto_lleno & otro_conjunto #=> {3, 4, 5} - -# Haz unión de conjuntos con | -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' -2 in conjunto_lleno #=> True -10 in conjunto_lleno #=> False - - -#################################################### -## 3. Control de Flujo -#################################################### - -# Hagamos sólo una variable -una_variable = 5 - -# 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." -elif una_variable < 10: # Este condición 'elif' es opcional. - print "una_variable es mas chica que 10." -else: # Esto también es opcional. - print "una_variable es de hecho 10." - - -""" -For itera sobre listas -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 - -""" -`range(número)` retorna una lista de números -desde cero hasta el número dado -imprime: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -While itera hasta que una condición no se cumple. -imprime: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - 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. - - -#################################################### -## 4. Funciones -#################################################### - -# Usa 'def' para crear nuevas funciones -def add(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 -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 - -varargs(1, 2, 3) #=> (1,2,3) - - -# Puedes definir funciones que toman un número variable de argumentos -# de palabras claves -def keyword_args(**kwargs): - return 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 - print kwargs -""" -todos_los_argumentos(1, 2, a=3, b=4) imprime: - (1, 2) - {"a": 3, "b": 4} -""" - -# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! -# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) -todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) -todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) - -# Python tiene funciones de primera clase -def crear_suma(x): - def suma(y): - return x + y - return suma - -sumar_10 = crear_suma(10) -sumar_10(3) #=> 13 - -# También hay funciones anónimas -(lambda x: x > 2)(3) #=> True - -# Hay funciones integradas de orden superior -map(sumar_10, [1,2,3]) #=> [11, 12, 13] -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] - -#################################################### -## 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 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 método de instancia. Todos los metodos toman self como primer argumento - def decir(self, msg): - return "%s: %s" % (self.nombre, msg) - - # Un metodo de clase es compartido a través de todas las instancias - # Son llamados con la clase como primer argumento - @classmethod - def get_especie(cls): - return cls.especie - - # Un metodo estático es llamado sin la clase o instancia como referencia - @staticmethod - def roncar(): - return "*roncar*" - - -# Instancia una clase -i = Humano(nombre="Ian") -print i.decir("hi") # imprime "Ian: hi" - -j = Humano("Joel") -print j.decir("hello") #imprime "Joel: hello" - -# Llama nuestro método de clase -i.get_especie() #=> "H. sapiens" - -# Cambia los atributos compartidos -Humano.especie = "H. neanderthalensis" -i.get_especie() #=> "H. neanderthalensis" -j.get_especie() #=> "H. neanderthalensis" - -# Llama al método estático -Humano.roncar() #=> "*roncar*" - - -#################################################### -## 6. Módulos -#################################################### - -# Puedes importar módulos -import math -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 - -# Puedes importar todas las funciones de un módulo -# Precaución: Esto no es recomendable -from math import * - -# Puedes acortar los nombres de los módulos -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Los módulos de Python son sólo archivos ordinarios de Python. -# Puedes escribir tus propios módulos e importarlos. El nombre del módulo -# es el mismo del nombre del archivo. - -# Puedes encontrar que funciones y atributos definen un módulo. -import math -dir(math) - - -#################################################### -## 7. Avanzado -#################################################### - -# 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 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 rodea a hablar -# Si por_favor es True se cambiará el mensaje. -from functools import wraps - - -def pedir(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, por_favor = target_function(*args, **kwargs) - if por_favor: - return "{} {}".format(msg, "¡Por favor! Soy pobre :(") - return msg - - return wrapper - - -@pedir -def hablar(por_favor=False): - msg = "¿Me puedes comprar una cerveza?" - return msg, por_favor - -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? - -### Gratis y en línea - -* [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/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### Encuadernados - -* [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/es-es/pythonlegacy-es.html.markdown b/es-es/pythonlegacy-es.html.markdown new file mode 100644 index 00000000..2b8f498a --- /dev/null +++ b/es-es/pythonlegacy-es.html.markdown @@ -0,0 +1,562 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Camilo Garrido", "http://www.twitter.com/hirohope"] + - ["Fabio Souto", "http://fabiosouto.me"] +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. +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 + como comentarios. +""" + +#################################################### +## 1. Tipos de datos primitivos y operadores. +#################################################### + +# 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 + +# 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 + +# 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 + +# 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 + +# Niega con 'not' +not True #=> False +not False #=> True + +# Igualdad es == +1 == 1 #=> True +2 == 1 #=> False + +# Desigualdad es != +1 != 1 #=> False +2 != 1 #=> True + +# Más comparaciones +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 + +# Strings se crean con " o ' +"Esto es un string." +'Esto también es un string' + +# ¡Strings también pueden ser sumados! +"Hola " + "mundo!" #=> "Hola mundo!" + +# 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") + +# 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 + +# No uses el símbolo de igualdad `==` para comparar objetos con None +# Usa `is` en lugar de +"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. +# Todos los otros valores son True +bool(0) #=> False +bool("") #=> False + + +#################################################### +## 2. Variables y Colecciones +#################################################### + +# 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 +una_variable #=> 5 + +# Acceder a variables no asignadas previamente es una excepción. +# 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 +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] +# Remueve del final de la lista con 'pop' +lista.pop() #=> 3 y lista ahora es [1, 2, 4] +# Pongámoslo de vuelta +lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. + +# Accede a una lista como lo harías con cualquier arreglo +lista[0] #=> 1 +# Mira el último elemento +lista[-1] #=> 3 + +# Mirar fuera de los límites es un error 'IndexError' +lista[4] # Levanta la excepción IndexError + +# Puedes mirar por rango con la sintáxis de trozo. +# (Es un rango cerrado/abierto para ustedes los matemáticos.) +lista[1:3] #=> [2, 4] +# Omite el inicio +lista[2:] #=> [4, 3] +# Omite el final +lista[:3] #=> [1, 2, 4] + +# Remueve elementos arbitrarios de una lista con 'del' +del lista[2] # lista ahora es [1, 2, 3] + +# Puedes sumar listas +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 +1 in lista #=> True + +# Examina el tamaño de una lista con 'len' +len(lista) #=> 6 + + +# Las tuplas son como las listas, pero son inmutables. +tupla = (1, 2, 3) +tupla[0] #=> 1 +tupla[0] = 3 # Levanta un error TypeError + +# También puedes hacer todas esas cosas que haces con listas +len(tupla) #=> 3 +tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tupla[:2] #=> (1, 2) +2 in tupla #=> True + +# Puedes desempacar tuplas (o listas) en variables +a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 +# Tuplas son creadas por defecto si omites los paréntesis +d, e, f = 4, 5, 6 +# Ahora mira que fácil es intercambiar dos valores +e, d = d, e # d ahora es 5 y e ahora es 4 + + +# Diccionarios almacenan mapeos +dicc_vacio = {} +# Aquí está un diccionario prellenado +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"] +# 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] +# Nota - Lo mismo que con las llaves, no se garantiza el orden. + +# Chequea la existencia de una llave en el diccionario con 'in' +"uno" in dicc_lleno #=> True +1 in dicc_lleno #=> False + +# Buscar una llave inexistente deriva en KeyError +dicc_lleno["cuatro"] # KeyError + +# Usa el método 'get' para evitar la excepción KeyError +dicc_lleno.get("uno") #=> 1 +dicc_lleno.get("cuatro") #=> None +# El método 'get' soporta un argumento por defecto cuando el valor no existe. +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 +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 + + +# 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} + +# Añade más valores a un conjunto +conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} + +# Haz intersección de conjuntos con & +otro_conjunto = {3, 4, 5, 6} +conjunto_lleno & otro_conjunto #=> {3, 4, 5} + +# Haz unión de conjuntos con | +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' +2 in conjunto_lleno #=> True +10 in conjunto_lleno #=> False + + +#################################################### +## 3. Control de Flujo +#################################################### + +# Hagamos sólo una variable +una_variable = 5 + +# 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." +elif una_variable < 10: # Este condición 'elif' es opcional. + print "una_variable es mas chica que 10." +else: # Esto también es opcional. + print "una_variable es de hecho 10." + + +""" +For itera sobre listas +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 + +""" +`range(número)` retorna una lista de números +desde cero hasta el número dado +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While itera hasta que una condición no se cumple. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + 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. + + +#################################################### +## 4. Funciones +#################################################### + +# Usa 'def' para crear nuevas funciones +def add(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 +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 + +varargs(1, 2, 3) #=> (1,2,3) + + +# Puedes definir funciones que toman un número variable de argumentos +# de palabras claves +def keyword_args(**kwargs): + return 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 + print kwargs +""" +todos_los_argumentos(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! +# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) +todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) +todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Python tiene funciones de primera clase +def crear_suma(x): + def suma(y): + return x + y + return suma + +sumar_10 = crear_suma(10) +sumar_10(3) #=> 13 + +# También hay funciones anónimas +(lambda x: x > 2)(3) #=> True + +# Hay funciones integradas de orden superior +map(sumar_10, [1,2,3]) #=> [11, 12, 13] +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] + +#################################################### +## 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 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 método de instancia. Todos los metodos toman self como primer argumento + def decir(self, msg): + return "%s: %s" % (self.nombre, msg) + + # Un metodo de clase es compartido a través de todas las instancias + # Son llamados con la clase como primer argumento + @classmethod + def get_especie(cls): + return cls.especie + + # Un metodo estático es llamado sin la clase o instancia como referencia + @staticmethod + def roncar(): + return "*roncar*" + + +# Instancia una clase +i = Humano(nombre="Ian") +print i.decir("hi") # imprime "Ian: hi" + +j = Humano("Joel") +print j.decir("hello") #imprime "Joel: hello" + +# Llama nuestro método de clase +i.get_especie() #=> "H. sapiens" + +# Cambia los atributos compartidos +Humano.especie = "H. neanderthalensis" +i.get_especie() #=> "H. neanderthalensis" +j.get_especie() #=> "H. neanderthalensis" + +# Llama al método estático +Humano.roncar() #=> "*roncar*" + + +#################################################### +## 6. Módulos +#################################################### + +# Puedes importar módulos +import math +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 + +# Puedes importar todas las funciones de un módulo +# Precaución: Esto no es recomendable +from math import * + +# Puedes acortar los nombres de los módulos +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Los módulos de Python son sólo archivos ordinarios de Python. +# Puedes escribir tus propios módulos e importarlos. El nombre del módulo +# es el mismo del nombre del archivo. + +# Puedes encontrar que funciones y atributos definen un módulo. +import math +dir(math) + + +#################################################### +## 7. Avanzado +#################################################### + +# 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 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 rodea a hablar +# Si por_favor es True se cambiará el mensaje. +from functools import wraps + + +def pedir(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, por_favor = target_function(*args, **kwargs) + if por_favor: + return "{} {}".format(msg, "¡Por favor! Soy pobre :(") + return msg + + return wrapper + + +@pedir +def hablar(por_favor=False): + msg = "¿Me puedes comprar una cerveza?" + return msg, por_favor + +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? + +### Gratis y en línea + +* [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/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Encuadernados + +* [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/python-fr.html.markdown b/fr-fr/python-fr.html.markdown deleted file mode 100644 index 0ae410de..00000000 --- a/fr-fr/python-fr.html.markdown +++ /dev/null @@ -1,488 +0,0 @@ ---- -language: python -filename: learnpython-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/fr-fr/pythonlegacy-fr.html.markdown b/fr-fr/pythonlegacy-fr.html.markdown new file mode 100644 index 00000000..0ae410de --- /dev/null +++ b/fr-fr/pythonlegacy-fr.html.markdown @@ -0,0 +1,488 @@ +--- +language: python +filename: learnpython-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/python-hu.html.markdown deleted file mode 100644 index 01f1c414..00000000 --- a/hu-hu/python-hu.html.markdown +++ /dev/null @@ -1,816 +0,0 @@ ---- -language: python -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"] -translators: - - ["Tamás Diószegi", "https://github.com/ditam"] -filename: learnpython-hu.py -lang: hu-hu ---- - -A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az -egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem -bele. Tulajdonképpen futtatható pszeudokód. - -Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh) -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/) -ajánlott. - -Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x -verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával. -A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami -Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott. - -```python - -# Az egysoros kommentek kettőskereszttel kezdődnek - -""" Többsoros stringeket három darab " közé - fogva lehet írni, ezeket gyakran használják - több soros kommentként. -""" - -#################################################### -# 1. Egyszerű adattípusok és operátorok -#################################################### - -# Használhatsz számokat -3 # => 3 - -# Az alapműveletek meglepetésektől mentesek -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része -# lesz az eredmény -5 / 2 # => 2 - -# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk -2.0 # Ez egy float -11.0 / 4.0 # => 2.75 áh... máris jobb - -# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # floatok esetén is --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Ha importáljuk a division modult (ld. 6. Modulok rész), -# akkor a '/' jellel pontos osztást tudunk végezni. -from __future__ import division - -11 / 4 # => 2.75 ...sima osztás -11 // 4 # => 2 ...egész osztás - -# Modulo művelet -7 % 3 # => 1 - -# Hatványozás (x az y. hatványra) -2 ** 4 # => 16 - -# A precedencia zárójelekkel befolyásolható -(1 + 3) * 2 # => 8 - -# Logikai operátorok -# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes -True and False # => False -False or True # => True - -# A logikai operátorok egészeken is használhatóak -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True - -# Negálni a not kulcsszóval lehet -not True # => False -not False # => True - -# Egyenlőségvizsgálat == -1 == 1 # => True -2 == 1 # => False - -# Egyenlőtlenség != -1 != 1 # => False -2 != 1 # => True - -# További összehasonlítások -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Az összehasonlítások láncolhatóak! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Stringeket " vagy ' jelek közt lehet megadni -"Ez egy string." -'Ez egy másik string.' - -# A stringek összeadhatóak! -"Hello " + "world!" # => "Hello world!" -# '+' jel nélkül is összeadhatóak -"Hello " "world!" # => "Hello world!" - -# ... illetve szorozhatóak -"Hello" * 3 # => "HelloHelloHello" - -# Kezelhető karakterek indexelhető listájaként -"This is a string"[0] # => 'T' - -# A string hosszát a len függvény adja meg -len("This is a string") # => 16 - -# String formázáshoz a % jel használható -# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog -# kerülni, de azért jó tudni, hogyan működik. -x = 'alma' -y = 'citrom' -z = "A kosárban levő elemek: %s és %s" % (x, y) - -# A string formázás újabb módja a format metódus használatával történik. -# Jelenleg ez a javasolt megoldás. -"{} egy {} szöveg".format("Ez", "helytartó") -"A {0} pedig {1}".format("string", "formázható") -# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók. -"{name} kedvence a {food}".format(name="Bob", food="lasagna") - -# None egy objektum -None # => None - -# A None-nal való összehasonlításhoz ne használd a "==" jelet, -# használd az "is" kulcsszót helyette -"etc" is None # => False -None is None # => True - -# Az 'is' operátor objektum egyezést vizsgál. -# Primitív típusok esetén ez nem túl hasznos, -# objektumok esetén azonban annál inkább. - -# Bármilyen objektum használható logikai kontextusban. -# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek): -# - None -# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j) -# - üres sorozatok (pl. '', (), []) -# - üres konténerek (pl., {}, set()) -# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint, -# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ -# -# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki) -bool(0) # => False -bool("") # => False - - -#################################################### -# 2. Változók és kollekciók -#################################################### - -# Létezik egy print utasítás -print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! - -# Így lehet egyszerűen bemenetet kérni a konzolról: -input_string_var = raw_input( - "Enter some data: ") # Visszatér a megadott stringgel -input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként -# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni -# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve - -# A változókat nem szükséges a használat előtt deklarálni -some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas -some_var # => 5 - -# Érték nélküli változóra hivatkozás hibát dob. -# Lásd a Control Flow szekciót a kivételkezelésről. -some_other_var # name error hibát dob - -# az if használható kifejezésként -# a C nyelv '?:' ternáris operátorával egyenértékűen -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# A listákban sorozatok tárolhatóak -li = [] -# Már inicializáláskor megadhatóak elemek -other_li = [4, 5, 6] - -# A lista végére az append metódus rak új elemet -li.append(1) # li jelenleg [1] -li.append(2) # li jelenleg [1, 2] -li.append(4) # li jelenleg [1, 2, 4] -li.append(3) # li jelenleg [1, 2, 4, 3] -# A végéről a pop metódus távolít el elemet -li.pop() # => 3 és li jelenleg [1, 2, 4] -# Rakjuk vissza -li.append(3) # li jelenleg [1, 2, 4, 3], újra. - -# A lista elemeket tömb indexeléssel lehet hivatkozni -li[0] # => 1 -# A már inicializált értékekhez a = jellel lehet új értéket rendelni -li[0] = 42 -li[0] # => 42 -li[0] = 1 # csak visszaállítjuk az eredeti értékére -# Így is lehet az utolsó elemre hivatkozni -li[-1] # => 3 - -# A túlindexelés eredménye IndexError -li[4] # IndexError hibát dob - -# A lista részeit a slice szintaxissal lehet kimetszeni -# (Matekosoknak ez egy zárt/nyitott intervallum.) -li[1:3] # => [2, 4] -# A lista eleje kihagyható így -li[2:] # => [4, 3] -# Kihagyható a vége -li[:3] # => [1, 2, 4] -# Minden második elem kiválasztása -li[::2] # =>[1, 4] -# A lista egy másolata, fordított sorrendben -li[::-1] # => [3, 4, 2, 1] -# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek -# li[start:end:step] - -# Listaelemek a "del" paranccsal törölhetőek -del li[2] # li jelenleg [1, 2, 3] - -# A listák összeadhatóak -li + other_li # => [1, 2, 3, 4, 5, 6] -# Megjegyzés: az eredeti li és other_li értékei változatlanok - -# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal -li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6] - -# Egy elem első előfordulásának eltávolítása -li.remove(2) # li jelenleg [1, 3, 4, 5, 6] -li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában - -# Elemek beszúrhatóak tetszőleges helyre -li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét - -# Egy elem első előfordulási helye -li.index(2) # => 1 -li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában - -# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető -1 in li # => True - -# A lista hossza a "len()" függvénnyel -len(li) # => 6 - -# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # TypeError hibát dob - -# Az összes lista-műveletet ezeken is használható -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Az N-esek (és listák) kicsomagolhatóak külön változókba -a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3 -d, e, f = 4, 5, 6 # a zárójel elhagyható -# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik -g = 4, 5, 6 # => (4, 5, 6) -# Nézd, milyen egyszerű két értéket megcserélni -e, d = d, e # d most már 5 és az e 4 - -# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók -empty_dict = {} -# Ez pedig rögtön értékekkel van inicializálva -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Egy dictionary értékei [] jelek közt indexelhetőek -filled_dict["one"] # => 1 - -# A "keys()" metódus visszatér a kulcsok listájával -filled_dict.keys() # => ["three", "two", "one"] -# Megjegyzés: egy dictionary párjainak sorrendje nem garantált -# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket. - -# Az értékek listája a "values()" metódussal kérhető le -filled_dict.values() # => [3, 2, 1] -# ld. a fenti megjegyzést az elemek sorrendjéről. - -# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal -filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] - -# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben -"one" in filled_dict # => True -1 in filled_dict # => False - -# Nem létező kulcs hivatkozása KeyError hibát dob -filled_dict["four"] # KeyError - -# A "get()" metódus használatával elkerülhető a KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 -# Megjegyzés: ettől még filled_dict.get("four") => None -# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben) - -# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek: -filled_dict["four"] = 4 # ez után filled_dict["four"] => 4 - -# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva -filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re -filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5 - -# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat -empty_set = set() -# Inicializáljuk ezt a halmazt néhány elemmel -some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4]) - -# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet -another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4]) - -# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Új halmaz-elemek hozzáadása -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} - -# Halmaz metszés a & operátorral -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Halmaz unió | operátorral -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Halmaz különbség - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Szimmetrikus differencia ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit -{1, 2} >= {1, 2, 3} # => False - -# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak -{1, 2} <= {1, 2, 3} # => True - -# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -# 3. Control Flow -#################################################### - -# Legyen egy változónk -some_var = 5 - -# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben! -# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél" -if some_var > 10: - print "some_var nagyobb, mint 10." -elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben. - print "some_var kisebb 10-nél" -else: # Ez sem kötelező. - print "some_var kereken 10." - -""" -For ciklusokkal végigiterálhatunk listákon -a kimenet: - A(z) kutya emlős - A(z) macska emlős - A(z) egér emlős -""" -for animal in ["kutya", "macska", "egér"]: - # A {0} kifejezéssel formázzuk a stringet, ld. korábban. - print "A(z) {0} emlős".format(animal) - -""" -"range(number)" visszatér számok listájával 0-től number-ig -a kimenet: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -"range(lower, upper)" visszatér a lower és upper közti számok listájával -a kimenet: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print i - -""" -A while ciklus a feltétel hamissá válásáig fut. -a kimenet: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Rövidítés az x = x + 1 kifejezésre - -# A kivételek try/except blokkokkal kezelhetőek - -# Python 2.6-tól felfele: -try: - # A "raise" szóval lehet hibát dobni - raise IndexError("Ez egy index error") -except IndexError as e: - pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat. -except (TypeError, NameError): - pass # Ha szükséges, egyszerre több hiba típus is kezelhető -else: # Az except blokk után opcionálisan megadható - print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák -finally: # Mindenképpen lefut - print "Itt felszabadíthatjuk az erőforrásokat például" - -# Az erőforrások felszabadításához try/finally helyett a with használható -with open("myfile.txt") as f: - for line in f: - print line - - -#################################################### -# 4. Függvények -#################################################### - -# A "def" szóval hozhatunk létre új függvényt -def add(x, y): - print "x is {0} and y is {1}".format(x, y) - return x + y # A return szóval tudunk értékeket visszaadni - - -# Így hívunk függvényt paraméterekkel -add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11 - -# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt -add(y=6, x=5) # Ez esetben a sorrendjük nem számít - - -# Változó számú paramétert fogadó függvény így definiálható. -# A * használatával a paramétereket egy N-esként kapjuk meg. -def varargs(*args): - return args - - -varargs(1, 2, 3) # => (1, 2, 3) - - -# Változó számú nevesített paramétert fogadó függvény is megadható, -# a ** használatával a paramétereket egy dictionary-ként kapjuk meg -def keyword_args(**kwargs): - return kwargs - - -# Nézzük meg, mi történik -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# A két módszer egyszerre is használható -def all_the_args(*args, **kwargs): - print args - print kwargs - - -""" -all_the_args(1, 2, a=3, b=4) kimenete: - (1, 2) - {"a": 3, "b": 4} -""" - -# Függvények hívásakor a fenti args és kwargs módszerek inverze használható -# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4) -all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4) -all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4) - - -# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek, -# a * illetve ** operátorokkal kifejtve -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - - -# Függvény scope -x = 5 - - -def set_x(num): - # A lokális x változó nem ugyanaz, mint a globális x - x = num # => 43 - print x # => 43 - - -def set_global_x(num): - global x - print x # => 5 - x = num # a globális x-et 6-ra állítjuk - print x # => 6 - - -set_x(43) -set_global_x(6) - - -# A pythonban a függvény elsőrendű (ún. "first class") típus -def create_adder(x): - def adder(y): - return x + y - - return adder - - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Névtelen függvények is definiálhatóak -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Léteznek beépített magasabb rendű függvények -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] - -# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel -[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] - -# halmaz és dictionary képzők is léteznek -{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. Osztályok -#################################################### - -# Az object osztály egy alosztályát képezzük -class Human(object): - # Osztály szintű mező: az osztály összes példányában azonos - species = "H. sapiens" - - # Ez a függvény meghívódik az osztály példányosításakor. - # Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python - # előre definiált, a nyelv által belsőleg használt, de a felhasználó által - # is látható objektumok és mezők neveire. - # Ne vezessünk be új, ilyen elnevezési sémát használó neveket! - def __init__(self, name): - # A paramétert értékül adjuk a példány name attribútumának - self.name = name - - # Inicializálunk egy mezőt - self.age = 0 - - # Példány metódus. Minden metódus első paramétere a "self", a példány maga - def say(self, msg): - return "{0}: {1}".format(self.name, msg) - - # Egy osztálymetódus az osztály összes példány közt meg van osztva. - # Hívásukkor az első paraméter mindig a hívó osztály. - @classmethod - def get_species(cls): - return cls.species - - # Egy statikus metódus osztály és példányreferencia nélkül hívódik - @staticmethod - def grunt(): - return "*grunt*" - - # Egy property jelölésű függvény olyan, mint egy getter. - # Használatával az age mező egy csak-olvasható attribútummá válik. - @property - def age(self): - return self._age - - # Így lehet settert megadni egy mezőhöz - @age.setter - def age(self, age): - self._age = age - - # Így lehet egy mező törlését engedélyezni - @age.deleter - def age(self): - del self._age - - -# Példányosítsuk az osztályt -i = Human(name="Ian") -print i.say("hi") # kimenet: "Ian: hi" - -j = Human("Joel") -print j.say("hello") # kimenet: "Joel: hello" - -# Hívjuk az osztály metódusunkat -i.get_species() # => "H. sapiens" - -# Változtassuk meg az osztály szintű attribútumot -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Hívjuk meg a statikus metódust -Human.grunt() # => "*grunt*" - -# Adjunk új értéket a mezőnek -i.age = 42 - -# Kérjük le a mező értékét -i.age # => 42 - -# Töröljük a mezőt -del i.age -i.age # => AttributeError hibát dob - -#################################################### -# 6. Modulok -#################################################### - -# Modulokat így lehet importálni -import math - -print math.sqrt(16) # => 4.0 - -# Lehetséges csak bizonyos függvényeket importálni egy modulból -from math import ceil, floor - -print ceil(3.7) # => 4.0 -print floor(3.7) # => 3.0 - -# Egy modul összes függvénye is importálható -# Vigyázat: ez nem ajánlott. -from math import * - -# A modulok nevei lerövidíthetőek -import math as m - -math.sqrt(16) == m.sqrt(16) # => True -# Meggyőződhetünk róla, hogy a függvények valóban azonosak -from math import sqrt - -math.sqrt == m.sqrt == sqrt # => True - -# A Python modulok egyszerű fájlok. -# Írhatsz sajátot és importálhatod is. -# A modul neve azonos a tartalmazó fájl nevével. - -# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul. -import math - -dir(math) - - -# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos -# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett. -# A lokális mappa prioritást élvez a beépített könyvtárak felett. - - -#################################################### -# 7. Haladóknak -#################################################### - -# Generátorok -# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket. - -# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit, -# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat! -def double_numbers(iterable): - double_arr = [] - for i in iterable: - double_arr.append(i + i) - return double_arr - - -# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk -# ezt a nagy listát a ciklus vezérléséhez. -for value in double_numbers(range(1000000)): # `test_non_generator` - print value - if value > 5: - break - - -# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet, -# amikor azt kérik tőle -def double_numbers_generator(iterable): - for i in iterable: - yield i + i - - -# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt. -# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak -# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!). -for value in double_numbers_generator(xrange(1000000)): # `test_generator` - print value - if value > 5: - break - -# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén -# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a -# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range` -# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük -# - esetünkben a ciklus következő iterációjakor - -# A lista képzéshez hasonlóan generátor képzőket is használhatunk -# ("generator comprehensions"). -values = (-x for x in [1, 2, 3, 4, 5]) -for x in values: - print(x) # kimenet: -1 -2 -3 -4 -5 - -# Egy generátor összes generált elemét listaként is elkérhetjük: -values = (-x for x in [1, 2, 3, 4, 5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - -# Dekorátorok -# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény. -# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény -# kimenetébe beszúrja az 'Apple' elemet. -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'] - -# A kimenet tartalmazza az 'Apple' elemet: -# Banana, Mango, Orange, Apple -print ', '.join(get_fruits()) - -# Ebben a példában a beg dekorátorral látjuk el a say függvényt. -# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor -# megváltoztatja az eredmény mondatot. -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 :( -``` - -## Még több érdekel? - -### Ingyenes online tartalmak - -* [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/) - -### Könyvek - -* [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/pythonlegacy-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown new file mode 100644 index 00000000..01f1c414 --- /dev/null +++ b/hu-hu/pythonlegacy-hu.html.markdown @@ -0,0 +1,816 @@ +--- +language: python +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"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +filename: learnpython-hu.py +lang: hu-hu +--- + +A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az +egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem +bele. Tulajdonképpen futtatható pszeudokód. + +Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh) +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/) +ajánlott. + +Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x +verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával. +A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami +Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott. + +```python + +# Az egysoros kommentek kettőskereszttel kezdődnek + +""" Többsoros stringeket három darab " közé + fogva lehet írni, ezeket gyakran használják + több soros kommentként. +""" + +#################################################### +# 1. Egyszerű adattípusok és operátorok +#################################################### + +# Használhatsz számokat +3 # => 3 + +# Az alapműveletek meglepetésektől mentesek +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része +# lesz az eredmény +5 / 2 # => 2 + +# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk +2.0 # Ez egy float +11.0 / 4.0 # => 2.75 áh... máris jobb + +# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # floatok esetén is +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Ha importáljuk a division modult (ld. 6. Modulok rész), +# akkor a '/' jellel pontos osztást tudunk végezni. +from __future__ import division + +11 / 4 # => 2.75 ...sima osztás +11 // 4 # => 2 ...egész osztás + +# Modulo művelet +7 % 3 # => 1 + +# Hatványozás (x az y. hatványra) +2 ** 4 # => 16 + +# A precedencia zárójelekkel befolyásolható +(1 + 3) * 2 # => 8 + +# Logikai operátorok +# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes +True and False # => False +False or True # => True + +# A logikai operátorok egészeken is használhatóak +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Negálni a not kulcsszóval lehet +not True # => False +not False # => True + +# Egyenlőségvizsgálat == +1 == 1 # => True +2 == 1 # => False + +# Egyenlőtlenség != +1 != 1 # => False +2 != 1 # => True + +# További összehasonlítások +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Az összehasonlítások láncolhatóak! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Stringeket " vagy ' jelek közt lehet megadni +"Ez egy string." +'Ez egy másik string.' + +# A stringek összeadhatóak! +"Hello " + "world!" # => "Hello world!" +# '+' jel nélkül is összeadhatóak +"Hello " "world!" # => "Hello world!" + +# ... illetve szorozhatóak +"Hello" * 3 # => "HelloHelloHello" + +# Kezelhető karakterek indexelhető listájaként +"This is a string"[0] # => 'T' + +# A string hosszát a len függvény adja meg +len("This is a string") # => 16 + +# String formázáshoz a % jel használható +# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog +# kerülni, de azért jó tudni, hogyan működik. +x = 'alma' +y = 'citrom' +z = "A kosárban levő elemek: %s és %s" % (x, y) + +# A string formázás újabb módja a format metódus használatával történik. +# Jelenleg ez a javasolt megoldás. +"{} egy {} szöveg".format("Ez", "helytartó") +"A {0} pedig {1}".format("string", "formázható") +# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók. +"{name} kedvence a {food}".format(name="Bob", food="lasagna") + +# None egy objektum +None # => None + +# A None-nal való összehasonlításhoz ne használd a "==" jelet, +# használd az "is" kulcsszót helyette +"etc" is None # => False +None is None # => True + +# Az 'is' operátor objektum egyezést vizsgál. +# Primitív típusok esetén ez nem túl hasznos, +# objektumok esetén azonban annál inkább. + +# Bármilyen objektum használható logikai kontextusban. +# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek): +# - None +# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j) +# - üres sorozatok (pl. '', (), []) +# - üres konténerek (pl., {}, set()) +# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint, +# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki) +bool(0) # => False +bool("") # => False + + +#################################################### +# 2. Változók és kollekciók +#################################################### + +# Létezik egy print utasítás +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# Így lehet egyszerűen bemenetet kérni a konzolról: +input_string_var = raw_input( + "Enter some data: ") # Visszatér a megadott stringgel +input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként +# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni +# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve + +# A változókat nem szükséges a használat előtt deklarálni +some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas +some_var # => 5 + +# Érték nélküli változóra hivatkozás hibát dob. +# Lásd a Control Flow szekciót a kivételkezelésről. +some_other_var # name error hibát dob + +# az if használható kifejezésként +# a C nyelv '?:' ternáris operátorával egyenértékűen +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# A listákban sorozatok tárolhatóak +li = [] +# Már inicializáláskor megadhatóak elemek +other_li = [4, 5, 6] + +# A lista végére az append metódus rak új elemet +li.append(1) # li jelenleg [1] +li.append(2) # li jelenleg [1, 2] +li.append(4) # li jelenleg [1, 2, 4] +li.append(3) # li jelenleg [1, 2, 4, 3] +# A végéről a pop metódus távolít el elemet +li.pop() # => 3 és li jelenleg [1, 2, 4] +# Rakjuk vissza +li.append(3) # li jelenleg [1, 2, 4, 3], újra. + +# A lista elemeket tömb indexeléssel lehet hivatkozni +li[0] # => 1 +# A már inicializált értékekhez a = jellel lehet új értéket rendelni +li[0] = 42 +li[0] # => 42 +li[0] = 1 # csak visszaállítjuk az eredeti értékére +# Így is lehet az utolsó elemre hivatkozni +li[-1] # => 3 + +# A túlindexelés eredménye IndexError +li[4] # IndexError hibát dob + +# A lista részeit a slice szintaxissal lehet kimetszeni +# (Matekosoknak ez egy zárt/nyitott intervallum.) +li[1:3] # => [2, 4] +# A lista eleje kihagyható így +li[2:] # => [4, 3] +# Kihagyható a vége +li[:3] # => [1, 2, 4] +# Minden második elem kiválasztása +li[::2] # =>[1, 4] +# A lista egy másolata, fordított sorrendben +li[::-1] # => [3, 4, 2, 1] +# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek +# li[start:end:step] + +# Listaelemek a "del" paranccsal törölhetőek +del li[2] # li jelenleg [1, 2, 3] + +# A listák összeadhatóak +li + other_li # => [1, 2, 3, 4, 5, 6] +# Megjegyzés: az eredeti li és other_li értékei változatlanok + +# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal +li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6] + +# Egy elem első előfordulásának eltávolítása +li.remove(2) # li jelenleg [1, 3, 4, 5, 6] +li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában + +# Elemek beszúrhatóak tetszőleges helyre +li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét + +# Egy elem első előfordulási helye +li.index(2) # => 1 +li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában + +# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető +1 in li # => True + +# A lista hossza a "len()" függvénnyel +len(li) # => 6 + +# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # TypeError hibát dob + +# Az összes lista-műveletet ezeken is használható +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Az N-esek (és listák) kicsomagolhatóak külön változókba +a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3 +d, e, f = 4, 5, 6 # a zárójel elhagyható +# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik +g = 4, 5, 6 # => (4, 5, 6) +# Nézd, milyen egyszerű két értéket megcserélni +e, d = d, e # d most már 5 és az e 4 + +# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók +empty_dict = {} +# Ez pedig rögtön értékekkel van inicializálva +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Egy dictionary értékei [] jelek közt indexelhetőek +filled_dict["one"] # => 1 + +# A "keys()" metódus visszatér a kulcsok listájával +filled_dict.keys() # => ["three", "two", "one"] +# Megjegyzés: egy dictionary párjainak sorrendje nem garantált +# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket. + +# Az értékek listája a "values()" metódussal kérhető le +filled_dict.values() # => [3, 2, 1] +# ld. a fenti megjegyzést az elemek sorrendjéről. + +# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben +"one" in filled_dict # => True +1 in filled_dict # => False + +# Nem létező kulcs hivatkozása KeyError hibát dob +filled_dict["four"] # KeyError + +# A "get()" metódus használatával elkerülhető a KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# Megjegyzés: ettől még filled_dict.get("four") => None +# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben) + +# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek: +filled_dict["four"] = 4 # ez után filled_dict["four"] => 4 + +# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva +filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re +filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5 + +# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat +empty_set = set() +# Inicializáljuk ezt a halmazt néhány elemmel +some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4]) + +# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet +another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4]) + +# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Új halmaz-elemek hozzáadása +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Halmaz metszés a & operátorral +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Halmaz unió | operátorral +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Halmaz különbség - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Szimmetrikus differencia ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit +{1, 2} >= {1, 2, 3} # => False + +# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak +{1, 2} <= {1, 2, 3} # => True + +# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +# 3. Control Flow +#################################################### + +# Legyen egy változónk +some_var = 5 + +# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben! +# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél" +if some_var > 10: + print "some_var nagyobb, mint 10." +elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben. + print "some_var kisebb 10-nél" +else: # Ez sem kötelező. + print "some_var kereken 10." + +""" +For ciklusokkal végigiterálhatunk listákon +a kimenet: + A(z) kutya emlős + A(z) macska emlős + A(z) egér emlős +""" +for animal in ["kutya", "macska", "egér"]: + # A {0} kifejezéssel formázzuk a stringet, ld. korábban. + print "A(z) {0} emlős".format(animal) + +""" +"range(number)" visszatér számok listájával 0-től number-ig +a kimenet: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" visszatér a lower és upper közti számok listájával +a kimenet: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +A while ciklus a feltétel hamissá válásáig fut. +a kimenet: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Rövidítés az x = x + 1 kifejezésre + +# A kivételek try/except blokkokkal kezelhetőek + +# Python 2.6-tól felfele: +try: + # A "raise" szóval lehet hibát dobni + raise IndexError("Ez egy index error") +except IndexError as e: + pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat. +except (TypeError, NameError): + pass # Ha szükséges, egyszerre több hiba típus is kezelhető +else: # Az except blokk után opcionálisan megadható + print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák +finally: # Mindenképpen lefut + print "Itt felszabadíthatjuk az erőforrásokat például" + +# Az erőforrások felszabadításához try/finally helyett a with használható +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +# 4. Függvények +#################################################### + +# A "def" szóval hozhatunk létre új függvényt +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # A return szóval tudunk értékeket visszaadni + + +# Így hívunk függvényt paraméterekkel +add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11 + +# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt +add(y=6, x=5) # Ez esetben a sorrendjük nem számít + + +# Változó számú paramétert fogadó függvény így definiálható. +# A * használatával a paramétereket egy N-esként kapjuk meg. +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Változó számú nevesített paramétert fogadó függvény is megadható, +# a ** használatával a paramétereket egy dictionary-ként kapjuk meg +def keyword_args(**kwargs): + return kwargs + + +# Nézzük meg, mi történik +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# A két módszer egyszerre is használható +def all_the_args(*args, **kwargs): + print args + print kwargs + + +""" +all_the_args(1, 2, a=3, b=4) kimenete: + (1, 2) + {"a": 3, "b": 4} +""" + +# Függvények hívásakor a fenti args és kwargs módszerek inverze használható +# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4) +all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4) +all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4) + + +# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek, +# a * illetve ** operátorokkal kifejtve +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Függvény scope +x = 5 + + +def set_x(num): + # A lokális x változó nem ugyanaz, mint a globális x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # a globális x-et 6-ra állítjuk + print x # => 6 + + +set_x(43) +set_global_x(6) + + +# A pythonban a függvény elsőrendű (ún. "first class") típus +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Névtelen függvények is definiálhatóak +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Léteznek beépített magasabb rendű függvények +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] + +# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel +[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] + +# halmaz és dictionary képzők is léteznek +{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. Osztályok +#################################################### + +# Az object osztály egy alosztályát képezzük +class Human(object): + # Osztály szintű mező: az osztály összes példányában azonos + species = "H. sapiens" + + # Ez a függvény meghívódik az osztály példányosításakor. + # Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python + # előre definiált, a nyelv által belsőleg használt, de a felhasználó által + # is látható objektumok és mezők neveire. + # Ne vezessünk be új, ilyen elnevezési sémát használó neveket! + def __init__(self, name): + # A paramétert értékül adjuk a példány name attribútumának + self.name = name + + # Inicializálunk egy mezőt + self.age = 0 + + # Példány metódus. Minden metódus első paramétere a "self", a példány maga + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # Egy osztálymetódus az osztály összes példány közt meg van osztva. + # Hívásukkor az első paraméter mindig a hívó osztály. + @classmethod + def get_species(cls): + return cls.species + + # Egy statikus metódus osztály és példányreferencia nélkül hívódik + @staticmethod + def grunt(): + return "*grunt*" + + # Egy property jelölésű függvény olyan, mint egy getter. + # Használatával az age mező egy csak-olvasható attribútummá válik. + @property + def age(self): + return self._age + + # Így lehet settert megadni egy mezőhöz + @age.setter + def age(self, age): + self._age = age + + # Így lehet egy mező törlését engedélyezni + @age.deleter + def age(self): + del self._age + + +# Példányosítsuk az osztályt +i = Human(name="Ian") +print i.say("hi") # kimenet: "Ian: hi" + +j = Human("Joel") +print j.say("hello") # kimenet: "Joel: hello" + +# Hívjuk az osztály metódusunkat +i.get_species() # => "H. sapiens" + +# Változtassuk meg az osztály szintű attribútumot +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Hívjuk meg a statikus metódust +Human.grunt() # => "*grunt*" + +# Adjunk új értéket a mezőnek +i.age = 42 + +# Kérjük le a mező értékét +i.age # => 42 + +# Töröljük a mezőt +del i.age +i.age # => AttributeError hibát dob + +#################################################### +# 6. Modulok +#################################################### + +# Modulokat így lehet importálni +import math + +print math.sqrt(16) # => 4.0 + +# Lehetséges csak bizonyos függvényeket importálni egy modulból +from math import ceil, floor + +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# Egy modul összes függvénye is importálható +# Vigyázat: ez nem ajánlott. +from math import * + +# A modulok nevei lerövidíthetőek +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# Meggyőződhetünk róla, hogy a függvények valóban azonosak +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# A Python modulok egyszerű fájlok. +# Írhatsz sajátot és importálhatod is. +# A modul neve azonos a tartalmazó fájl nevével. + +# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul. +import math + +dir(math) + + +# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos +# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett. +# A lokális mappa prioritást élvez a beépített könyvtárak felett. + + +#################################################### +# 7. Haladóknak +#################################################### + +# Generátorok +# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket. + +# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit, +# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk +# ezt a nagy listát a ciklus vezérléséhez. +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet, +# amikor azt kérik tőle +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt. +# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak +# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!). +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén +# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a +# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range` +# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük +# - esetünkben a ciklus következő iterációjakor + +# A lista képzéshez hasonlóan generátor képzőket is használhatunk +# ("generator comprehensions"). +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # kimenet: -1 -2 -3 -4 -5 + +# Egy generátor összes generált elemét listaként is elkérhetjük: +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Dekorátorok +# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény. +# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény +# kimenetébe beszúrja az 'Apple' elemet. +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'] + +# A kimenet tartalmazza az 'Apple' elemet: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# Ebben a példában a beg dekorátorral látjuk el a say függvényt. +# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor +# megváltoztatja az eredmény mondatot. +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 :( +``` + +## Még több érdekel? + +### Ingyenes online tartalmak + +* [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/) + +### Könyvek + +* [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/it-it/python-it.html.markdown b/it-it/python-it.html.markdown deleted file mode 100644 index 794e7a70..00000000 --- a/it-it/python-it.html.markdown +++ /dev/null @@ -1,778 +0,0 @@ ---- -language: python -filename: learnpython-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/python3/). - -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/it-it/pythonlegacy-it.html.markdown b/it-it/pythonlegacy-it.html.markdown new file mode 100644 index 00000000..794e7a70 --- /dev/null +++ b/it-it/pythonlegacy-it.html.markdown @@ -0,0 +1,778 @@ +--- +language: python +filename: learnpython-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/python3/). + +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/ko-kr/python-kr.html.markdown b/ko-kr/python-kr.html.markdown deleted file mode 100644 index 0145754d..00000000 --- a/ko-kr/python-kr.html.markdown +++ /dev/null @@ -1,484 +0,0 @@ ---- -language: python -category: language -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -filename: learnpython-ko.py -translators: - - ["wikibook", "http://wikibook.co.kr"] -lang: ko-kr ---- - -파이썬은 귀도 반 로섬이 90년대에 만들었습니다. 파이썬은 현존하는 널리 사용되는 언어 중 하나입니다. -저는 문법적 명료함에 반해 파이썬을 사랑하게 됐습니다. 파이썬은 기본적으로 실행 가능한 의사코드입니다. - -피드백 주시면 정말 감사하겠습니다! [@louiedinh](http://twitter.com/louiedinh)나 -louiedinh [at] [구글의 이메일 서비스]를 통해 저에게 연락하시면 됩니다. - -참고: 이 글은 구체적으로 파이썬 2.7에 해당하는 내용을 담고 있습니다만 -파이썬 2.x에도 적용할 수 있을 것입니다. 파이썬 3을 다룬 튜토리얼도 곧 나올 테니 기대하세요! - -```python -# 한 줄짜리 주석은 해시로 시작합니다. -""" 여러 줄 문자열은 "를 세 개 써서 시작할 수 있고, - 주석으로 자주 사용됩니다. -""" - -#################################################### -## 1. 기본 자료형과 연산자 -#################################################### - -# 숫자 -3 #=> 3 - -# 수학 연산은 예상하신 대로입니다. -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# 나눗셈은 약간 까다롭습니다. 정수로 나눈 다음 결과값을 자동으로 내림합니다. -5 / 2 #=> 2 - -# 나눗셈 문제를 해결하려면 float에 대해 알아야 합니다. -2.0 # 이것이 float입니다. -11.0 / 4.0 #=> 2.75 훨씬 낫네요 - -# 괄호를 이용해 연산자 우선순위를 지정합니다. -(1 + 3) * 2 #=> 8 - -# 불린(Boolean) 값은 기본형입니다. -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 # 이름 오류가 발생 - -# 표현식으로도 사용할 수 있습니다. -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# 리스트는 순차 항목을 저장합니다. -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]입니다. -# 다시 넣어봅시다 -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] - -# del로 임의의 요소를 제거할 수 있습니다. -del li[2] # li is now [1, 2, 3] - -# 리스트를 추가할 수도 있습니다. -li + other_li #=> [1, 2, 3, 4, 5, 6] - 참고: li와 other_li는 그대로 유지됩니다. - -# 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 - -# 모든 키를 리스트로 구합니다. -filled_dict.keys() #=> ["three", "two", "one"] -# 참고 - 딕셔너리 키의 순서는 보장되지 않습니다. -# 따라서 결과가 이와 정확히 일치하지 않을 수도 있습니다. - -# 모든 값을 리스트로 구합니다. -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입니다. - - -# 세트는 집합을 저장합니다. -empty_set = set() -# 다수의 값으로 세트를 초기화합니다. -some_set = set([1,2,2,3,4]) # 이제 some_set는 set([1, 2, 3, 4])입니다. - -# 파이썬 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 문입니다. 파이썬에서는 들여쓰기가 대단히 중요합니다! -# 다음 코드를 실행하면 "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: # 이 부분 역시 선택사항입니다. - 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 루프는 조건이 더는 충족되지 않을 때까지 진행됩니다. -prints: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # x = x + 1의 축약형 - -# try/except 블록을 이용한 예외 처리 - -# 파이썬 2.6 및 상위 버전에서 동작하는 코드 -try: - # raise를 이용해 오류를 발생시킵니다 - raise IndexError("This is an index error") -except IndexError as e: - pass # pass는 단순 no-op 연산입니다. 보통 이곳에 복구 코드를 작성합니다. - - -#################################################### -## 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)를 실행하면 다음과 같은 내용이 출력됩니다: - (1, 2) - {"a": 3, "b": 4} -""" - -# 함수를 호출할 때 varargs/kwargs와 반대되는 일을 할 수 있습니다! -# *를 이용해 튜플을 확장하고 **를 이용해 kwargs를 확장합니다. -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)와 같음 - -# 파이썬에는 일급 함수가 있습니다 -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 - -# 내장된 고차 함수(high order function)도 있습니다. -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# 맵과 필터에 리스트 조건 제시법(list comprehensions)을 사용할 수 있습니다. -[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. 클래스 -#################################################### - -# 클래스를 하나 만들기 위해 특정 객체의 하위 클래스를 만들 수 있습니다. -class Human(object): - - # 클래스 속성은 이 클래스의 모든 인스턴스에서 공유합니다. - species = "H. sapiens" - - # 기본 초기화자 - def __init__(self, name): - # 인자를 인스턴스의 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 - -# 모듈의 모든 함수를 임포트할 수 있습니다. -# Warning: this is not recommended -from math import * - -# 모듈 이름을 축약해서 쓸 수 있습니다. -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# 파이썬 모듈은 평범한 파이썬 파일에 불과합니다. -# 직접 모듈을 작성해서 그것들을 임포트할 수 있습니다. -# 모듈의 이름은 파일의 이름과 같습니다. - -# 다음과 같은 코드로 모듈을 구성하는 함수와 속성을 확인할 수 있습니다. -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/) - -### 파이썬 관련 도서 - -* [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/ko-kr/pythonlegacy-kr.html.markdown b/ko-kr/pythonlegacy-kr.html.markdown new file mode 100644 index 00000000..0145754d --- /dev/null +++ b/ko-kr/pythonlegacy-kr.html.markdown @@ -0,0 +1,484 @@ +--- +language: python +category: language +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +filename: learnpython-ko.py +translators: + - ["wikibook", "http://wikibook.co.kr"] +lang: ko-kr +--- + +파이썬은 귀도 반 로섬이 90년대에 만들었습니다. 파이썬은 현존하는 널리 사용되는 언어 중 하나입니다. +저는 문법적 명료함에 반해 파이썬을 사랑하게 됐습니다. 파이썬은 기본적으로 실행 가능한 의사코드입니다. + +피드백 주시면 정말 감사하겠습니다! [@louiedinh](http://twitter.com/louiedinh)나 +louiedinh [at] [구글의 이메일 서비스]를 통해 저에게 연락하시면 됩니다. + +참고: 이 글은 구체적으로 파이썬 2.7에 해당하는 내용을 담고 있습니다만 +파이썬 2.x에도 적용할 수 있을 것입니다. 파이썬 3을 다룬 튜토리얼도 곧 나올 테니 기대하세요! + +```python +# 한 줄짜리 주석은 해시로 시작합니다. +""" 여러 줄 문자열은 "를 세 개 써서 시작할 수 있고, + 주석으로 자주 사용됩니다. +""" + +#################################################### +## 1. 기본 자료형과 연산자 +#################################################### + +# 숫자 +3 #=> 3 + +# 수학 연산은 예상하신 대로입니다. +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# 나눗셈은 약간 까다롭습니다. 정수로 나눈 다음 결과값을 자동으로 내림합니다. +5 / 2 #=> 2 + +# 나눗셈 문제를 해결하려면 float에 대해 알아야 합니다. +2.0 # 이것이 float입니다. +11.0 / 4.0 #=> 2.75 훨씬 낫네요 + +# 괄호를 이용해 연산자 우선순위를 지정합니다. +(1 + 3) * 2 #=> 8 + +# 불린(Boolean) 값은 기본형입니다. +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 # 이름 오류가 발생 + +# 표현식으로도 사용할 수 있습니다. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# 리스트는 순차 항목을 저장합니다. +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]입니다. +# 다시 넣어봅시다 +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] + +# del로 임의의 요소를 제거할 수 있습니다. +del li[2] # li is now [1, 2, 3] + +# 리스트를 추가할 수도 있습니다. +li + other_li #=> [1, 2, 3, 4, 5, 6] - 참고: li와 other_li는 그대로 유지됩니다. + +# 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 + +# 모든 키를 리스트로 구합니다. +filled_dict.keys() #=> ["three", "two", "one"] +# 참고 - 딕셔너리 키의 순서는 보장되지 않습니다. +# 따라서 결과가 이와 정확히 일치하지 않을 수도 있습니다. + +# 모든 값을 리스트로 구합니다. +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입니다. + + +# 세트는 집합을 저장합니다. +empty_set = set() +# 다수의 값으로 세트를 초기화합니다. +some_set = set([1,2,2,3,4]) # 이제 some_set는 set([1, 2, 3, 4])입니다. + +# 파이썬 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 문입니다. 파이썬에서는 들여쓰기가 대단히 중요합니다! +# 다음 코드를 실행하면 "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: # 이 부분 역시 선택사항입니다. + 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 루프는 조건이 더는 충족되지 않을 때까지 진행됩니다. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # x = x + 1의 축약형 + +# try/except 블록을 이용한 예외 처리 + +# 파이썬 2.6 및 상위 버전에서 동작하는 코드 +try: + # raise를 이용해 오류를 발생시킵니다 + raise IndexError("This is an index error") +except IndexError as e: + pass # pass는 단순 no-op 연산입니다. 보통 이곳에 복구 코드를 작성합니다. + + +#################################################### +## 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)를 실행하면 다음과 같은 내용이 출력됩니다: + (1, 2) + {"a": 3, "b": 4} +""" + +# 함수를 호출할 때 varargs/kwargs와 반대되는 일을 할 수 있습니다! +# *를 이용해 튜플을 확장하고 **를 이용해 kwargs를 확장합니다. +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)와 같음 + +# 파이썬에는 일급 함수가 있습니다 +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 + +# 내장된 고차 함수(high order function)도 있습니다. +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# 맵과 필터에 리스트 조건 제시법(list comprehensions)을 사용할 수 있습니다. +[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. 클래스 +#################################################### + +# 클래스를 하나 만들기 위해 특정 객체의 하위 클래스를 만들 수 있습니다. +class Human(object): + + # 클래스 속성은 이 클래스의 모든 인스턴스에서 공유합니다. + species = "H. sapiens" + + # 기본 초기화자 + def __init__(self, name): + # 인자를 인스턴스의 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 + +# 모듈의 모든 함수를 임포트할 수 있습니다. +# Warning: this is not recommended +from math import * + +# 모듈 이름을 축약해서 쓸 수 있습니다. +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# 파이썬 모듈은 평범한 파이썬 파일에 불과합니다. +# 직접 모듈을 작성해서 그것들을 임포트할 수 있습니다. +# 모듈의 이름은 파일의 이름과 같습니다. + +# 다음과 같은 코드로 모듈을 구성하는 함수와 속성을 확인할 수 있습니다. +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/) + +### 파이썬 관련 도서 + +* [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/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown deleted file mode 100644 index 222f753f..00000000 --- a/pl-pl/python-pl.html.markdown +++ /dev/null @@ -1,640 +0,0 @@ ---- -name: python -category: language -language: python -filename: learnpython-pl.py -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Amin Bandali", "http://aminbandali.com"] - - ["Andre Polykanine", "https://github.com/Oire"] -translators: - - ["Dominik Krzemiński", "https://github.com/dokato"] -lang: pl-pl ---- - -Python został opracowany przez Guido Van Rossuma na początku lat 90-tych. -Obecnie jest jednym z najbardziej popularnych języków programowania. -Zakochałem się w Pythonie dzięki porządkowi, jaki utrzymywany jest w kodzie. -To po prostu wykonywalny pseudokod. - -Zapraszam do kontaktu. Złapiecie nas na: -- kontakt polski: raymon92 [at] [google's email service] -- kontakt angielski: [@louiedinh](http://twitter.com/louiedinh) lub louiedinh [at] [google's email service] - -Uwaga: Ten artykuł odnosi się do wersji Pythona 2.7, ale powinien -działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stronie głównej. - -```python -# -*- coding: utf-8 -*- - -# Pojedyncze komentarze oznaczamy takim symbolem. - -""" Wielolinijkowe napisy zapisywane są przy użyciu - potrójnych cudzysłowów i często - wykorzystywane są jako komentarze. -""" - -#################################################### -## 1. Podstawowe typy danych i operatory -#################################################### - -# Liczby to liczby -3 # => 3 - -# Matematyka jest intuicyjna -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# Dzielenie może być kłopotliwe. Poniższe działanie to dzielenie -# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany. -5 / 2 # => 2 - -# Aby to naprawić, musimy powiedzieć nieco o liczbach zmiennoprzecinkowych. -2.0 # To liczba zmiennoprzecinkowa, tzw. float -11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej - -# Wynik dzielenia całkowitoliczbowego jest obcinany dla liczb -# dodatnich i ujemnych. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # działa też na floatach --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Operator modulo - wyznaczanie reszty z dzielenia -7 % 3 # => 1 - -# Potęgowanie (x do potęgi y-tej) -2**4 # => 16 - -# Wymuszanie pierwszeństwa w nawiasach -(1 + 3) * 2 # => 8 - -# Operacje logiczne -# Zauważ, że przy "and" i "or" trzeba zwracać uwagę na rozmiar liter -True and False #=> False # Fałsz -False or True #=> True # Prawda - -# Zauważ, że operatorów logicznych można używać z intami -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -k1 == True #=> True - -# aby zanegować, użyj "not" -not True # => False -not False # => True - -# Równość == -1 == 1 # => True -2 == 1 # => False - -# Nierówność != -1 != 1 # => False -2 != 1 # => True - -# Więcej porównań -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Porównania można układać w łańcuch! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Napisy (typ string) tworzone są przy użyciu cudzysłowów " lub ' -"Jestem napisem." -'Ja też jestem napisem.' - -# Napisy można dodawać! -"Witaj " + "świecie!" # => "Witaj świecie!" - -# ... a nawet mnożyć -"Hej" * 3 # => "HejHejHej" - -# Napis może być traktowany jako lista znaków -"To napis"[0] # => 'T' - -# % może być używane do formatowania napisów: -"%s są %s" % ("napisy", "fajne") - -# Jednak nowszym sposobem formatowania jest metoda "format". -# Ta metoda jest obecnie polecana: -"{0} są {1}".format("napisy", "fajne") -# Jeśli nie chce ci się liczyć, użyj słów kluczowych. -"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron") - -# None jest obiektem -None # => None - -# Nie używaj "==" w celu porównania obiektów z None -# Zamiast tego użyj "is" -"etc" is None # => False -None is None # => True - -# Operator 'is' testuje identyczność obiektów. Nie jest to zbyt -# pożyteczne, gdy działamy tylko na prostych wartościach, -# ale przydaje się, gdy mamy do czynienia z obiektami. - -# None, 0 i pusty napis "" są odpowiednikami logicznego False. -# Wszystkie inne wartości są uznawane za prawdę (True) -bool(0) # => False -bool("") # => False - - -#################################################### -## 2. Zmienne i zbiory danych -#################################################### - -# Python ma instrukcję wypisującą "print" we wszystkich wersjach 2.x, ale -# została ona usunięta z wersji 3. -print "Jestem Python. Miło Cię poznać!" -# Python ma też funkcję "print" dostępną w wersjach 2.7 i 3... -# ale w 2.7 musisz dodać import (odkomentuj): -# from __future__ import print_function -print("Ja też jestem Python! ") - -# Nie trzeba deklarować zmiennych przed przypisaniem. -jakas_zmienna = 5 # Konwencja mówi: używaj małych liter i znaków podkreślenia _ -jakas_zmienna # => 5 - -# Próba dostępu do niezadeklarowanej zmiennej da błąd. -# Przejdź do sekcji Obsługa wyjątków, aby dowiedzieć się więcej... -inna_zmienna # Wyrzuca nazwę błędu - -# "if" może być użyte jako wyrażenie -"huraaa!" if 3 > 2 else 2 # => "huraaa!" - -# Listy: -li = [] -# Możesz zacząć od wypełnionej listy -inna_li = [4, 5, 6] - -# Dodaj na koniec, używając "append" -li.append(1) # li to teraz [1] -li.append(2) # li to teraz [1, 2] -li.append(4) # li to teraz [1, 2, 4] -li.append(3) # li to teraz [1, 2, 4, 3] -# Usuwanie z konca da "pop" -li.pop() # => 3 a li stanie się [1, 2, 4] -# Dodajmy ponownie -li.append(3) # li to znowu [1, 2, 4, 3]. - -# Dostęp do list jak do każdej tablicy -li[0] # => 1 -# Aby nadpisać wcześniej wypełnione miejsca w liście, użyj znaku = -li[0] = 42 -li[0] # => 42 -li[0] = 1 # Uwaga: ustawiamy starą wartość -# Tak podglądamy ostatni element -li[-1] # => 3 - -# Jeżeli wyjdziesz poza zakres... -li[4] # ... zobaczysz IndexError - -# Możesz też tworzyć wycinki. -li[1:3] # => [2, 4] -# Bez początku -li[2:] # => [4, 3] -# Omijamy koniec -li[:3] # => [1, 2, 4] -# Wybierz co drugi -li[::2] # =>[1, 4] -# Odwróć listę -li[::-1] # => [3, 4, 2, 1] -# Użyj kombinacji powyższych aby tworzyć bardziej skomplikowane wycinki -# li[poczatek:koniec:krok] - -# Usuń element używając "del" -del li[2] # li to teraz [1, 2, 3] - -# Listy można dodawać -li + inna_li # => [1, 2, 3, 4, 5, 6] -# Uwaga: wartości oryginalnych list li i inna_li się nie zmieniają. - -# Do łączenia list użyj "extend()" -li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6] - -# Sprawdź, czy element jest w liście używając "in" -1 in li # => True - -# "len()" pokazuje długość listy -len(li) # => 6 - - -# Krotki (tuple) są jak listy, ale nie można ich modyfikować. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # wyrzuci TypeError - -# Ale wielu akcji dla list możesz używać przy krotkach -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Można rozpakować krotki i listy do poszczególych zmiennych -a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3 -# Jeżeli zapomnisz nawiasów, automatycznie tworzone są krotki -d, e, f = 4, 5, 6 -# Popatrz jak prosto zamienić wartości -e, d = d, e # d to teraz 5 a e to 4 - - -# Słowniki są również pożyteczne -pusty_slownik = {} -# Tu tworzymy wypełniony: -pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3} - -# Podglądany wartość -pelen_slownik["one"] # => 1 - -# Wypisz wszystkie klucze, używając "keys()" -pelen_slownik.keys() # => ["trzy", "dwa", "raz"] -# Uwaga: słowniki nie zapamiętują kolejności kluczy. - -# A teraz wszystkie wartości "values()" -pelen_slownik.values() # => [3, 2, 1] -# Uwaga: to samo dotyczy wartości. - -# Sprawdzanie czy klucz występuje w słowniku za pomocą "in" -"raz" in pelen_slownik # => True -1 in pelen_slownik # => False - -# Próba dobrania się do nieistniejącego klucza da KeyError -pelen_slownik["cztery"] # KeyError - -# Użyj metody "get()", aby uniknąć błędu KeyError -pelen_slownik.get("raz") # => 1 -pelen_slownik.get("cztery") # => None -# Metoda get zwraca domyślną wartość gdy brakuje klucza -pelen_slownik.get("one", 4) # => 1 -pelen_slownik.get("cztery", 4) # => 4 -# zauważ, że pelen_slownik.get("cztery") wciąż zwraca => None -# (get nie ustawia wartości słownika) - -# przypisz wartość do klucza podobnie jak w listach -pelen_slownik["cztery"] = 4 # teraz: pelen_slownik["cztery"] => 4 - -# "setdefault()" wstawia do słownika tylko jeśli nie było klucza -pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5 -pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5 - - -# Teraz zbiory (set) - działają jak zwykłe listy, ale bez potórzeń -pusty_zbior = set() -# Inicjalizujemy "set()" pewnymi wartościami -jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4]) - -# kolejność nie jest zachowana, nawet gdy wydaje się posortowane -inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4]) - -# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru -pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Dodaj więcej elementów przez "add()" -pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5} - -# Znajdź przecięcie (część wspólną) zbiorów, używając & -inny_zbior = {3, 4, 5, 6} -pelen_zbior & other_set # => {3, 4, 5} - -# Suma zbiorów | -pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} - -# Różnicę zbiorów da znak - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Sprawdzanie obecności w zbiorze: "in". -2 in pelen_zbior # => True -10 in pelen_zbior # => False - - -#################################################### -## 3. Kontrola przepływu -#################################################### - -# Tworzymy zmienną jakas_zm -jakas_zm = 5 - -# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia w Pythonie są ważne! -# Poniższy kod wypisze "jakas_zm jest mniejsza niż 10" -if jakas_zm > 10: - print("jakas_zm jest wieksza niż 10") -elif some_var < 10: # Opcjonalna klauzula elif - print("jakas_zm jest mniejsza niż 10") -else: # Również opcjonalna klauzula else - print("jakas_zm jest równa 10") - - -""" -Pętla for iteruje po elementach listy, wypisując: - pies to ssak - kot to ssak - mysz to ssak -""" -for zwierze in ["pies", "kot", "mysz"]: - # Użyj metody format, aby umieścić wartość zmiennej w ciągu - print("{0} to ssak".format(zwierze)) - -""" -"range(liczba)" zwraca listę liczb -z przedziału od zera do wskazanej liczby (bez niej): - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -While to pętla, która jest wykonywana, dopóki spełniony jest warunek: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Skrót od x = x + 1 - -# Wyjątki wyłapujemy, używając try i except - -# Działa w Pythonie 2.6 i wyższych: -try: - # Użyj "raise" aby wyrzucić wyjątek - raise IndexError("To błąd indeksu") -except IndexError as e: - pass # Pass to brak reakcji na błąd. Zwykle opisujesz tutaj, jak program ma się zachować w przypadku błędu. -except (TypeError, NameError): - pass # kilka wyjątków można przechwycić jednocześnie. -else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu - print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku. - - -#################################################### -## 4. Funkcje -#################################################### - -# Użyj "def", aby stworzyć nową funkcję -def dodaj(x, y): - print("x to %s, a y to %s" % (x, y)) - return x + y # słowo kluczowe return zwraca wynik działania - -# Tak wywołuje się funkcję z parametrami: -dodaj(5, 6) # => wypisze "x to 5, a y to 6" i zwróci 11 - -# Innym sposobem jest wywołanie z parametrami nazwanymi. -dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia. - - -# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów pozycyjnych, -# które zostaną przekazana jako krotka, pisząc w definicji funkcji "*args" -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów -# nazwanych kwargs, które zostaną przekazane jako słownik, pisząc w definicji funkcji "**kwargs" -def keyword_args(**kwargs): - return kwargs - -# Wywołajmy to i sprawdźmy co się dzieje -keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"} - - -# Możesz też przyjmować jednocześnie zmienną liczbę parametrów pozycyjnych i nazwanych -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) wypisze: - (1, 2) - {"a": 3, "b": 4} -""" - -# Użyj * aby rozwinąć parametry z krotki args -# i użyj ** aby rozwinąć parametry nazwane ze słownika kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # odpowiednik foo(1, 2, 3, 4) -all_the_args(**kwargs) # odpowiednik foo(a=3, b=4) -all_the_args(*args, **kwargs) # odpowiednik foo(1, 2, 3, 4, a=3, b=4) - -# Możesz podać parametry args i kwargs do funkcji równocześnie -# przez rozwinięcie odpowiednio * i ** -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - -# Zasięg zmiennych -x = 5 - -def setX(num): - # Lokalna zmienna x nie jest tym samym co zmienna x - x = num # => 43 - print x # => 43 - -def setGlobalX(num): - global x - print x # => 5 - x = num # globalna zmienna to teraz 6 - print x # => 6 - -setX(43) -setGlobalX(6) - -# Można tworzyć funkcje wewnętrzne i zwrócić je jako wynik -def rob_dodawacz(x): - def dodawacz(y): - return x + y - return dodawacz - -dodaj_10 = rob_dodawacz(10) -dodaj_10(3) # => 13 - -# Są również funkcje anonimowe "lambda" -(lambda x: x > 2)(3) # => True - -# Python ma też wbudowane funkcje wyższego rzędu (przyjmujące inną funkcje jako parametr) -map(add_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# Można używać wyrażeń listowych (list comprehensions) do mapowania i filtrowania -[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. Klasy -#################################################### - -# Wszystkie klasy są podklasą object -class Czlowiek(object): - - # Atrybut klasy. Występuje we wszystkich instancjach klasy. - gatunek = "H. sapiens" - - # Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji. - # Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają - # specjalne obiekty lub atrybuty wykorzystywane wewnętrznie przez Pythona. - # Nie używaj ich we własnych metodach. - def __init__(self, nazwa): - # przypisz parametr "nazwa" do atrybutu instancji - self.nazwa = nazwa - - # Metoda instancji. Wszystkie metody przyjmują "self" jako pierwszy argument - def mow(self, wiadomosc): - return "%s: %s" % (self.nazwa, wiadomosc) - - # Metoda klasowa współdzielona przez instancje. - # Przyjmuje wywołującą klasę jako pierwszy argument. - @classmethod - def daj_gatunek(cls): - return cls.gatunek - - # Metoda statyczna jest wywoływana bez argumentów klasy czy instancji. - @staticmethod - def grunt(): - return "*grunt*" - - -# Instancja klasy -i = Czlowiek(name="Ian") -print(i.mow("cześć")) # wypisze "Ian: cześć" - -j = Czlowiek("Joel") -print(j.mow("cześć")) # wypisze "Joel: cześć" - -# Wywołujemy naszą metodę klasową -i.daj_gatunek() # => "H. sapiens" - -# Zmieniamy wspólny parametr -Czlowiek.gatunek = "H. neanderthalensis" -i.daj_gatunek() # => "H. neanderthalensis" -j.daj_gatunek() # => "H. neanderthalensis" - -# Wywołanie metody statycznej -Czlowiek.grunt() # => "*grunt*" - - -#################################################### -## 6. Moduły -#################################################### - -# Tak importuje się moduły: -import math -print(math.sqrt(16)) # => 4.0 - -# Można podać konkretne funkcje, np. ceil, floor z modułu math -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Można zaimportować wszystkie funkcje z danego modułu. -# Uwaga: nie jest to polecane, bo później w kodzie trudno połapać się, -# która funkcja pochodzi z którego modułu. -from math import * - -# Można skracać nazwy modułów. -import math as m -math.sqrt(16) == m.sqrt(16) # => True -# sprawdźmy czy funkcje są równoważne -from math import sqrt -math.sqrt == m.sqrt == sqrt # => True - -# Moduły Pythona to zwykłe skrypty napisane w tym języku. Możesz -# pisać własne i importować je. Nazwa modułu to nazwa pliku. - -# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu. -import math -dir(math) - - -#################################################### -## 7. Zaawansowane -#################################################### - -# Generatory pomagają tworzyć tzw. "leniwy kod" -def podwojne_liczby(iterowalne): - for i in iterowalne: - yield i + i - -# Generatory tworzą wartości w locie. -# Zamiast generować wartości raz i zapisywać je (np. w liście), -# generator tworzy je na bieżąco, w wyniku iteracji. To oznacza, -# że w poniższym przykładzie wartości większe niż 15 nie będą przetworzone -# w funkcji "podwojne_liczby". -# Zauważ, że xrange to generator, który wykonuje tę samą operację co range. -# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci, -# a xrange tworzy obiekt generatora zamiast budować całą listę jak range. - -# Aby odróżnić nazwę zmiennej od nazwy zarezerwowanej w Pythonie, używamy -# zwykle na końcu znaku podkreślenia -xrange_ = xrange(1, 900000000) - -# poniższa pętla będzie podwajać liczby aż do 30 -for i in podwojne_liczby(xrange_): - print(i) - if i >= 30: - break - - -# Dekoratory -# w tym przykładzie "beg" jest nakładką na "say" -# Beg wywołuje say. Jeśli say_please jest prawdziwe, wtedy zwracana wartość -# zostanie zmieniona - -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, "Proszę! Jestem spłukany :(") - return msg - return wrapper - - -@beg -def say(say_please=False): - msg = "Kupisz mi piwo?" - return msg, say_please - - -print(say()) # Kupisz mi piwo? -print(say(say_please=True)) # Kupisz mi piwo? Proszę! Jestem spłukany :( -``` - -## Gotowy na więcej? -### Polskie - -* [Zanurkuj w Pythonie](http://pl.wikibooks.org/wiki/Zanurkuj_w_Pythonie) -* [LearnPythonPl](http://www.learnpython.org/pl/) - -### Angielskie: -#### Darmowe źródła online - -* [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/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -#### Inne - -* [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/pl-pl/pythonlegacy-pl.html.markdown b/pl-pl/pythonlegacy-pl.html.markdown new file mode 100644 index 00000000..222f753f --- /dev/null +++ b/pl-pl/pythonlegacy-pl.html.markdown @@ -0,0 +1,640 @@ +--- +name: python +category: language +language: python +filename: learnpython-pl.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Dominik Krzemiński", "https://github.com/dokato"] +lang: pl-pl +--- + +Python został opracowany przez Guido Van Rossuma na początku lat 90-tych. +Obecnie jest jednym z najbardziej popularnych języków programowania. +Zakochałem się w Pythonie dzięki porządkowi, jaki utrzymywany jest w kodzie. +To po prostu wykonywalny pseudokod. + +Zapraszam do kontaktu. Złapiecie nas na: +- kontakt polski: raymon92 [at] [google's email service] +- kontakt angielski: [@louiedinh](http://twitter.com/louiedinh) lub louiedinh [at] [google's email service] + +Uwaga: Ten artykuł odnosi się do wersji Pythona 2.7, ale powinien +działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stronie głównej. + +```python +# -*- coding: utf-8 -*- + +# Pojedyncze komentarze oznaczamy takim symbolem. + +""" Wielolinijkowe napisy zapisywane są przy użyciu + potrójnych cudzysłowów i często + wykorzystywane są jako komentarze. +""" + +#################################################### +## 1. Podstawowe typy danych i operatory +#################################################### + +# Liczby to liczby +3 # => 3 + +# Matematyka jest intuicyjna +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Dzielenie może być kłopotliwe. Poniższe działanie to dzielenie +# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany. +5 / 2 # => 2 + +# Aby to naprawić, musimy powiedzieć nieco o liczbach zmiennoprzecinkowych. +2.0 # To liczba zmiennoprzecinkowa, tzw. float +11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej + +# Wynik dzielenia całkowitoliczbowego jest obcinany dla liczb +# dodatnich i ujemnych. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # działa też na floatach +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Operator modulo - wyznaczanie reszty z dzielenia +7 % 3 # => 1 + +# Potęgowanie (x do potęgi y-tej) +2**4 # => 16 + +# Wymuszanie pierwszeństwa w nawiasach +(1 + 3) * 2 # => 8 + +# Operacje logiczne +# Zauważ, że przy "and" i "or" trzeba zwracać uwagę na rozmiar liter +True and False #=> False # Fałsz +False or True #=> True # Prawda + +# Zauważ, że operatorów logicznych można używać z intami +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +k1 == True #=> True + +# aby zanegować, użyj "not" +not True # => False +not False # => True + +# Równość == +1 == 1 # => True +2 == 1 # => False + +# Nierówność != +1 != 1 # => False +2 != 1 # => True + +# Więcej porównań +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Porównania można układać w łańcuch! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Napisy (typ string) tworzone są przy użyciu cudzysłowów " lub ' +"Jestem napisem." +'Ja też jestem napisem.' + +# Napisy można dodawać! +"Witaj " + "świecie!" # => "Witaj świecie!" + +# ... a nawet mnożyć +"Hej" * 3 # => "HejHejHej" + +# Napis może być traktowany jako lista znaków +"To napis"[0] # => 'T' + +# % może być używane do formatowania napisów: +"%s są %s" % ("napisy", "fajne") + +# Jednak nowszym sposobem formatowania jest metoda "format". +# Ta metoda jest obecnie polecana: +"{0} są {1}".format("napisy", "fajne") +# Jeśli nie chce ci się liczyć, użyj słów kluczowych. +"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron") + +# None jest obiektem +None # => None + +# Nie używaj "==" w celu porównania obiektów z None +# Zamiast tego użyj "is" +"etc" is None # => False +None is None # => True + +# Operator 'is' testuje identyczność obiektów. Nie jest to zbyt +# pożyteczne, gdy działamy tylko na prostych wartościach, +# ale przydaje się, gdy mamy do czynienia z obiektami. + +# None, 0 i pusty napis "" są odpowiednikami logicznego False. +# Wszystkie inne wartości są uznawane za prawdę (True) +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Zmienne i zbiory danych +#################################################### + +# Python ma instrukcję wypisującą "print" we wszystkich wersjach 2.x, ale +# została ona usunięta z wersji 3. +print "Jestem Python. Miło Cię poznać!" +# Python ma też funkcję "print" dostępną w wersjach 2.7 i 3... +# ale w 2.7 musisz dodać import (odkomentuj): +# from __future__ import print_function +print("Ja też jestem Python! ") + +# Nie trzeba deklarować zmiennych przed przypisaniem. +jakas_zmienna = 5 # Konwencja mówi: używaj małych liter i znaków podkreślenia _ +jakas_zmienna # => 5 + +# Próba dostępu do niezadeklarowanej zmiennej da błąd. +# Przejdź do sekcji Obsługa wyjątków, aby dowiedzieć się więcej... +inna_zmienna # Wyrzuca nazwę błędu + +# "if" może być użyte jako wyrażenie +"huraaa!" if 3 > 2 else 2 # => "huraaa!" + +# Listy: +li = [] +# Możesz zacząć od wypełnionej listy +inna_li = [4, 5, 6] + +# Dodaj na koniec, używając "append" +li.append(1) # li to teraz [1] +li.append(2) # li to teraz [1, 2] +li.append(4) # li to teraz [1, 2, 4] +li.append(3) # li to teraz [1, 2, 4, 3] +# Usuwanie z konca da "pop" +li.pop() # => 3 a li stanie się [1, 2, 4] +# Dodajmy ponownie +li.append(3) # li to znowu [1, 2, 4, 3]. + +# Dostęp do list jak do każdej tablicy +li[0] # => 1 +# Aby nadpisać wcześniej wypełnione miejsca w liście, użyj znaku = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Uwaga: ustawiamy starą wartość +# Tak podglądamy ostatni element +li[-1] # => 3 + +# Jeżeli wyjdziesz poza zakres... +li[4] # ... zobaczysz IndexError + +# Możesz też tworzyć wycinki. +li[1:3] # => [2, 4] +# Bez początku +li[2:] # => [4, 3] +# Omijamy koniec +li[:3] # => [1, 2, 4] +# Wybierz co drugi +li[::2] # =>[1, 4] +# Odwróć listę +li[::-1] # => [3, 4, 2, 1] +# Użyj kombinacji powyższych aby tworzyć bardziej skomplikowane wycinki +# li[poczatek:koniec:krok] + +# Usuń element używając "del" +del li[2] # li to teraz [1, 2, 3] + +# Listy można dodawać +li + inna_li # => [1, 2, 3, 4, 5, 6] +# Uwaga: wartości oryginalnych list li i inna_li się nie zmieniają. + +# Do łączenia list użyj "extend()" +li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6] + +# Sprawdź, czy element jest w liście używając "in" +1 in li # => True + +# "len()" pokazuje długość listy +len(li) # => 6 + + +# Krotki (tuple) są jak listy, ale nie można ich modyfikować. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # wyrzuci TypeError + +# Ale wielu akcji dla list możesz używać przy krotkach +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Można rozpakować krotki i listy do poszczególych zmiennych +a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3 +# Jeżeli zapomnisz nawiasów, automatycznie tworzone są krotki +d, e, f = 4, 5, 6 +# Popatrz jak prosto zamienić wartości +e, d = d, e # d to teraz 5 a e to 4 + + +# Słowniki są również pożyteczne +pusty_slownik = {} +# Tu tworzymy wypełniony: +pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3} + +# Podglądany wartość +pelen_slownik["one"] # => 1 + +# Wypisz wszystkie klucze, używając "keys()" +pelen_slownik.keys() # => ["trzy", "dwa", "raz"] +# Uwaga: słowniki nie zapamiętują kolejności kluczy. + +# A teraz wszystkie wartości "values()" +pelen_slownik.values() # => [3, 2, 1] +# Uwaga: to samo dotyczy wartości. + +# Sprawdzanie czy klucz występuje w słowniku za pomocą "in" +"raz" in pelen_slownik # => True +1 in pelen_slownik # => False + +# Próba dobrania się do nieistniejącego klucza da KeyError +pelen_slownik["cztery"] # KeyError + +# Użyj metody "get()", aby uniknąć błędu KeyError +pelen_slownik.get("raz") # => 1 +pelen_slownik.get("cztery") # => None +# Metoda get zwraca domyślną wartość gdy brakuje klucza +pelen_slownik.get("one", 4) # => 1 +pelen_slownik.get("cztery", 4) # => 4 +# zauważ, że pelen_slownik.get("cztery") wciąż zwraca => None +# (get nie ustawia wartości słownika) + +# przypisz wartość do klucza podobnie jak w listach +pelen_slownik["cztery"] = 4 # teraz: pelen_slownik["cztery"] => 4 + +# "setdefault()" wstawia do słownika tylko jeśli nie było klucza +pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5 +pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5 + + +# Teraz zbiory (set) - działają jak zwykłe listy, ale bez potórzeń +pusty_zbior = set() +# Inicjalizujemy "set()" pewnymi wartościami +jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4]) + +# kolejność nie jest zachowana, nawet gdy wydaje się posortowane +inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4]) + +# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru +pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Dodaj więcej elementów przez "add()" +pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5} + +# Znajdź przecięcie (część wspólną) zbiorów, używając & +inny_zbior = {3, 4, 5, 6} +pelen_zbior & other_set # => {3, 4, 5} + +# Suma zbiorów | +pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} + +# Różnicę zbiorów da znak - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Sprawdzanie obecności w zbiorze: "in". +2 in pelen_zbior # => True +10 in pelen_zbior # => False + + +#################################################### +## 3. Kontrola przepływu +#################################################### + +# Tworzymy zmienną jakas_zm +jakas_zm = 5 + +# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia w Pythonie są ważne! +# Poniższy kod wypisze "jakas_zm jest mniejsza niż 10" +if jakas_zm > 10: + print("jakas_zm jest wieksza niż 10") +elif some_var < 10: # Opcjonalna klauzula elif + print("jakas_zm jest mniejsza niż 10") +else: # Również opcjonalna klauzula else + print("jakas_zm jest równa 10") + + +""" +Pętla for iteruje po elementach listy, wypisując: + pies to ssak + kot to ssak + mysz to ssak +""" +for zwierze in ["pies", "kot", "mysz"]: + # Użyj metody format, aby umieścić wartość zmiennej w ciągu + print("{0} to ssak".format(zwierze)) + +""" +"range(liczba)" zwraca listę liczb +z przedziału od zera do wskazanej liczby (bez niej): + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While to pętla, która jest wykonywana, dopóki spełniony jest warunek: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Skrót od x = x + 1 + +# Wyjątki wyłapujemy, używając try i except + +# Działa w Pythonie 2.6 i wyższych: +try: + # Użyj "raise" aby wyrzucić wyjątek + raise IndexError("To błąd indeksu") +except IndexError as e: + pass # Pass to brak reakcji na błąd. Zwykle opisujesz tutaj, jak program ma się zachować w przypadku błędu. +except (TypeError, NameError): + pass # kilka wyjątków można przechwycić jednocześnie. +else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu + print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku. + + +#################################################### +## 4. Funkcje +#################################################### + +# Użyj "def", aby stworzyć nową funkcję +def dodaj(x, y): + print("x to %s, a y to %s" % (x, y)) + return x + y # słowo kluczowe return zwraca wynik działania + +# Tak wywołuje się funkcję z parametrami: +dodaj(5, 6) # => wypisze "x to 5, a y to 6" i zwróci 11 + +# Innym sposobem jest wywołanie z parametrami nazwanymi. +dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia. + + +# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów pozycyjnych, +# które zostaną przekazana jako krotka, pisząc w definicji funkcji "*args" +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów +# nazwanych kwargs, które zostaną przekazane jako słownik, pisząc w definicji funkcji "**kwargs" +def keyword_args(**kwargs): + return kwargs + +# Wywołajmy to i sprawdźmy co się dzieje +keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"} + + +# Możesz też przyjmować jednocześnie zmienną liczbę parametrów pozycyjnych i nazwanych +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) wypisze: + (1, 2) + {"a": 3, "b": 4} +""" + +# Użyj * aby rozwinąć parametry z krotki args +# i użyj ** aby rozwinąć parametry nazwane ze słownika kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # odpowiednik foo(1, 2, 3, 4) +all_the_args(**kwargs) # odpowiednik foo(a=3, b=4) +all_the_args(*args, **kwargs) # odpowiednik foo(1, 2, 3, 4, a=3, b=4) + +# Możesz podać parametry args i kwargs do funkcji równocześnie +# przez rozwinięcie odpowiednio * i ** +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Zasięg zmiennych +x = 5 + +def setX(num): + # Lokalna zmienna x nie jest tym samym co zmienna x + x = num # => 43 + print x # => 43 + +def setGlobalX(num): + global x + print x # => 5 + x = num # globalna zmienna to teraz 6 + print x # => 6 + +setX(43) +setGlobalX(6) + +# Można tworzyć funkcje wewnętrzne i zwrócić je jako wynik +def rob_dodawacz(x): + def dodawacz(y): + return x + y + return dodawacz + +dodaj_10 = rob_dodawacz(10) +dodaj_10(3) # => 13 + +# Są również funkcje anonimowe "lambda" +(lambda x: x > 2)(3) # => True + +# Python ma też wbudowane funkcje wyższego rzędu (przyjmujące inną funkcje jako parametr) +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Można używać wyrażeń listowych (list comprehensions) do mapowania i filtrowania +[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. Klasy +#################################################### + +# Wszystkie klasy są podklasą object +class Czlowiek(object): + + # Atrybut klasy. Występuje we wszystkich instancjach klasy. + gatunek = "H. sapiens" + + # Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji. + # Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają + # specjalne obiekty lub atrybuty wykorzystywane wewnętrznie przez Pythona. + # Nie używaj ich we własnych metodach. + def __init__(self, nazwa): + # przypisz parametr "nazwa" do atrybutu instancji + self.nazwa = nazwa + + # Metoda instancji. Wszystkie metody przyjmują "self" jako pierwszy argument + def mow(self, wiadomosc): + return "%s: %s" % (self.nazwa, wiadomosc) + + # Metoda klasowa współdzielona przez instancje. + # Przyjmuje wywołującą klasę jako pierwszy argument. + @classmethod + def daj_gatunek(cls): + return cls.gatunek + + # Metoda statyczna jest wywoływana bez argumentów klasy czy instancji. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancja klasy +i = Czlowiek(name="Ian") +print(i.mow("cześć")) # wypisze "Ian: cześć" + +j = Czlowiek("Joel") +print(j.mow("cześć")) # wypisze "Joel: cześć" + +# Wywołujemy naszą metodę klasową +i.daj_gatunek() # => "H. sapiens" + +# Zmieniamy wspólny parametr +Czlowiek.gatunek = "H. neanderthalensis" +i.daj_gatunek() # => "H. neanderthalensis" +j.daj_gatunek() # => "H. neanderthalensis" + +# Wywołanie metody statycznej +Czlowiek.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduły +#################################################### + +# Tak importuje się moduły: +import math +print(math.sqrt(16)) # => 4.0 + +# Można podać konkretne funkcje, np. ceil, floor z modułu math +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Można zaimportować wszystkie funkcje z danego modułu. +# Uwaga: nie jest to polecane, bo później w kodzie trudno połapać się, +# która funkcja pochodzi z którego modułu. +from math import * + +# Można skracać nazwy modułów. +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# sprawdźmy czy funkcje są równoważne +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Moduły Pythona to zwykłe skrypty napisane w tym języku. Możesz +# pisać własne i importować je. Nazwa modułu to nazwa pliku. + +# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu. +import math +dir(math) + + +#################################################### +## 7. Zaawansowane +#################################################### + +# Generatory pomagają tworzyć tzw. "leniwy kod" +def podwojne_liczby(iterowalne): + for i in iterowalne: + yield i + i + +# Generatory tworzą wartości w locie. +# Zamiast generować wartości raz i zapisywać je (np. w liście), +# generator tworzy je na bieżąco, w wyniku iteracji. To oznacza, +# że w poniższym przykładzie wartości większe niż 15 nie będą przetworzone +# w funkcji "podwojne_liczby". +# Zauważ, że xrange to generator, który wykonuje tę samą operację co range. +# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci, +# a xrange tworzy obiekt generatora zamiast budować całą listę jak range. + +# Aby odróżnić nazwę zmiennej od nazwy zarezerwowanej w Pythonie, używamy +# zwykle na końcu znaku podkreślenia +xrange_ = xrange(1, 900000000) + +# poniższa pętla będzie podwajać liczby aż do 30 +for i in podwojne_liczby(xrange_): + print(i) + if i >= 30: + break + + +# Dekoratory +# w tym przykładzie "beg" jest nakładką na "say" +# Beg wywołuje say. Jeśli say_please jest prawdziwe, wtedy zwracana wartość +# zostanie zmieniona + +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, "Proszę! Jestem spłukany :(") + return msg + return wrapper + + +@beg +def say(say_please=False): + msg = "Kupisz mi piwo?" + return msg, say_please + + +print(say()) # Kupisz mi piwo? +print(say(say_please=True)) # Kupisz mi piwo? Proszę! Jestem spłukany :( +``` + +## Gotowy na więcej? +### Polskie + +* [Zanurkuj w Pythonie](http://pl.wikibooks.org/wiki/Zanurkuj_w_Pythonie) +* [LearnPythonPl](http://www.learnpython.org/pl/) + +### Angielskie: +#### Darmowe źródła online + +* [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/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +#### Inne + +* [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/python-pt.html.markdown b/pt-br/python-pt.html.markdown deleted file mode 100644 index 82b70117..00000000 --- a/pt-br/python-pt.html.markdown +++ /dev/null @@ -1,509 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Vilson Vieira", "http://automata.cc"] -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. - -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/pt-br/pythonlegacy-pt.html.markdown b/pt-br/pythonlegacy-pt.html.markdown new file mode 100644 index 00000000..82b70117 --- /dev/null +++ b/pt-br/pythonlegacy-pt.html.markdown @@ -0,0 +1,509 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Vilson Vieira", "http://automata.cc"] +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. + +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 deleted file mode 100644 index 0cc33a80..00000000 --- a/python.html.markdown +++ /dev/null @@ -1,827 +0,0 @@ ---- -language: python -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: 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. - -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. - -```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/pythonlegacy.html.markdown b/pythonlegacy.html.markdown new file mode 100644 index 00000000..0cc33a80 --- /dev/null +++ b/pythonlegacy.html.markdown @@ -0,0 +1,827 @@ +--- +language: python +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: 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. + +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. + +```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/python-ro.html.markdown deleted file mode 100644 index ada0c034..00000000 --- a/ro-ro/python-ro.html.markdown +++ /dev/null @@ -1,493 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Ovidiu Ciule", "https://github.com/ociule"] -filename: learnpython-ro.py -lang: ro-ro ---- - -Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a -devenit astăzi unul din cele mai populare limbaje de programare. -M-am indrăgostit de Python pentru claritatea sa sintactică. Python este aproape -pseudocod executabil. - -Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) -sau ociule [at] [google's email service] - -Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. -O versiune Python 3 va apărea în curând, în limba engleză mai întâi. - -```python -# Comentariile pe o singură linie încep cu un caracter diez. -""" Şirurile de caractere pe mai multe linii pot fi încadrate folosind trei caractere ", şi sunt des - folosite ca şi comentarii pe mai multe linii. -""" - -#################################################### -## 1. Operatori şi tipuri de date primare -#################################################### - -# Avem numere -3 #=> 3 - -# Matematica se comportă cum ne-am aştepta -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere -# întregi şi rotunjeşte -# automat spre valoarea mai mică -5 / 2 #=> 2 - -# Pentru a folosi împărţirea fără rest avem nevoie de numere reale -2.0 # Acesta e un număr real -11.0 / 4.0 #=> 2.75 ahhh ... cum ne aşteptam - -# Ordinea operaţiilor se poate forţa cu paranteze -(1 + 3) * 2 #=> 8 - -# Valoriile boolene sunt şi ele valori primare -True -False - -# Pot fi negate cu operatorul not -not True #=> False -not False #=> True - -# Egalitatea este == -1 == 1 #=> True -2 == 1 #=> False - -# Inegalitate este != -1 != 1 #=> False -2 != 1 #=> True - -# Comparaţii -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Comparaţiile pot fi inlănţuite! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Şirurile de caractere pot fi încadrate cu " sau ' -"Acesta e un şir de caractere." -'Şi acesta este un şir de caractere.' - -# Şirurile de caractere pot fi adăugate! -"Hello " + "world!" #=> "Hello world!" - -# Un şir de caractere poate fi folosit ca o listă -"Acesta e un şir de caractere"[0] #=> 'A' - -# Caracterul % (procent) poate fi folosit pentru a formata şiruri de caractere : -"%s pot fi %s" % ("şirurile", "interpolate") - -# O metodă mai nouă de a formata şiruri este metoda "format" -# Este metoda recomandată -"{0} pot fi {1}".format("şirurile", "formatate") -# Puteţi folosi cuvinte cheie dacă nu doriţi sa număraţi -"{nume} vrea să mănânce {fel}".format(nume="Bob", fel="lasagna") - -# "None", care reprezintă valoarea nedefinită, e un obiect -None #=> None - -# Nu folosiţi operatorul == pentru a compara un obiect cu None -# Folosiţi operatorul "is" -"etc" is None #=> False -None is None #=> True - -# Operatorul "is" testeaza dacă obiectele sunt identice. -# Acastă operaţie nu e foarte folositoare cu tipuri primare, -# dar e foarte folositoare cu obiecte. - -# None, 0, şi şiruri de caractere goale sunt evaluate ca si fals, False. -# Toate celelalte valori sunt adevărate, True. -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. Variabile şi colecţii -#################################################### - -# Printarea este uşoară -print "Eu sunt Python. Încântat de cunoştinţă!" - - -# Nu este nevoie sa declari variabilele înainte de a le folosi -o_variabila = 5 # Convenţia este de a folosi caractere_minuscule_cu_underscore -o_variabila #=> 5 - -# Dacă accesăm o variabilă nefolosită declanşăm o excepţie. -# Vezi secţiunea Control de Execuţie pentru mai multe detalii despre excepţii. -alta_variabila # Declanşează o eroare de nume - -# "If" poate fi folosit într-o expresie. -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# Listele sunt folosite pentru colecţii -li = [] -# O listă poate avea valori de la început -alta_li = [4, 5, 6] - -# Se adaugă valori la sfârşitul lister cu append -li.append(1) #li e acum [1] -li.append(2) #li e acum [1, 2] -li.append(4) #li e acum [1, 2, 4] -li.append(3) #li este acum [1, 2, 4, 3] -# Se şterg de la sfarşit cu pop -li.pop() #=> 3 şi li e acum [1, 2, 4] -# Să o adaugăm înapoi valoarea -li.append(3) # li e din nou [1, 2, 4, 3] - -# Putem accesa valorile individuale dintr-o listă cu operatorul index -li[0] #=> 1 -# Valoarea speciala -1 pentru index accesează ultima valoare -li[-1] #=> 3 - -# Dacă depaşim limitele listei declanşăm o eroare IndexError -li[4] # Declanşează IndexError - -# Putem să ne uităm la intervale folosind sintaxa de "felii" -# În Python, intervalele sunt închise la început si deschise la sfârşit. -li[1:3] #=> [2, 4] -# Fără început -li[2:] #=> [4, 3] -# Fără sfarşit -li[:3] #=> [1, 2, 4] - -# Putem şterge elemente arbitrare din lista cu operatorul "del" care primeşte indexul lor -del li[2] # li e acum [1, 2, 3] - -# Listele pot fi adăugate -li + alta_li #=> [1, 2, 3, 4, 5, 6] - Notă: li si alta_li nu sunt modificate! - -# Concatenăm liste cu "extend()" -li.extend(alta_li) # Acum li este [1, 2, 3, 4, 5, 6] - -# Se verifică existenţa valorilor in lista cu "in" -1 in li #=> True - -# Şi lungimea cu "len()" -len(li) #=> 6 - - -# Tuplele sunt ca şi listele dar imutabile -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Declanşează TypeError - -# Pot fi folosite ca şi liste -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Tuplele pot fi despachetate -a, b, c = (1, 2, 3) # a este acum 1, b este acum 2 şi c este acum 3 -# Tuplele pot fi folosite şi fără paranteze -d, e, f = 4, 5, 6 -# Putem inversa valori foarte uşor! -e, d = d, e # d este acum 5 şi e este acum 4 - - -# Dicţionarele stochează chei şi o valoare pentru fiecare cheie -dict_gol = {} -# Şi un dicţionar cu valori -dict_cu_valori = {"unu": 1, "doi": 2, "trei": 3} - -# Căutaţi valori cu [] -dict_cu_valori["unu"] #=> 1 - -# Obţinem lista cheilor cu "keys()" -dict_cu_valori.keys() #=> ["trei", "doi", "unu"] -# Notă - ordinea cheilor obţinute cu keys() nu este garantată. -# Puteţi obţine rezultate diferite de exemplul de aici. - -# Obţinem valorile cu values() -dict_cu_valori.values() #=> [3, 2, 1] -# Notă - aceeaşi ca mai sus, aplicată asupra valorilor. - -# Verificăm existenţa unei valori cu "in" -"unu" in dict_cu_valori #=> True -1 in dict_cu_valori #=> False - -# Accesarea unei chei care nu exista declanşează o KeyError -dict_cu_valori["four"] # KeyError - -# Putem folosi metoda "get()" pentru a evita KeyError -dict_cu_valori.get("one") #=> 1 -dict_cu_valori.get("four") #=> None -# Metoda get poate primi ca al doilea argument o valoare care va fi returnată -# când cheia nu este prezentă. -dict_cu_valori.get("one", 4) #=> 1 -dict_cu_valori.get("four", 4) #=> 4 - -# "setdefault()" este o metodă pentru a adăuga chei-valori fără a le modifica, dacă cheia există deja -dict_cu_valori.setdefault("five", 5) #dict_cu_valori["five"] este acum 5 -dict_cu_valori.setdefault("five", 6) #dict_cu_valori["five"] exista deja, nu este modificată, tot 5 - - -# Set este colecţia mulţime -set_gol = set() -# Putem crea un set cu valori -un_set = set([1,2,2,3,4]) # un_set este acum set([1, 2, 3, 4]), amintiţi-vă ca mulţimile garantează unicatul! - -# În Python 2.7, {} poate fi folosit pentru un set -set_cu_valori = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# Putem adăuga valori cu add -set_cu_valori.add(5) # set_cu_valori este acum {1, 2, 3, 4, 5} - -# Putem intersecta seturi -alt_set = {3, 4, 5, 6} -set_cu_valori & alt_set #=> {3, 4, 5} - -# Putem calcula uniunea cu | -set_cu_valori | alt_set #=> {1, 2, 3, 4, 5, 6} - -# Diferenţa între seturi se face cu - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Verificăm existenţa cu "in" -2 in set_cu_valori #=> True -10 in set_cu_valori #=> False - - -#################################################### -## 3. Controlul Execuţiei -#################################################### - -# O variabilă -o_variabila = 5 - -# Acesta este un "if". Indentarea este importanta în python! -# Printează "o_variabila este mai mică ca 10" -if o_variabila > 10: - print "o_variabila e mai mare ca 10." -elif o_variabila < 10: # Clauza elif e opţională. - print "o_variabila este mai mică ca 10." -else: # Şi else e opţional. - print "o_variabila este exact 10." - - -""" -Buclele "for" pot fi folosite pentru a parcurge liste -Vom afişa: - câinele este un mamifer - pisica este un mamifer - şoarecele este un mamifer -""" -for animal in ["câinele", "pisica", "şoarecele"]: - # Folosim % pentru a compune mesajul - print "%s este un mamifer" % animal - -""" -"range(număr)" crează o lista de numere -de la zero la numărul dat -afişează: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -While repetă pana când condiţia dată nu mai este adevărată. -afişează: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Prescurtare pentru x = x + 1 - -# Recepţionăm excepţii cu blocuri try/except - -# Acest cod e valid in Python > 2.6: -try: - # Folosim "raise" pentru a declanşa o eroare - raise IndexError("Asta este o IndexError") -except IndexError as e: - pass # Pass nu face nimic. În mod normal aici ne-am ocupa de eroare. - - -#################################################### -## 4. Funcţii -#################################################### - -# Folosim "def" pentru a defini funcţii -def add(x, y): - print "x este %s şi y este %s" % (x, y) - return x + y # Funcţia poate returna valori cu "return" - -# Apelăm funcţia "add" cu parametrii -add(5, 6) #=> Va afişa "x este 5 şi y este 6" şi va returna 11 - -# Altă cale de a apela funcţii: cu parametrii numiţi -add(y=6, x=5) # Ordinea parametrilor numiţi nu contează - -# Putem defini funcţii care primesc un număr variabil de parametrii nenumiţi -# Aceşti parametrii nenumiţi se cheamă si poziţinali -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Şi putem defini funcţii care primesc un număr variabil de parametrii numiţi -def keyword_args(**kwargs): - return kwargs - -# Hai să vedem cum merge -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Se pot combina -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) va afişa: - (1, 2) - {"a": 3, "b": 4} -""" - -# Când apelăm funcţii, putem face inversul args/kwargs! -# Folosim * pentru a expanda tuple şi ** pentru a expanda kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # echivalent cu foo(1, 2, 3, 4) -all_the_args(**kwargs) # echivalent cu foo(a=3, b=4) -all_the_args(*args, **kwargs) # echivalent cu foo(1, 2, 3, 4, a=3, b=4) - -# În Python, funcţiile sunt obiecte primare -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Funcţiile pot fi anonime -(lambda x: x > 2)(3) #=> True - -# Există funcţii de ordin superior (care operează pe alte funcţii) predefinite -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Putem folosi scurtături de liste pentru a simplifica munca cu map si filter -[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. Clase -#################################################### - -# Moştenim object pentru a crea o nouă clasă -class Om(object): - - # Acesta este un atribut al clasei. Va fi moştenit de toate instanţele. - species = "H. sapiens" - - # Constructor (mai degrabă, configurator de bază) - def __init__(self, nume): - # Valoarea parametrului este stocată in atributul instanţei - self.nume = nume - - # Aceasta este o metoda a instanţei. - # Toate metodele primesc "self" ca si primul argument. - def spune(self, mesaj): - return "%s: %s" % (self.nume, mesaj) - - # O metodă a clasei. Este partajată de toate instanţele. - # Va primi ca si primul argument clasa căreia îi aparţine. - @classmethod - def get_species(cls): - return cls.species - - # O metoda statica nu primeste un argument automat. - @staticmethod - def exclama(): - return "*Aaaaaah*" - - -# Instanţiem o clasă -i = Om(nume="Ion") -print i.spune("salut") # afişează: "Ion: salut" - -j = Om("George") -print j.spune("ciau") # afişează George: ciau" - -# Apelăm metoda clasei -i.get_species() #=> "H. sapiens" - -# Modificăm atributul partajat -Om.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Apelăm metoda statică -Om.exclama() #=> "*Aaaaaah*" - - -#################################################### -## 6. Module -#################################################### - -# Pentru a folosi un modul, trebuie importat -import math -print math.sqrt(16) #=> 4.0 - -# Putem importa doar anumite funcţii dintr-un modul -from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 - -# Putem importa toate funcţiile dintr-un modul, dar nu este o idee bună -# Nu faceţi asta! -from math import * - -# Numele modulelor pot fi modificate la import, de exemplu pentru a le scurta -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Modulele python sunt pur şi simplu fişiere cu cod python. -# Puteţi sa creaţi modulele voastre, şi sa le importaţi. -# Numele modulului este acelasi cu numele fişierului. - -# Cu "dir" inspectăm ce funcţii conţine un modul -import math -dir(math) - - -``` - -## Doriţi mai mult? - -### Gratis online, în limba engleză - -* [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/) - -### Cărţi, în limba engleză - -* [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/pythonlegacy-ro.html.markdown b/ro-ro/pythonlegacy-ro.html.markdown new file mode 100644 index 00000000..ada0c034 --- /dev/null +++ b/ro-ro/pythonlegacy-ro.html.markdown @@ -0,0 +1,493 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Ovidiu Ciule", "https://github.com/ociule"] +filename: learnpython-ro.py +lang: ro-ro +--- + +Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a +devenit astăzi unul din cele mai populare limbaje de programare. +M-am indrăgostit de Python pentru claritatea sa sintactică. Python este aproape +pseudocod executabil. + +Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) +sau ociule [at] [google's email service] + +Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. +O versiune Python 3 va apărea în curând, în limba engleză mai întâi. + +```python +# Comentariile pe o singură linie încep cu un caracter diez. +""" Şirurile de caractere pe mai multe linii pot fi încadrate folosind trei caractere ", şi sunt des + folosite ca şi comentarii pe mai multe linii. +""" + +#################################################### +## 1. Operatori şi tipuri de date primare +#################################################### + +# Avem numere +3 #=> 3 + +# Matematica se comportă cum ne-am aştepta +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere +# întregi şi rotunjeşte +# automat spre valoarea mai mică +5 / 2 #=> 2 + +# Pentru a folosi împărţirea fără rest avem nevoie de numere reale +2.0 # Acesta e un număr real +11.0 / 4.0 #=> 2.75 ahhh ... cum ne aşteptam + +# Ordinea operaţiilor se poate forţa cu paranteze +(1 + 3) * 2 #=> 8 + +# Valoriile boolene sunt şi ele valori primare +True +False + +# Pot fi negate cu operatorul not +not True #=> False +not False #=> True + +# Egalitatea este == +1 == 1 #=> True +2 == 1 #=> False + +# Inegalitate este != +1 != 1 #=> False +2 != 1 #=> True + +# Comparaţii +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Comparaţiile pot fi inlănţuite! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Şirurile de caractere pot fi încadrate cu " sau ' +"Acesta e un şir de caractere." +'Şi acesta este un şir de caractere.' + +# Şirurile de caractere pot fi adăugate! +"Hello " + "world!" #=> "Hello world!" + +# Un şir de caractere poate fi folosit ca o listă +"Acesta e un şir de caractere"[0] #=> 'A' + +# Caracterul % (procent) poate fi folosit pentru a formata şiruri de caractere : +"%s pot fi %s" % ("şirurile", "interpolate") + +# O metodă mai nouă de a formata şiruri este metoda "format" +# Este metoda recomandată +"{0} pot fi {1}".format("şirurile", "formatate") +# Puteţi folosi cuvinte cheie dacă nu doriţi sa număraţi +"{nume} vrea să mănânce {fel}".format(nume="Bob", fel="lasagna") + +# "None", care reprezintă valoarea nedefinită, e un obiect +None #=> None + +# Nu folosiţi operatorul == pentru a compara un obiect cu None +# Folosiţi operatorul "is" +"etc" is None #=> False +None is None #=> True + +# Operatorul "is" testeaza dacă obiectele sunt identice. +# Acastă operaţie nu e foarte folositoare cu tipuri primare, +# dar e foarte folositoare cu obiecte. + +# None, 0, şi şiruri de caractere goale sunt evaluate ca si fals, False. +# Toate celelalte valori sunt adevărate, True. +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variabile şi colecţii +#################################################### + +# Printarea este uşoară +print "Eu sunt Python. Încântat de cunoştinţă!" + + +# Nu este nevoie sa declari variabilele înainte de a le folosi +o_variabila = 5 # Convenţia este de a folosi caractere_minuscule_cu_underscore +o_variabila #=> 5 + +# Dacă accesăm o variabilă nefolosită declanşăm o excepţie. +# Vezi secţiunea Control de Execuţie pentru mai multe detalii despre excepţii. +alta_variabila # Declanşează o eroare de nume + +# "If" poate fi folosit într-o expresie. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listele sunt folosite pentru colecţii +li = [] +# O listă poate avea valori de la început +alta_li = [4, 5, 6] + +# Se adaugă valori la sfârşitul lister cu append +li.append(1) #li e acum [1] +li.append(2) #li e acum [1, 2] +li.append(4) #li e acum [1, 2, 4] +li.append(3) #li este acum [1, 2, 4, 3] +# Se şterg de la sfarşit cu pop +li.pop() #=> 3 şi li e acum [1, 2, 4] +# Să o adaugăm înapoi valoarea +li.append(3) # li e din nou [1, 2, 4, 3] + +# Putem accesa valorile individuale dintr-o listă cu operatorul index +li[0] #=> 1 +# Valoarea speciala -1 pentru index accesează ultima valoare +li[-1] #=> 3 + +# Dacă depaşim limitele listei declanşăm o eroare IndexError +li[4] # Declanşează IndexError + +# Putem să ne uităm la intervale folosind sintaxa de "felii" +# În Python, intervalele sunt închise la început si deschise la sfârşit. +li[1:3] #=> [2, 4] +# Fără început +li[2:] #=> [4, 3] +# Fără sfarşit +li[:3] #=> [1, 2, 4] + +# Putem şterge elemente arbitrare din lista cu operatorul "del" care primeşte indexul lor +del li[2] # li e acum [1, 2, 3] + +# Listele pot fi adăugate +li + alta_li #=> [1, 2, 3, 4, 5, 6] - Notă: li si alta_li nu sunt modificate! + +# Concatenăm liste cu "extend()" +li.extend(alta_li) # Acum li este [1, 2, 3, 4, 5, 6] + +# Se verifică existenţa valorilor in lista cu "in" +1 in li #=> True + +# Şi lungimea cu "len()" +len(li) #=> 6 + + +# Tuplele sunt ca şi listele dar imutabile +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Declanşează TypeError + +# Pot fi folosite ca şi liste +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Tuplele pot fi despachetate +a, b, c = (1, 2, 3) # a este acum 1, b este acum 2 şi c este acum 3 +# Tuplele pot fi folosite şi fără paranteze +d, e, f = 4, 5, 6 +# Putem inversa valori foarte uşor! +e, d = d, e # d este acum 5 şi e este acum 4 + + +# Dicţionarele stochează chei şi o valoare pentru fiecare cheie +dict_gol = {} +# Şi un dicţionar cu valori +dict_cu_valori = {"unu": 1, "doi": 2, "trei": 3} + +# Căutaţi valori cu [] +dict_cu_valori["unu"] #=> 1 + +# Obţinem lista cheilor cu "keys()" +dict_cu_valori.keys() #=> ["trei", "doi", "unu"] +# Notă - ordinea cheilor obţinute cu keys() nu este garantată. +# Puteţi obţine rezultate diferite de exemplul de aici. + +# Obţinem valorile cu values() +dict_cu_valori.values() #=> [3, 2, 1] +# Notă - aceeaşi ca mai sus, aplicată asupra valorilor. + +# Verificăm existenţa unei valori cu "in" +"unu" in dict_cu_valori #=> True +1 in dict_cu_valori #=> False + +# Accesarea unei chei care nu exista declanşează o KeyError +dict_cu_valori["four"] # KeyError + +# Putem folosi metoda "get()" pentru a evita KeyError +dict_cu_valori.get("one") #=> 1 +dict_cu_valori.get("four") #=> None +# Metoda get poate primi ca al doilea argument o valoare care va fi returnată +# când cheia nu este prezentă. +dict_cu_valori.get("one", 4) #=> 1 +dict_cu_valori.get("four", 4) #=> 4 + +# "setdefault()" este o metodă pentru a adăuga chei-valori fără a le modifica, dacă cheia există deja +dict_cu_valori.setdefault("five", 5) #dict_cu_valori["five"] este acum 5 +dict_cu_valori.setdefault("five", 6) #dict_cu_valori["five"] exista deja, nu este modificată, tot 5 + + +# Set este colecţia mulţime +set_gol = set() +# Putem crea un set cu valori +un_set = set([1,2,2,3,4]) # un_set este acum set([1, 2, 3, 4]), amintiţi-vă ca mulţimile garantează unicatul! + +# În Python 2.7, {} poate fi folosit pentru un set +set_cu_valori = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Putem adăuga valori cu add +set_cu_valori.add(5) # set_cu_valori este acum {1, 2, 3, 4, 5} + +# Putem intersecta seturi +alt_set = {3, 4, 5, 6} +set_cu_valori & alt_set #=> {3, 4, 5} + +# Putem calcula uniunea cu | +set_cu_valori | alt_set #=> {1, 2, 3, 4, 5, 6} + +# Diferenţa între seturi se face cu - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Verificăm existenţa cu "in" +2 in set_cu_valori #=> True +10 in set_cu_valori #=> False + + +#################################################### +## 3. Controlul Execuţiei +#################################################### + +# O variabilă +o_variabila = 5 + +# Acesta este un "if". Indentarea este importanta în python! +# Printează "o_variabila este mai mică ca 10" +if o_variabila > 10: + print "o_variabila e mai mare ca 10." +elif o_variabila < 10: # Clauza elif e opţională. + print "o_variabila este mai mică ca 10." +else: # Şi else e opţional. + print "o_variabila este exact 10." + + +""" +Buclele "for" pot fi folosite pentru a parcurge liste +Vom afişa: + câinele este un mamifer + pisica este un mamifer + şoarecele este un mamifer +""" +for animal in ["câinele", "pisica", "şoarecele"]: + # Folosim % pentru a compune mesajul + print "%s este un mamifer" % animal + +""" +"range(număr)" crează o lista de numere +de la zero la numărul dat +afişează: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While repetă pana când condiţia dată nu mai este adevărată. +afişează: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Prescurtare pentru x = x + 1 + +# Recepţionăm excepţii cu blocuri try/except + +# Acest cod e valid in Python > 2.6: +try: + # Folosim "raise" pentru a declanşa o eroare + raise IndexError("Asta este o IndexError") +except IndexError as e: + pass # Pass nu face nimic. În mod normal aici ne-am ocupa de eroare. + + +#################################################### +## 4. Funcţii +#################################################### + +# Folosim "def" pentru a defini funcţii +def add(x, y): + print "x este %s şi y este %s" % (x, y) + return x + y # Funcţia poate returna valori cu "return" + +# Apelăm funcţia "add" cu parametrii +add(5, 6) #=> Va afişa "x este 5 şi y este 6" şi va returna 11 + +# Altă cale de a apela funcţii: cu parametrii numiţi +add(y=6, x=5) # Ordinea parametrilor numiţi nu contează + +# Putem defini funcţii care primesc un număr variabil de parametrii nenumiţi +# Aceşti parametrii nenumiţi se cheamă si poziţinali +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Şi putem defini funcţii care primesc un număr variabil de parametrii numiţi +def keyword_args(**kwargs): + return kwargs + +# Hai să vedem cum merge +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Se pot combina +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) va afişa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Când apelăm funcţii, putem face inversul args/kwargs! +# Folosim * pentru a expanda tuple şi ** pentru a expanda kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # echivalent cu foo(1, 2, 3, 4) +all_the_args(**kwargs) # echivalent cu foo(a=3, b=4) +all_the_args(*args, **kwargs) # echivalent cu foo(1, 2, 3, 4, a=3, b=4) + +# În Python, funcţiile sunt obiecte primare +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Funcţiile pot fi anonime +(lambda x: x > 2)(3) #=> True + +# Există funcţii de ordin superior (care operează pe alte funcţii) predefinite +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Putem folosi scurtături de liste pentru a simplifica munca cu map si filter +[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. Clase +#################################################### + +# Moştenim object pentru a crea o nouă clasă +class Om(object): + + # Acesta este un atribut al clasei. Va fi moştenit de toate instanţele. + species = "H. sapiens" + + # Constructor (mai degrabă, configurator de bază) + def __init__(self, nume): + # Valoarea parametrului este stocată in atributul instanţei + self.nume = nume + + # Aceasta este o metoda a instanţei. + # Toate metodele primesc "self" ca si primul argument. + def spune(self, mesaj): + return "%s: %s" % (self.nume, mesaj) + + # O metodă a clasei. Este partajată de toate instanţele. + # Va primi ca si primul argument clasa căreia îi aparţine. + @classmethod + def get_species(cls): + return cls.species + + # O metoda statica nu primeste un argument automat. + @staticmethod + def exclama(): + return "*Aaaaaah*" + + +# Instanţiem o clasă +i = Om(nume="Ion") +print i.spune("salut") # afişează: "Ion: salut" + +j = Om("George") +print j.spune("ciau") # afişează George: ciau" + +# Apelăm metoda clasei +i.get_species() #=> "H. sapiens" + +# Modificăm atributul partajat +Om.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Apelăm metoda statică +Om.exclama() #=> "*Aaaaaah*" + + +#################################################### +## 6. Module +#################################################### + +# Pentru a folosi un modul, trebuie importat +import math +print math.sqrt(16) #=> 4.0 + +# Putem importa doar anumite funcţii dintr-un modul +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Putem importa toate funcţiile dintr-un modul, dar nu este o idee bună +# Nu faceţi asta! +from math import * + +# Numele modulelor pot fi modificate la import, de exemplu pentru a le scurta +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Modulele python sunt pur şi simplu fişiere cu cod python. +# Puteţi sa creaţi modulele voastre, şi sa le importaţi. +# Numele modulului este acelasi cu numele fişierului. + +# Cu "dir" inspectăm ce funcţii conţine un modul +import math +dir(math) + + +``` + +## Doriţi mai mult? + +### Gratis online, în limba engleză + +* [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/) + +### Cărţi, în limba engleză + +* [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/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown deleted file mode 100644 index 6087a686..00000000 --- a/ru-ru/python-ru.html.markdown +++ /dev/null @@ -1,643 +0,0 @@ ---- -language: python -lang: ru-ru -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -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 знака " и обычно используется - в качестве встроенной документации -""" - -#################################################### -## 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 Вооот... Так гораздо лучше - -# Результат целочисленного деления округляется в меньшую сторону -# как для положительных, так и для отрицательных чисел. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Остаток от деления -7 % 3 # => 1 - -# Возведение в степень -2**4 # => 16 - -# Приоритет операций указывается скобками -(1 + 3) * 2 #=> 8 - -# Логические операторы -# Обратите внимание: ключевые слова «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 - -# Для отрицания используется ключевое слово 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 - -# Строки определяются символом " или ' -"Это строка." -'Это тоже строка.' - -# И строки тоже можно складывать! -"Привет " + "мир!" #=> "Привет мир!" - -# ... или умножать -"Привет" * 3 # => "ПриветПриветПривет" - -# Со строкой можно работать, как со списком символов -"Это строка"[0] #=> 'Э' - -# Символ % используется для форматирования строк, например: -"%s могут быть %s" % ("строки", "интерполированы") - -# Новый способ форматирования строк — использование метода format. -# Это предпочитаемый способ. -"{0} могут быть {1}".format("строки", "форматированы") - -# Если вы не хотите считать, можете использовать ключевые слова. -"{name} хочет есть {food}".format(name="Боб", food="лазанью") - -# None является объектом -None #=> None - -# Не используйте оператор равенства '=='' для сравнения -# объектов с None. Используйте для этого «is» -"etc" is None #=> False -None is None #=> True - -# Оператор 'is' проверяет идентичность объектов. Он не -# очень полезен при работе с примитивными типами, но -# зато просто незаменим при работе с объектами. - -# None, 0 и пустые строки/списки равны False. -# Все остальные значения равны True -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. Переменные и коллекции -#################################################### - -# В 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_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] -li.append(4) # [1, 2, 4] -li.append(3) # [1, 2, 4, 3] -# И удаляются с конца методом pop -li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] -# Положим элемент обратно -li.append(3) # [1, 2, 4, 3]. - -# Обращайтесь со списком, как с обычным массивом -li[0] #=> 1 -# Присваивайте новые значения уже инициализированным индексам с помощью = -li[0] = 42 -li[0] # => 42 -li[0] = 1 # Обратите внимание: возвращаемся на исходное значение -# Обратимся к последнему элементу -li[-1] #=> 3 - -# Попытка выйти за границы массива приведёт к ошибке индекса -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 теперь [1, 2, 3] - -# Вы можете складывать, или, как ещё говорят, конкатенировать списки -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] - -# Проверить элемент на вхождение в список можно оператором 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 -filled_dict.keys() #=> ["three", "two", "one"] -# Замечание: сохранение порядка ключей в словаре не гарантируется -# Ваши результаты могут не совпадать с этими. - -# Можно получить и все значения в виде списка, используйте метод values -filled_dict.values() #=> [3, 2, 1] -# То же самое замечание насчёт порядка ключей справедливо и здесь - -# При помощи оператора in можно проверять ключи на вхождение в словарь -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Попытка получить значение по несуществующему ключу выбросит ошибку ключа -filled_dict["four"] # KeyError - -# Чтобы избежать этого, используйте метод get() -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# Метод get также принимает аргумент по умолчанию, значение которого будет -# возвращено при отсутствии указанного ключа -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() вставляет пару ключ-значение, только если такого ключа нет -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]) - -# Порядок сортировки не гарантируется, хотя иногда они выглядят отсортированными -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} - -# Пересечение множеств: & -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: # Это тоже необязательно. - print("some_var равно 10.") - - -""" -Циклы For проходят по спискам - -Результат: - собака — это млекопитающее - кошка — это млекопитающее - мышь — это млекопитающее -""" -for animal in ["собака", "кошка", "мышь"]: - # Можете использовать оператор % для интерполяции форматированных строк - print("%s — это млекопитающее" % animal) - -""" -«range(число)» возвращает список чисел -от нуля до заданного числа -Результат: - 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("Это ошибка индекса") -except IndexError as e: - # pass — это просто отсутствие оператора. Обычно здесь происходит - # восстановление после ошибки. - pass -except (TypeError, NameError): - pass # Несколько исключений можно обработать вместе, если нужно. -else: # Необязательное выражение. Должно следовать за последним блоком except - print("Всё хорошо!") # Выполнится, только если не было никаких исключений - - - -#################################################### -## 4. Функции -#################################################### - -# Используйте def для создания новых функций -def add(x, y): - print("x равен %s, а y равен %s" % (x, y)) - return x + y # Возвращайте результат с помощью ключевого слова return - -# Вызов функции с аргументами -add(5, 6) #=> выводит «x равен 5, а y равен 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) выводит: - (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) - -# вы можете передавать переменное число позиционных или именованных аргументов -# другим функциям, которые их принимают, распаковывая их с помощью -# * или ** соответственно -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - -# Область определения функций -x = 5 - -def setX(num): - # Локальная переменная x — это не то же самое, что глобальная переменная x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # Глобальная переменная x теперь равна 6 - 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): - # Присваивание значения аргумента атрибуту класса 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="Иван") -print(i.say("привет")) # Выводит: «Иван: привет» - -j = Human("Пётр") -print(j.say("Привет")) # Выводит: «Пётр: привет» - -# Вызов метода класса -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 -# Вы также можете убедиться, что функции эквивалентны -from math import sqrt -math.sqrt == m.sqrt == sqrt # => True - -# Модули в Python — это обычные Python-файлы. Вы -# можете писать свои модули и импортировать их. Название -# модуля совпадает с названием файла. - -# Вы можете узнать, какие функции и атрибуты определены -# в модуле -import math -dir(math) - -#################################################### -## 7. Дополнительно -#################################################### - -# Генераторы помогут выполнить ленивые вычисления -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Генератор создаёт значения на лету. -# Он не возвращает все значения разом, а создаёт каждое из них при каждой -# итерации. Это значит, что значения больше 15 в double_numbers -# обработаны не будут. -# Обратите внимание: xrange — это генератор, который делает то же, что и range. -# Создание списка чисел от 1 до 900000000 требует много места и времени. -# xrange создаёт объект генератора, а не список сразу, как это делает range. -# Если нам нужно имя переменной, совпадающее с ключевым словом Python, -# мы используем подчёркивание в конце -xrange_ = xrange(1, 900000000) - -# Будет удваивать все числа, пока результат не превысит 30 -for i in double_numbers(xrange_): - print(i) - if i >= 30: - break - - -# Декораторы -# В этом примере beg оборачивает say -# Метод beg вызовет say. Если say_please равно True, -# он изменит возвращаемое сообщение -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, " Пожалуйста! У меня нет денег :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Вы не купите мне пива?" - return msg, say_please - - -print(say()) # Вы не купите мне пива? -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/) -* [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) - -### Платные - -* [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/ru-ru/pythonlegacy-ru.html.markdown b/ru-ru/pythonlegacy-ru.html.markdown new file mode 100644 index 00000000..6087a686 --- /dev/null +++ b/ru-ru/pythonlegacy-ru.html.markdown @@ -0,0 +1,643 @@ +--- +language: python +lang: ru-ru +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +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 знака " и обычно используется + в качестве встроенной документации +""" + +#################################################### +## 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 Вооот... Так гораздо лучше + +# Результат целочисленного деления округляется в меньшую сторону +# как для положительных, так и для отрицательных чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Остаток от деления +7 % 3 # => 1 + +# Возведение в степень +2**4 # => 16 + +# Приоритет операций указывается скобками +(1 + 3) * 2 #=> 8 + +# Логические операторы +# Обратите внимание: ключевые слова «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 + +# Для отрицания используется ключевое слово 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 + +# Строки определяются символом " или ' +"Это строка." +'Это тоже строка.' + +# И строки тоже можно складывать! +"Привет " + "мир!" #=> "Привет мир!" + +# ... или умножать +"Привет" * 3 # => "ПриветПриветПривет" + +# Со строкой можно работать, как со списком символов +"Это строка"[0] #=> 'Э' + +# Символ % используется для форматирования строк, например: +"%s могут быть %s" % ("строки", "интерполированы") + +# Новый способ форматирования строк — использование метода format. +# Это предпочитаемый способ. +"{0} могут быть {1}".format("строки", "форматированы") + +# Если вы не хотите считать, можете использовать ключевые слова. +"{name} хочет есть {food}".format(name="Боб", food="лазанью") + +# None является объектом +None #=> None + +# Не используйте оператор равенства '=='' для сравнения +# объектов с None. Используйте для этого «is» +"etc" is None #=> False +None is None #=> True + +# Оператор 'is' проверяет идентичность объектов. Он не +# очень полезен при работе с примитивными типами, но +# зато просто незаменим при работе с объектами. + +# None, 0 и пустые строки/списки равны False. +# Все остальные значения равны True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Переменные и коллекции +#################################################### + +# В 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_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] +li.append(4) # [1, 2, 4] +li.append(3) # [1, 2, 4, 3] +# И удаляются с конца методом pop +li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] +# Положим элемент обратно +li.append(3) # [1, 2, 4, 3]. + +# Обращайтесь со списком, как с обычным массивом +li[0] #=> 1 +# Присваивайте новые значения уже инициализированным индексам с помощью = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Обратите внимание: возвращаемся на исходное значение +# Обратимся к последнему элементу +li[-1] #=> 3 + +# Попытка выйти за границы массива приведёт к ошибке индекса +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 теперь [1, 2, 3] + +# Вы можете складывать, или, как ещё говорят, конкатенировать списки +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] + +# Проверить элемент на вхождение в список можно оператором 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 +filled_dict.keys() #=> ["three", "two", "one"] +# Замечание: сохранение порядка ключей в словаре не гарантируется +# Ваши результаты могут не совпадать с этими. + +# Можно получить и все значения в виде списка, используйте метод values +filled_dict.values() #=> [3, 2, 1] +# То же самое замечание насчёт порядка ключей справедливо и здесь + +# При помощи оператора in можно проверять ключи на вхождение в словарь +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Попытка получить значение по несуществующему ключу выбросит ошибку ключа +filled_dict["four"] # KeyError + +# Чтобы избежать этого, используйте метод get() +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Метод get также принимает аргумент по умолчанию, значение которого будет +# возвращено при отсутствии указанного ключа +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() вставляет пару ключ-значение, только если такого ключа нет +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]) + +# Порядок сортировки не гарантируется, хотя иногда они выглядят отсортированными +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} + +# Пересечение множеств: & +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: # Это тоже необязательно. + print("some_var равно 10.") + + +""" +Циклы For проходят по спискам + +Результат: + собака — это млекопитающее + кошка — это млекопитающее + мышь — это млекопитающее +""" +for animal in ["собака", "кошка", "мышь"]: + # Можете использовать оператор % для интерполяции форматированных строк + print("%s — это млекопитающее" % animal) + +""" +«range(число)» возвращает список чисел +от нуля до заданного числа +Результат: + 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("Это ошибка индекса") +except IndexError as e: + # pass — это просто отсутствие оператора. Обычно здесь происходит + # восстановление после ошибки. + pass +except (TypeError, NameError): + pass # Несколько исключений можно обработать вместе, если нужно. +else: # Необязательное выражение. Должно следовать за последним блоком except + print("Всё хорошо!") # Выполнится, только если не было никаких исключений + + + +#################################################### +## 4. Функции +#################################################### + +# Используйте def для создания новых функций +def add(x, y): + print("x равен %s, а y равен %s" % (x, y)) + return x + y # Возвращайте результат с помощью ключевого слова return + +# Вызов функции с аргументами +add(5, 6) #=> выводит «x равен 5, а y равен 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) выводит: + (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) + +# вы можете передавать переменное число позиционных или именованных аргументов +# другим функциям, которые их принимают, распаковывая их с помощью +# * или ** соответственно +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Область определения функций +x = 5 + +def setX(num): + # Локальная переменная x — это не то же самое, что глобальная переменная x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # Глобальная переменная x теперь равна 6 + 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): + # Присваивание значения аргумента атрибуту класса 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="Иван") +print(i.say("привет")) # Выводит: «Иван: привет» + +j = Human("Пётр") +print(j.say("Привет")) # Выводит: «Пётр: привет» + +# Вызов метода класса +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 +# Вы также можете убедиться, что функции эквивалентны +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Модули в Python — это обычные Python-файлы. Вы +# можете писать свои модули и импортировать их. Название +# модуля совпадает с названием файла. + +# Вы можете узнать, какие функции и атрибуты определены +# в модуле +import math +dir(math) + +#################################################### +## 7. Дополнительно +#################################################### + +# Генераторы помогут выполнить ленивые вычисления +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Генератор создаёт значения на лету. +# Он не возвращает все значения разом, а создаёт каждое из них при каждой +# итерации. Это значит, что значения больше 15 в double_numbers +# обработаны не будут. +# Обратите внимание: xrange — это генератор, который делает то же, что и range. +# Создание списка чисел от 1 до 900000000 требует много места и времени. +# xrange создаёт объект генератора, а не список сразу, как это делает range. +# Если нам нужно имя переменной, совпадающее с ключевым словом Python, +# мы используем подчёркивание в конце +xrange_ = xrange(1, 900000000) + +# Будет удваивать все числа, пока результат не превысит 30 +for i in double_numbers(xrange_): + print(i) + if i >= 30: + break + + +# Декораторы +# В этом примере beg оборачивает say +# Метод beg вызовет say. Если say_please равно True, +# он изменит возвращаемое сообщение +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, " Пожалуйста! У меня нет денег :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Вы не купите мне пива?" + return msg, say_please + + +print(say()) # Вы не купите мне пива? +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/) +* [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) + +### Платные + +* [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/python-tr.html.markdown b/tr-tr/python-tr.html.markdown deleted file mode 100644 index 99a3eb4e..00000000 --- a/tr-tr/python-tr.html.markdown +++ /dev/null @@ -1,502 +0,0 @@ ---- -language: python -filename: learnpython-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/tr-tr/pythonlegacy-tr.html.markdown b/tr-tr/pythonlegacy-tr.html.markdown new file mode 100644 index 00000000..99a3eb4e --- /dev/null +++ b/tr-tr/pythonlegacy-tr.html.markdown @@ -0,0 +1,502 @@ +--- +language: python +filename: learnpython-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/python-ua.html.markdown deleted file mode 100644 index 4091e433..00000000 --- a/uk-ua/python-ua.html.markdown +++ /dev/null @@ -1,818 +0,0 @@ ---- -language: python -lang: uk-ua -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"] -translators: - - ["Oleh Hromiak", "https://github.com/ogroleg"] -filename: learnpython-ua.py ---- - -Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з -найбільш популярних мов. Я закохався у Python завдяки простому і зрозумілому -синтаксису. Це майже як виконуваний псевдокод. - -З вдячністю чекаю ваших відгуків: [@louiedinh](http://twitter.com/louiedinh) -або louiedinh [at] [поштовий сервіс від Google] - -Примітка: Ця стаття стосується Python 2.7, проте має працювати і -у інших версіях Python 2.x. Python 2.7 підходить до кінця свого терміну, -його підтримку припинять у 2020, тож наразі краще починати вивчення Python -з версії 3.x. -Аби вивчити Python 3.x, звертайтесь до статті по Python 3. - -```python -# Однорядкові коментарі починаються з символу решітки. - -""" Текст, що займає декілька рядків, - може бути записаний з використанням 3 знаків " і - зазвичай використовується у якості - вбудованої документації -""" - -#################################################### -## 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 ох... Так набагато краще - -# Результат цілочисельного ділення округлюється у меншу сторону -# як для додатніх, так і для від'ємних чисел. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # Працює і для чисел з плаваючою комою --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Зверніть увагу, що ми також можемо імпортувати модуль для ділення, -# див. розділ Модулі -# аби звичне ділення працювало при використанні лише '/'. -from __future__ import division - -11 / 4 # => 2.75 ...звичне ділення -11 // 4 # => 2 ...цілочисельне ділення - -# Залишок від ділення -7 % 3 # => 1 - -# Піднесення до степеня -2 ** 4 # => 16 - -# Приорітет операцій вказується дужками -(1 + 3) * 2 # => 8 - -# Логічні оператори -# Зверніть увагу: ключові слова «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 - -# Для заперечення використовується 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 - -# Рядки позначаються символом " або ' -"Це рядок." -'Це теж рядок.' - -# І рядки також можна додавати! -"Привіт " + "світ!" # => "Привіт світ!" -# Рядки можна додавати і без '+' -"Привіт " "світ!" # => "Привіт світ!" - -# ... або множити -"Привіт" * 3 # => "ПривітПривітПривіт" - -# З рядком можна працювати як зі списком символів -"Це рядок"[0] # => 'Ц' - -# Ви можете дізнатися довжину рядка -len("Це рядок") # => 8 - -# Символ % використовується для форматування рядків, наприклад: -"%s можуть бути %s" % ("рядки", "інтерпольовані") - -# Новий спосіб форматування рядків — використання методу format. -# Це бажаний спосіб. -"{} є {}".format("Це", "заповнювач") -"{0} можуть бути {1}".format("рядки", "форматовані") -# Якщо ви не хочете рахувати, то можете скористатися ключовими словами. -"{name} хоче з'істи {food}".format(name="Боб", food="лазанью") - -# None - це об'єкт -None # => None - -# Не використовуйте оператор рівності '=='' для порівняння -# об'єктів з None. Використовуйте для цього «is» -"etc" is None # => False -None is None # => True - -# Оператор 'is' перевіряє ідентичність об'єктів. Він не -# дуже корисний при роботі з примітивними типами, проте -# незамінний при роботі з об'єктами. - -# None, 0 і порожні рядки/списки рівні False. -# Всі інші значення рівні True -bool(0) # => False -bool("") # => False - - -#################################################### -## 2. Змінні та колекції -#################################################### - -# В Python є оператор print -print "Я Python. Приємно познайомитись!" # => Я Python. Приємно познайомитись! - -# Отримати дані з консолі просто -input_string_var = raw_input( - "Введіть щось: ") # Повертає дані у вигляді рядка -input_var = input("Введіть щось: ") # Працює з даними як з кодом на python -# Застереження: будьте обережні при використанні методу input() - -# Оголошувати змінні перед ініціалізацією не потрібно. -some_var = 5 # За угодою використовується нижній_регістр_з_підкресленнями -some_var # => 5 - -# При спробі доступу до неініціалізованої змінної -# виникне виняткова ситуація. -# Див. розділ Потік управління, аби дізнатись про винятки більше. -some_other_var # Помилка в імені - -# if може використовуватися як вираз -# Такий запис еквівалентний тернарному оператору '?:' у мові С -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Списки зберігають послідовності -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] -# Повернемо елемент назад -li.append(3) # li тепер знову дорівнює [1, 2, 4, 3] - -# Поводьтесь зі списком як зі звичайним масивом -li[0] # => 1 -# Присвоюйте нові значення вже ініціалізованим індексам за допомогою = -li[0] = 42 -li[0] # => 42 -li[0] = 1 # Зверніть увагу: повертаємось до попереднього значення -# Звертаємось до останнього елементу -li[-1] # => 3 - -# Спроба вийти за границі масиву призводить до помилки в індексі -li[4] # помилка в індексі - -# Можна звертатися до діапазону, використовуючи так звані зрізи -# (Для тих, хто любить математику: це називається замкнуто-відкритий інтервал). -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 тепер [1, 2, 3] - -# Ви можете додавати списки -li + other_li # => [1, 2, 3, 4, 5, 6] -# Зверніть увагу: значення li та other_li при цьому не змінились. - -# Поєднувати списки можна за допомогою методу extend -li.extend(other_li) # Тепер li дорівнює [1, 2, 3, 4, 5, 6] - -# Видалити перше входження значення -li.remove(2) # Тепер li дорівнює [1, 3, 4, 5, 6] -li.remove(2) # Помилка значення, оскільки у списку li немає 2 - -# Вставити елемент за вказаним індексом -li.insert(1, 2) # li знову дорівнює [1, 2, 3, 4, 5, 6] - -# Отримати індекс першого знайденого елементу -li.index(2) # => 1 -li.index(7) # Помилка значення, оскільки у списку li немає 7 - -# Перевірити елемент на входження у список можна оператором in -1 in li # => True - -# Довжина списку обчислюється за допомогою функції 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 -d, e, f = 4, 5, 6 # дужки можна опустити -# Кортежі створюються за замовчуванням, якщо дужки опущено -g = 4, 5, 6 # => (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 -filled_dict.keys() # => ["three", "two", "one"] -# Примітка: збереження порядку ключів у словників не гарантується -# Ваші результати можуть не співпадати з цими. - -# Можна отримати і всі значення у вигляді списку, використовуйте метод values -filled_dict.values() # => [3, 2, 1] -# Те ж зауваження щодо порядку ключів діє і тут - -# Отримуйте всі пари ключ-значення у вигляді списку кортежів -# за допомогою "items()" -filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] - -# За допомогою оператору in можна перевіряти ключі на входження у словник -"one" in filled_dict # => True -1 in filled_dict # => False - -# Спроба отримати значення за неіснуючим ключем викине помилку ключа -filled_dict["four"] # помилка ключа - -# Аби уникнути цього, використовуйте метод get() -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# Метод get також приймає аргумент за замовчуванням, значення якого буде -# повернуто при відсутності вказаного ключа -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() вставляє пару ключ-значення лише -# за відсутності такого ключа -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]) - -# Порядок не гарантовано, хоча інколи множини виглядають відсортованими -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} - -# Перетин множин: & -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} - -# Симетрична різниця множин: ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Перевіряємо чи множина зліва є надмножиною множини справа -{1, 2} >= {1, 2, 3} # => False - -# Перевіряємо чи множина зліва є підмножиною множини справа -{1, 2} <= {1, 2, 3} # => True - -# Перевірка на входження у множину: 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: # Це теж необов'язково. - print("some_var дорівнює 10.") - - -""" -Цикли For проходять по спискам - -Результат: - собака — це ссавець - кішка — це ссавець - миша — це ссавець -""" -for animal in ["собака", "кішка", "миша"]: - # Можете використовувати оператор {0} для інтерполяції форматованих рядків - print "{0} — це ссавець".format(animal) - -""" -"range(число)" повертає список чисел -від нуля до заданого числа -Друкує: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) -""" -"range(нижня_границя, верхня_границя)" повертає список чисел -від нижньої границі до верхньої -Друкує: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - 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("Помилка у індексі!") -except IndexError as e: - pass # pass — оператор, який нічого не робить. Зазвичай тут відбувається - # відновлення після помилки. -except (TypeError, NameError): - pass # Винятки можна обробляти групами, якщо потрібно. -else: # Необов'язковий вираз. Має слідувати за останнім блоком except - print("Все добре!") # Виконається лише якщо не було ніяких винятків -finally: # Виконується у будь-якому випадку - print "Тут ми можемо звільнити ресурси" - -# Замість try/finally для звільнення ресурсів -# ви можете використовувати вираз with -with open("myfile.txt") as f: - for line in f: - print line - - -#################################################### -## 4. Функції -#################################################### - -# Використовуйте def для створення нових функцій -def add(x, y): - print "x дорівнює {0}, а y дорівнює {1}".format(x, y) - return x + y # Повертайте результат за допомогою ключового слова return - - -# Виклик функції з аргументами -add(5, 6) # => друкує «x дорівнює 5, а y дорівнює 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) друкує: - (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) - -# ви можете передавати довільне число позиційних або іменованих аргументів -# іншим функціям, які їх приймають, розпаковуючи за допомогою -# * або ** відповідно -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - - -# Область визначення функцій -x = 5 - - -def set_x(num): - # Локальна змінна x - не те ж саме, що глобальна змінна x - x = num # => 43 - print x # => 43 - - -def set_global_x(num): - global x - print x # => 5 - x = num # глобальна змінна x тепер дорівнює 6 - print x # => 6 - - -set_x(43) -set_global_x(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 -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Присутні вбудовані функції вищого порядку -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] - -# Для зручного відображення і фільтрації можна використовувати -# включення у вигляді списків -[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 '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. Класи -#################################################### - -# Аби отримати клас, ми наслідуємо object. -class Human(object): - # Атрибут класу. Він розділяється всіма екземплярами цього класу. - species = "H. sapiens" - - # Звичайний конструктор, буде викликаний при ініціалізації екземпляру класу - # Зверніть увагу, що подвійне підкреслення на початку та наприкінці імені - # використовується для позначення об'єктів та атрибутів, - # які використовуються Python, але знаходяться у просторах імен, - # якими керує користувач. Не варто вигадувати для них імена самостійно. - def __init__(self, name): - # Присвоєння значення аргумента атрибуту класу name - self.name = name - - # Ініціалізуємо властивість - self.age = 0 - - # Метод екземпляру. Всі методи приймають self у якості першого аргументу - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # Методи класу розділяються між усіма екземплярами - # Вони викликаються з вказанням викликаючого класу - # у якості першого аргументу - @classmethod - def get_species(cls): - return cls.species - - # Статичний метод викликається без посилання на клас або екземпляр - @staticmethod - def grunt(): - return "*grunt*" - - # Властивість. - # Перетворює метод age() в атрибут тільки для читання - # з таким же ім'ям. - @property - def age(self): - return self._age - - # Це дозволяє змінювати значення властивості - @age.setter - def age(self, age): - self._age = age - - # Це дозволяє видаляти властивість - @age.deleter - def age(self): - del self._age - - -# Створюємо екземпляр класу -i = Human(name="Данило") -print(i.say("привіт")) # Друкує: «Данило: привіт» - -j = Human("Меланка") -print(j.say("Привіт")) # Друкує: «Меланка: привіт» - -# Виклик методу класу -i.get_species() # => "H. sapiens" - -# Зміна розділюваного атрибуту -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Виклик статичного методу -Human.grunt() # => "*grunt*" - -# Оновлюємо властивість -i.age = 42 - -# Отримуємо значення -i.age # => 42 - -# Видаляємо властивість -del i.age -i.age # => виникає помилка атрибуту - -#################################################### -## 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 -# Ви також можете переконатися, що функції еквівалентні -from math import sqrt - -math.sqrt == m.sqrt == sqrt # => True - -# Модулі в Python — це звичайні Python-файли. Ви -# можете писати свої модулі та імпортувати їх. Назва -# модуля співпадає з назвою файлу. - -# Ви можете дізнатися, які функції та атрибути визначені -# в модулі -import math - -dir(math) - - -# Якщо у вас є Python скрипт з назвою math.py у тій же папці, що -# і ваш поточний скрипт, то файл math.py -# може бути завантажено замість вбудованого у Python модуля. -# Так трапляється, оскільки локальна папка має перевагу -# над вбудованими у Python бібліотеками. - -#################################################### -## 7. Додатково -#################################################### - -# Генератори -# Генератор "генерує" значення тоді, коли вони запитуються, замість того, -# щоб зберігати все одразу - -# Метод нижче (*НЕ* генератор) подвоює всі значення і зберігає їх -# в `double_arr`. При великих розмірах може знадобитися багато ресурсів! -def double_numbers(iterable): - double_arr = [] - for i in iterable: - double_arr.append(i + i) - return double_arr - - -# Тут ми спочатку подвоюємо всі значення, потім повертаємо їх, -# аби перевірити умову -for value in double_numbers(range(1000000)): # `test_non_generator` - print value - if value > 5: - break - - -# Натомість ми можемо скористатися генератором, аби "згенерувати" -# подвійне значення, як тільки воно буде запитане -def double_numbers_generator(iterable): - for i in iterable: - yield i + i - - -# Той самий код, але вже з генератором, тепер дозволяє нам пройтися по -# значенням і подвоювати їх одне за одним якраз тоді, коли вони обробляються -# за нашою логікою, одне за одним. А як тільки ми бачимо, що value > 5, ми -# виходимо з циклу і більше не подвоюємо більшість значень, -# які отримали на вхід (НАБАГАТО ШВИДШЕ!) -for value in double_numbers_generator(xrange(1000000)): # `test_generator` - print value - if value > 5: - break - -# Між іншим: ви помітили використання `range` у `test_non_generator` і -# `xrange` у `test_generator`? -# Як `double_numbers_generator` є версією-генератором `double_numbers`, так -# і `xrange` є аналогом `range`, але у вигляді генератора. -# `range` поверне нам масив з 1000000 значень -# `xrange`, у свою чергу, згенерує 1000000 значень для нас тоді, -# коли ми їх запитуємо / будемо проходитись по ним. - -# Аналогічно включенням у вигляді списків, ви можете створювати включення -# у вигляді генераторів. -values = (-x for x in [1, 2, 3, 4, 5]) -for x in values: - print(x) # друкує -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] - -# Декоратори -# Декоратор – це функція вищого порядку, яка приймає та повертає функцію. -# Простий приклад використання – декоратор add_apples додає елемент 'Apple' в -# список fruits, який повертає цільова функція get_fruits. -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'] - -# Друкуємо список разом з елементом 'Apple', який знаходиться в ньому: -# Banana, Mango, Orange, Apple -print ', '.join(get_fruits()) - -# У цьому прикладі beg обертає say -# Beg викличе say. Якщо say_please дорівнюватиме True, то повідомлення, -# що повертається, буде змінено. -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, "Будь ласка! Я бідний :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Ви можете купити мені пива?" - return msg, say_please - - -print say() # Ви можете купити мені пива? -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/) -* [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) - -### Платні - -* [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/pythonlegacy-ua.html.markdown b/uk-ua/pythonlegacy-ua.html.markdown new file mode 100644 index 00000000..4091e433 --- /dev/null +++ b/uk-ua/pythonlegacy-ua.html.markdown @@ -0,0 +1,818 @@ +--- +language: python +lang: uk-ua +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"] +translators: + - ["Oleh Hromiak", "https://github.com/ogroleg"] +filename: learnpython-ua.py +--- + +Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з +найбільш популярних мов. Я закохався у Python завдяки простому і зрозумілому +синтаксису. Це майже як виконуваний псевдокод. + +З вдячністю чекаю ваших відгуків: [@louiedinh](http://twitter.com/louiedinh) +або louiedinh [at] [поштовий сервіс від Google] + +Примітка: Ця стаття стосується Python 2.7, проте має працювати і +у інших версіях Python 2.x. Python 2.7 підходить до кінця свого терміну, +його підтримку припинять у 2020, тож наразі краще починати вивчення Python +з версії 3.x. +Аби вивчити Python 3.x, звертайтесь до статті по Python 3. + +```python +# Однорядкові коментарі починаються з символу решітки. + +""" Текст, що займає декілька рядків, + може бути записаний з використанням 3 знаків " і + зазвичай використовується у якості + вбудованої документації +""" + +#################################################### +## 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 ох... Так набагато краще + +# Результат цілочисельного ділення округлюється у меншу сторону +# як для додатніх, так і для від'ємних чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # Працює і для чисел з плаваючою комою +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Зверніть увагу, що ми також можемо імпортувати модуль для ділення, +# див. розділ Модулі +# аби звичне ділення працювало при використанні лише '/'. +from __future__ import division + +11 / 4 # => 2.75 ...звичне ділення +11 // 4 # => 2 ...цілочисельне ділення + +# Залишок від ділення +7 % 3 # => 1 + +# Піднесення до степеня +2 ** 4 # => 16 + +# Приорітет операцій вказується дужками +(1 + 3) * 2 # => 8 + +# Логічні оператори +# Зверніть увагу: ключові слова «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 + +# Для заперечення використовується 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 + +# Рядки позначаються символом " або ' +"Це рядок." +'Це теж рядок.' + +# І рядки також можна додавати! +"Привіт " + "світ!" # => "Привіт світ!" +# Рядки можна додавати і без '+' +"Привіт " "світ!" # => "Привіт світ!" + +# ... або множити +"Привіт" * 3 # => "ПривітПривітПривіт" + +# З рядком можна працювати як зі списком символів +"Це рядок"[0] # => 'Ц' + +# Ви можете дізнатися довжину рядка +len("Це рядок") # => 8 + +# Символ % використовується для форматування рядків, наприклад: +"%s можуть бути %s" % ("рядки", "інтерпольовані") + +# Новий спосіб форматування рядків — використання методу format. +# Це бажаний спосіб. +"{} є {}".format("Це", "заповнювач") +"{0} можуть бути {1}".format("рядки", "форматовані") +# Якщо ви не хочете рахувати, то можете скористатися ключовими словами. +"{name} хоче з'істи {food}".format(name="Боб", food="лазанью") + +# None - це об'єкт +None # => None + +# Не використовуйте оператор рівності '=='' для порівняння +# об'єктів з None. Використовуйте для цього «is» +"etc" is None # => False +None is None # => True + +# Оператор 'is' перевіряє ідентичність об'єктів. Він не +# дуже корисний при роботі з примітивними типами, проте +# незамінний при роботі з об'єктами. + +# None, 0 і порожні рядки/списки рівні False. +# Всі інші значення рівні True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Змінні та колекції +#################################################### + +# В Python є оператор print +print "Я Python. Приємно познайомитись!" # => Я Python. Приємно познайомитись! + +# Отримати дані з консолі просто +input_string_var = raw_input( + "Введіть щось: ") # Повертає дані у вигляді рядка +input_var = input("Введіть щось: ") # Працює з даними як з кодом на python +# Застереження: будьте обережні при використанні методу input() + +# Оголошувати змінні перед ініціалізацією не потрібно. +some_var = 5 # За угодою використовується нижній_регістр_з_підкресленнями +some_var # => 5 + +# При спробі доступу до неініціалізованої змінної +# виникне виняткова ситуація. +# Див. розділ Потік управління, аби дізнатись про винятки більше. +some_other_var # Помилка в імені + +# if може використовуватися як вираз +# Такий запис еквівалентний тернарному оператору '?:' у мові С +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Списки зберігають послідовності +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] +# Повернемо елемент назад +li.append(3) # li тепер знову дорівнює [1, 2, 4, 3] + +# Поводьтесь зі списком як зі звичайним масивом +li[0] # => 1 +# Присвоюйте нові значення вже ініціалізованим індексам за допомогою = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Зверніть увагу: повертаємось до попереднього значення +# Звертаємось до останнього елементу +li[-1] # => 3 + +# Спроба вийти за границі масиву призводить до помилки в індексі +li[4] # помилка в індексі + +# Можна звертатися до діапазону, використовуючи так звані зрізи +# (Для тих, хто любить математику: це називається замкнуто-відкритий інтервал). +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 тепер [1, 2, 3] + +# Ви можете додавати списки +li + other_li # => [1, 2, 3, 4, 5, 6] +# Зверніть увагу: значення li та other_li при цьому не змінились. + +# Поєднувати списки можна за допомогою методу extend +li.extend(other_li) # Тепер li дорівнює [1, 2, 3, 4, 5, 6] + +# Видалити перше входження значення +li.remove(2) # Тепер li дорівнює [1, 3, 4, 5, 6] +li.remove(2) # Помилка значення, оскільки у списку li немає 2 + +# Вставити елемент за вказаним індексом +li.insert(1, 2) # li знову дорівнює [1, 2, 3, 4, 5, 6] + +# Отримати індекс першого знайденого елементу +li.index(2) # => 1 +li.index(7) # Помилка значення, оскільки у списку li немає 7 + +# Перевірити елемент на входження у список можна оператором in +1 in li # => True + +# Довжина списку обчислюється за допомогою функції 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 +d, e, f = 4, 5, 6 # дужки можна опустити +# Кортежі створюються за замовчуванням, якщо дужки опущено +g = 4, 5, 6 # => (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 +filled_dict.keys() # => ["three", "two", "one"] +# Примітка: збереження порядку ключів у словників не гарантується +# Ваші результати можуть не співпадати з цими. + +# Можна отримати і всі значення у вигляді списку, використовуйте метод values +filled_dict.values() # => [3, 2, 1] +# Те ж зауваження щодо порядку ключів діє і тут + +# Отримуйте всі пари ключ-значення у вигляді списку кортежів +# за допомогою "items()" +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# За допомогою оператору in можна перевіряти ключі на входження у словник +"one" in filled_dict # => True +1 in filled_dict # => False + +# Спроба отримати значення за неіснуючим ключем викине помилку ключа +filled_dict["four"] # помилка ключа + +# Аби уникнути цього, використовуйте метод get() +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# Метод get також приймає аргумент за замовчуванням, значення якого буде +# повернуто при відсутності вказаного ключа +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() вставляє пару ключ-значення лише +# за відсутності такого ключа +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]) + +# Порядок не гарантовано, хоча інколи множини виглядають відсортованими +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} + +# Перетин множин: & +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} + +# Симетрична різниця множин: ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Перевіряємо чи множина зліва є надмножиною множини справа +{1, 2} >= {1, 2, 3} # => False + +# Перевіряємо чи множина зліва є підмножиною множини справа +{1, 2} <= {1, 2, 3} # => True + +# Перевірка на входження у множину: 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: # Це теж необов'язково. + print("some_var дорівнює 10.") + + +""" +Цикли For проходять по спискам + +Результат: + собака — це ссавець + кішка — це ссавець + миша — це ссавець +""" +for animal in ["собака", "кішка", "миша"]: + # Можете використовувати оператор {0} для інтерполяції форматованих рядків + print "{0} — це ссавець".format(animal) + +""" +"range(число)" повертає список чисел +від нуля до заданого числа +Друкує: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) +""" +"range(нижня_границя, верхня_границя)" повертає список чисел +від нижньої границі до верхньої +Друкує: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + 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("Помилка у індексі!") +except IndexError as e: + pass # pass — оператор, який нічого не робить. Зазвичай тут відбувається + # відновлення після помилки. +except (TypeError, NameError): + pass # Винятки можна обробляти групами, якщо потрібно. +else: # Необов'язковий вираз. Має слідувати за останнім блоком except + print("Все добре!") # Виконається лише якщо не було ніяких винятків +finally: # Виконується у будь-якому випадку + print "Тут ми можемо звільнити ресурси" + +# Замість try/finally для звільнення ресурсів +# ви можете використовувати вираз with +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +## 4. Функції +#################################################### + +# Використовуйте def для створення нових функцій +def add(x, y): + print "x дорівнює {0}, а y дорівнює {1}".format(x, y) + return x + y # Повертайте результат за допомогою ключового слова return + + +# Виклик функції з аргументами +add(5, 6) # => друкує «x дорівнює 5, а y дорівнює 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) друкує: + (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) + +# ви можете передавати довільне число позиційних або іменованих аргументів +# іншим функціям, які їх приймають, розпаковуючи за допомогою +# * або ** відповідно +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Область визначення функцій +x = 5 + + +def set_x(num): + # Локальна змінна x - не те ж саме, що глобальна змінна x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # глобальна змінна x тепер дорівнює 6 + print x # => 6 + + +set_x(43) +set_global_x(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 +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Присутні вбудовані функції вищого порядку +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] + +# Для зручного відображення і фільтрації можна використовувати +# включення у вигляді списків +[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 '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. Класи +#################################################### + +# Аби отримати клас, ми наслідуємо object. +class Human(object): + # Атрибут класу. Він розділяється всіма екземплярами цього класу. + species = "H. sapiens" + + # Звичайний конструктор, буде викликаний при ініціалізації екземпляру класу + # Зверніть увагу, що подвійне підкреслення на початку та наприкінці імені + # використовується для позначення об'єктів та атрибутів, + # які використовуються Python, але знаходяться у просторах імен, + # якими керує користувач. Не варто вигадувати для них імена самостійно. + def __init__(self, name): + # Присвоєння значення аргумента атрибуту класу name + self.name = name + + # Ініціалізуємо властивість + self.age = 0 + + # Метод екземпляру. Всі методи приймають self у якості першого аргументу + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Методи класу розділяються між усіма екземплярами + # Вони викликаються з вказанням викликаючого класу + # у якості першого аргументу + @classmethod + def get_species(cls): + return cls.species + + # Статичний метод викликається без посилання на клас або екземпляр + @staticmethod + def grunt(): + return "*grunt*" + + # Властивість. + # Перетворює метод age() в атрибут тільки для читання + # з таким же ім'ям. + @property + def age(self): + return self._age + + # Це дозволяє змінювати значення властивості + @age.setter + def age(self, age): + self._age = age + + # Це дозволяє видаляти властивість + @age.deleter + def age(self): + del self._age + + +# Створюємо екземпляр класу +i = Human(name="Данило") +print(i.say("привіт")) # Друкує: «Данило: привіт» + +j = Human("Меланка") +print(j.say("Привіт")) # Друкує: «Меланка: привіт» + +# Виклик методу класу +i.get_species() # => "H. sapiens" + +# Зміна розділюваного атрибуту +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Виклик статичного методу +Human.grunt() # => "*grunt*" + +# Оновлюємо властивість +i.age = 42 + +# Отримуємо значення +i.age # => 42 + +# Видаляємо властивість +del i.age +i.age # => виникає помилка атрибуту + +#################################################### +## 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 +# Ви також можете переконатися, що функції еквівалентні +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# Модулі в Python — це звичайні Python-файли. Ви +# можете писати свої модулі та імпортувати їх. Назва +# модуля співпадає з назвою файлу. + +# Ви можете дізнатися, які функції та атрибути визначені +# в модулі +import math + +dir(math) + + +# Якщо у вас є Python скрипт з назвою math.py у тій же папці, що +# і ваш поточний скрипт, то файл math.py +# може бути завантажено замість вбудованого у Python модуля. +# Так трапляється, оскільки локальна папка має перевагу +# над вбудованими у Python бібліотеками. + +#################################################### +## 7. Додатково +#################################################### + +# Генератори +# Генератор "генерує" значення тоді, коли вони запитуються, замість того, +# щоб зберігати все одразу + +# Метод нижче (*НЕ* генератор) подвоює всі значення і зберігає їх +# в `double_arr`. При великих розмірах може знадобитися багато ресурсів! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# Тут ми спочатку подвоюємо всі значення, потім повертаємо їх, +# аби перевірити умову +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Натомість ми можемо скористатися генератором, аби "згенерувати" +# подвійне значення, як тільки воно буде запитане +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# Той самий код, але вже з генератором, тепер дозволяє нам пройтися по +# значенням і подвоювати їх одне за одним якраз тоді, коли вони обробляються +# за нашою логікою, одне за одним. А як тільки ми бачимо, що value > 5, ми +# виходимо з циклу і більше не подвоюємо більшість значень, +# які отримали на вхід (НАБАГАТО ШВИДШЕ!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Між іншим: ви помітили використання `range` у `test_non_generator` і +# `xrange` у `test_generator`? +# Як `double_numbers_generator` є версією-генератором `double_numbers`, так +# і `xrange` є аналогом `range`, але у вигляді генератора. +# `range` поверне нам масив з 1000000 значень +# `xrange`, у свою чергу, згенерує 1000000 значень для нас тоді, +# коли ми їх запитуємо / будемо проходитись по ним. + +# Аналогічно включенням у вигляді списків, ви можете створювати включення +# у вигляді генераторів. +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # друкує -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] + +# Декоратори +# Декоратор – це функція вищого порядку, яка приймає та повертає функцію. +# Простий приклад використання – декоратор add_apples додає елемент 'Apple' в +# список fruits, який повертає цільова функція get_fruits. +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'] + +# Друкуємо список разом з елементом 'Apple', який знаходиться в ньому: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# У цьому прикладі beg обертає say +# Beg викличе say. Якщо say_please дорівнюватиме True, то повідомлення, +# що повертається, буде змінено. +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, "Будь ласка! Я бідний :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Ви можете купити мені пива?" + return msg, say_please + + +print say() # Ви можете купити мені пива? +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/) +* [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) + +### Платні + +* [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/python-cn.html.markdown b/zh-cn/python-cn.html.markdown deleted file mode 100644 index 65f125d1..00000000 --- a/zh-cn/python-cn.html.markdown +++ /dev/null @@ -1,476 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Chenbo Li", "http://binarythink.net"] -filename: learnpython-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-cn/pythonlegacy-cn.html.markdown b/zh-cn/pythonlegacy-cn.html.markdown new file mode 100644 index 00000000..65f125d1 --- /dev/null +++ b/zh-cn/pythonlegacy-cn.html.markdown @@ -0,0 +1,476 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +filename: learnpython-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/python-tw.html.markdown deleted file mode 100644 index cd7481d7..00000000 --- a/zh-tw/python-tw.html.markdown +++ /dev/null @@ -1,727 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Amin Bandali", "http://aminbandali.com"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["evuez", "http://github.com/evuez"] -translators: - - ["Michael Yeh", "https://hinet60613.github.io/"] -filename: learnpython-tw.py -lang: zh-tw ---- - -Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。 - -非常歡迎各位給我們任何回饋! 你可以在[@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 2.7和3.X是可以做到的,只要引入 - [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組. - `__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼,詳細訊息請參考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 精確多了! - -# 整數除法的無條件捨去對正數或負數都適用 -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # 浮點數的整數也適用 --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# 我們可以用除法模組(參考第六節:模組),讓 -# 單一斜線代表普通除法,而非無條件捨去 -from __future__ import division -11/4 # => 2.75 ...普通除法 -11//4 # => 2 ...無條件捨去 - -# 取餘數 -7 % 3 # => 1 - -# 指數 (x的y次方) -2**4 # => 16 - -# 用括號改變運算順序 -(1 + 3) * 2 # => 8 - -# 布林運算 -# 注意 "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 - -# 用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!" -# 不用加號也可以做字串相加 -"Hello " "world!" # => "Hello world!" - -# ... 也可以做相乘 -"Hello" * 3 # => "HelloHelloHello" - -# 字串可以被視為字元的陣列 -"This is a string"[0] # => 'T' - -# 字串的格式化可以用百分之符號 % -# 儘管在Python 3.1後這個功能被廢棄了,並且在 -# 之後的版本會被移除,但還是可以了解一下 -x = 'apple' -y = 'lemon' -z = "The items in the basket are %s and %s" % (x,y) - -# 新的格式化方式是使用format函式 -# 這個方式也是較為推薦的 -"{} is a {}".format("This", "placeholder") -"{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' 運算元是用來識別物件的。對原始型別來說或許沒什麼用, -# 但對物件來說是很有用的。 - -# 任何物件都可以被當作布林值使用 -# 以下的值會被視為是False : -# - 無(None) -# - 任何型別的零 (例如: 0, 0L, 0.0, 0j) -# - 空序列 (例如: '', (), []) -# - 空容器 (例如: {}, set()) -# - 自定義型別的實體,且滿足某些條件 -# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ -# -# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值). -bool(0) # => False -bool("") # => False - - -#################################################### -## 2. 變數與集合 -#################################################### - -# Python的輸出很方便 -print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! - -# 從命令列獲得值也很方便 -input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數 -input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行 -# 注意: 請謹慎使用input()函式 -# 註: 在Python 3中,input()已被棄用,raw_input()已被更名為input() - -# 使用變數前不需要先宣告 -some_var = 5 # 方便好用 -lower_case_with_underscores -some_var # => 5 - -# 對沒有被賦值的變數取值會造成例外 -# 請參考錯誤流程部分做例外處理 -some_other_var # 造成 NameError - -# if可以當判斷式使用 -# 相當於C語言中的二元判斷式 -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# 串列型態可以儲存集合 -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] -# 然後再塞回去 -li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3] - -# 你可以像存取陣列一樣的存取串列 -li[0] # => 1 -# 用等號 = 給串列中特定索引的元素賦值 -li[0] = 42 -li[0] # => 42 -li[0] = 1 # 註: 將其設定回原本的值 -# 用 -1 索引值查看串列最後一個元素 -li[-1] # => 3 - -# 存取超過範圍會產生IndexError -li[4] # Raises an 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 內容為 [1, 2, 3] - -# 你可以做串列相加 -li + other_li # => [1, 2, 3, 4, 5, 6] -# 註: li 及 other_li 沒有被更動 - -# 用 "extend()" 做串列串接 -li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6] - -# 移除特定值的第一次出現 -li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6] -li.remove(2) # 2 不在串列中,造成 ValueError - -# 在特定位置插入值 -li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6] - -# 取得特定值在串列中第一次出現的位置 -li.index(2) # => 1 -li.index(7) # 7 不在串列中,造成 ValueError - -# 用 "in" 檢查特定值是否出現在串列中 -1 in li # => True - -# 用 "len()" 取得串列長度 -len(li) # => 6 - - -# 元組(Tuple,以下仍用原文)類似於串列,但是它是不可改變的 -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # 產生TypeError - -# 能對串列做的東西都可以對tuple做 -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# 你可以把tuple拆開並分別將值存入不同變數 -a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3 -d, e, f = 4, 5, 6 # 也可以不寫括號 -# 如果不加括號,預設會產生tuple -g = 4, 5, 6 # => (4, 5, 6) -# 你看,交換兩個值很簡單吧 -e, d = d, e # 此時 d 的值為 5 且 e 的值為 4 - - -# 字典(Dictionary)用來儲存映射關係 -empty_dict = {} -# 你可以對字典做初始化 -filled_dict = {"one": 1, "two": 2, "three": 3} - -# 用 [] 取值 -filled_dict["one"] # => 1 - -# 用 "keys()" 將所有的Key輸出到一個List中 -filled_dict.keys() # => ["three", "two", "one"] -# 註: 字典裡key的排序是不固定的 -# 你的執行結果可能與上面不同 -# 譯註: 只能保證所有的key都有出現,但不保證順序 - -# 用 "values()" 將所有的Value輸出到一個List中 -filled_dict.values() # => [3, 2, 1] -# 註: 同上,不保證順序 - -# 用 "in" 來檢查指定的Key是否在字典中 -"one" in filled_dict # => True -1 in filled_dict # => False - -# 查詢不存在的Key會造成KeyError -filled_dict["four"] # KeyError - -# 用 "get()" 來避免KeyError -# 若指定的Key不存在的話會得到None -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# "get()" 函式支援預設值,當找不到指定的值時,會回傳指定的預設值 -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 -# 注意此時 filled_dict.get("four") 仍然為 None -# (get()此時並沒有產生出任何的值) - -# 像操作list一樣,對指定的Key賦值 -filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4 - -# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary -filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5 - - -# 集合(Set)被用來儲存...集合。 -# 跟串列(List)有點像,但集合內不會有重複的元素 -empty_set = set() -# 初始化 "set()" 並給定一些值 -some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入 - -# 一樣,不保證順序,就算真的有照順序排也只是你運氣好 -another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4]) - -# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# 加入更多元素進入Set -filled_set.add(5) # filled_set is now {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} - -# 用 ^ 來對兩個集合取差集 -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# 檢查左邊是否為右邊的母集 -{1, 2} >= {1, 2, 3} # => False - -# 檢查左邊是否為右邊的子集 -{1, 2} <= {1, 2, 3} # => True - -# 用 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 迴圈會遞迴整的List -下面的程式碼會輸出: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # 你可以用{0}來組合0出格式化字串 (見上面.) - print "{0} is a mammal".format(animal) - -""" -"range(number)" 回傳一個包含從0到給定值的數字List, -下面的程式碼會輸出: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -"range(lower, upper)" 回傳一個包含從給定的下限 -到給定的上限的數字List -下面的程式碼會輸出: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - 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。通常這邊會讓你做對例外的處理 -except (TypeError, NameError): - pass # 有需要的話,多種例外可以一起處理 -else: # else 可有可無,但必須寫在所有的except後 - print "All good!" # 只有在try的時候沒有產生任何except才會被執行 -finally: # 不管什麼情況下一定會被執行 - print "We can clean up resources here" - -# 除了try/finally以外,你可以用 with 來簡單的處理清理動作 -with open("myfile.txt") as f: - for line in f: - print line - -#################################################### -## 4. 函式 -#################################################### - -# 用 "def" 來建立新函式 -def add(x, y): - print "x is {0} and y is {1}".format(x, y) - return x + y # 用 "return" 來回傳值 - -# 用參數來呼叫函式 -add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 - -# 你也可以寫上參數名稱來呼叫函式 -add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行 - - -# 你可以定義接受多個變數的函式,用*來表示參數tuple -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# 你可以定義接受多個變數的函式,用**來表示參數dictionary -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} -""" - -# 呼叫函式時,你可以做反向的操作 -# 用 * 將變數展開為順序排序的變數 -# 用 ** 將變數展開為Keyword排序的變數 -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) - -# 你可以把args跟kwargs傳到下一個函式內 -# 分別用 * 跟 ** 將它展開就可以了 -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - -# 函式範圍 -x = 5 - -def set_x(num): - # 區域變數 x 和全域變數 x 不是同一個東西 - x = num # => 43 - print x # => 43 - -def set_global_x(num): - global x - print x # => 5 - x = num # 全域變數 x 在set_global_x(6)被設定為 6 - print x # => 6 - -set_x(43) -set_global_x(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 -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# 還有內建的高階函式 -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] - -# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用 -[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" - - # 基礎建構函式,當class被實體化的時候會被呼叫 - # 注意前後的雙底線 - # 代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 - def __init__(self, name): - # 將函式引入的參數 name 指定給實體的 name 參數 - self.name = name - - # 初始化屬性 - self.age = 0 - - - # 一個實體的方法(method)。 所有的method都以self為第一個參數 - def say(self, msg): - return "{0}: {1}".format(self.name, msg) - - # 一個類別方法會被所有的實體所共用 - # 他們會以類別為第一參數的方式被呼叫 - @classmethod - def get_species(cls): - return cls.species - - # 靜態方法 - @staticmethod - def grunt(): - return "*grunt*" - - # 屬性就像是用getter取值一樣 - # 它將方法 age() 轉為同名的、只能讀取的屬性 - @property - def age(self): - return self._age - - # 這樣寫的話可以讓屬性被寫入新的值 - @age.setter - def age(self, age): - self._age = age - - # 這樣寫的話允許屬性被刪除 - @age.deleter - def age(self): - del self._age - - -# 將類別實體化 -i = Human(name="Ian") -print i.say("hi") # prints out "Ian: hi" - -j = Human("Joel") -print j.say("hello") # prints out "Joel: hello" - -# 呼叫類別方法 -i.get_species() # => "H. sapiens" - -# 更改共用的屬性 -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# 呼叫靜態方法 -Human.grunt() # => "*grunt*" - -# 更新屬性 -i.age = 42 - -# 取得屬性 -i.age # => 42 - -# 移除屬性 -del i.age -i.age # => raises an AttributeError - - -#################################################### -## 6. 模組 -#################################################### - -# 你可以引入模組來做使用 -import math -print math.sqrt(16) # => 4.0 - # math.sqrt()為取根號 - -# 你可以只從模組取出特定幾個函式 -from math import ceil, floor -print ceil(3.7) # => 4.0 -print floor(3.7) # => 3.0 - -# 你可以將所有的函式從模組中引入 -# 注意:不建議這麼做 -from math import * - -# 你可以用 as 簡寫模組名稱 -import math as m -math.sqrt(16) == m.sqrt(16) # => True -# 你也可以測試函示是否相等 -from math import sqrt -math.sqrt == m.sqrt == sqrt # => True - -# Python的模組就只是一般的Python檔。 -# 你可以自己的模組自己寫、自己的模組自己引入 -# 模組的名稱和檔案名稱一樣 - -# 你可以用dir()來查看有哪些可用函式和屬性 -import math -dir(math) - - -#################################################### -## 7. 進階 -#################################################### - -# 產生器(Generator)可以讓你寫更懶惰的程式碼 -def double_numbers(iterable): - for i in iterable: - yield i + i - -# 產生器可以讓你即時的產生值 -# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時 -# 產生值。 這也意味著大於15的值不會在double_numbers中產生。 -# 這邊,xrange()做的事情和range()一樣 -# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間 -# xrange() 建立一個產生器物件,而不是如range()建立整個List -# 我們用底線來避免可能和python的關鍵字重複的名稱 -xrange_ = xrange(1, 900000000) - -# 下面的程式碼會把所有的值乘以兩倍,直到出現大於30的值 -for i in double_numbers(xrange_): - print i - if i >= 30: - break - - -# 裝飾子 -# 在這個範例中,beg會綁在say上 -# Beg會呼叫say。 如果say_please為True的話,它會更改回傳的訊息 -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 :( -``` - -## 準備好學更多了嗎? - -### 線上免費資源 - -* [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/) - -### 或買本書? - -* [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-tw/pythonlegacy-tw.html.markdown b/zh-tw/pythonlegacy-tw.html.markdown new file mode 100644 index 00000000..cd7481d7 --- /dev/null +++ b/zh-tw/pythonlegacy-tw.html.markdown @@ -0,0 +1,727 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] +translators: + - ["Michael Yeh", "https://hinet60613.github.io/"] +filename: learnpython-tw.py +lang: zh-tw +--- + +Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。 + +非常歡迎各位給我們任何回饋! 你可以在[@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 2.7和3.X是可以做到的,只要引入 + [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組. + `__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼,詳細訊息請參考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 精確多了! + +# 整數除法的無條件捨去對正數或負數都適用 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # 浮點數的整數也適用 +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# 我們可以用除法模組(參考第六節:模組),讓 +# 單一斜線代表普通除法,而非無條件捨去 +from __future__ import division +11/4 # => 2.75 ...普通除法 +11//4 # => 2 ...無條件捨去 + +# 取餘數 +7 % 3 # => 1 + +# 指數 (x的y次方) +2**4 # => 16 + +# 用括號改變運算順序 +(1 + 3) * 2 # => 8 + +# 布林運算 +# 注意 "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 + +# 用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!" +# 不用加號也可以做字串相加 +"Hello " "world!" # => "Hello world!" + +# ... 也可以做相乘 +"Hello" * 3 # => "HelloHelloHello" + +# 字串可以被視為字元的陣列 +"This is a string"[0] # => 'T' + +# 字串的格式化可以用百分之符號 % +# 儘管在Python 3.1後這個功能被廢棄了,並且在 +# 之後的版本會被移除,但還是可以了解一下 +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x,y) + +# 新的格式化方式是使用format函式 +# 這個方式也是較為推薦的 +"{} is a {}".format("This", "placeholder") +"{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' 運算元是用來識別物件的。對原始型別來說或許沒什麼用, +# 但對物件來說是很有用的。 + +# 任何物件都可以被當作布林值使用 +# 以下的值會被視為是False : +# - 無(None) +# - 任何型別的零 (例如: 0, 0L, 0.0, 0j) +# - 空序列 (例如: '', (), []) +# - 空容器 (例如: {}, set()) +# - 自定義型別的實體,且滿足某些條件 +# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值). +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. 變數與集合 +#################################################### + +# Python的輸出很方便 +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# 從命令列獲得值也很方便 +input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數 +input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行 +# 注意: 請謹慎使用input()函式 +# 註: 在Python 3中,input()已被棄用,raw_input()已被更名為input() + +# 使用變數前不需要先宣告 +some_var = 5 # 方便好用 +lower_case_with_underscores +some_var # => 5 + +# 對沒有被賦值的變數取值會造成例外 +# 請參考錯誤流程部分做例外處理 +some_other_var # 造成 NameError + +# if可以當判斷式使用 +# 相當於C語言中的二元判斷式 +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# 串列型態可以儲存集合 +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] +# 然後再塞回去 +li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3] + +# 你可以像存取陣列一樣的存取串列 +li[0] # => 1 +# 用等號 = 給串列中特定索引的元素賦值 +li[0] = 42 +li[0] # => 42 +li[0] = 1 # 註: 將其設定回原本的值 +# 用 -1 索引值查看串列最後一個元素 +li[-1] # => 3 + +# 存取超過範圍會產生IndexError +li[4] # Raises an 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 內容為 [1, 2, 3] + +# 你可以做串列相加 +li + other_li # => [1, 2, 3, 4, 5, 6] +# 註: li 及 other_li 沒有被更動 + +# 用 "extend()" 做串列串接 +li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6] + +# 移除特定值的第一次出現 +li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6] +li.remove(2) # 2 不在串列中,造成 ValueError + +# 在特定位置插入值 +li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6] + +# 取得特定值在串列中第一次出現的位置 +li.index(2) # => 1 +li.index(7) # 7 不在串列中,造成 ValueError + +# 用 "in" 檢查特定值是否出現在串列中 +1 in li # => True + +# 用 "len()" 取得串列長度 +len(li) # => 6 + + +# 元組(Tuple,以下仍用原文)類似於串列,但是它是不可改變的 +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # 產生TypeError + +# 能對串列做的東西都可以對tuple做 +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# 你可以把tuple拆開並分別將值存入不同變數 +a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3 +d, e, f = 4, 5, 6 # 也可以不寫括號 +# 如果不加括號,預設會產生tuple +g = 4, 5, 6 # => (4, 5, 6) +# 你看,交換兩個值很簡單吧 +e, d = d, e # 此時 d 的值為 5 且 e 的值為 4 + + +# 字典(Dictionary)用來儲存映射關係 +empty_dict = {} +# 你可以對字典做初始化 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# 用 [] 取值 +filled_dict["one"] # => 1 + +# 用 "keys()" 將所有的Key輸出到一個List中 +filled_dict.keys() # => ["three", "two", "one"] +# 註: 字典裡key的排序是不固定的 +# 你的執行結果可能與上面不同 +# 譯註: 只能保證所有的key都有出現,但不保證順序 + +# 用 "values()" 將所有的Value輸出到一個List中 +filled_dict.values() # => [3, 2, 1] +# 註: 同上,不保證順序 + +# 用 "in" 來檢查指定的Key是否在字典中 +"one" in filled_dict # => True +1 in filled_dict # => False + +# 查詢不存在的Key會造成KeyError +filled_dict["four"] # KeyError + +# 用 "get()" 來避免KeyError +# 若指定的Key不存在的話會得到None +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# "get()" 函式支援預設值,當找不到指定的值時,會回傳指定的預設值 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# 注意此時 filled_dict.get("four") 仍然為 None +# (get()此時並沒有產生出任何的值) + +# 像操作list一樣,對指定的Key賦值 +filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4 + +# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary +filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5 + + +# 集合(Set)被用來儲存...集合。 +# 跟串列(List)有點像,但集合內不會有重複的元素 +empty_set = set() +# 初始化 "set()" 並給定一些值 +some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入 + +# 一樣,不保證順序,就算真的有照順序排也只是你運氣好 +another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4]) + +# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# 加入更多元素進入Set +filled_set.add(5) # filled_set is now {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} + +# 用 ^ 來對兩個集合取差集 +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# 檢查左邊是否為右邊的母集 +{1, 2} >= {1, 2, 3} # => False + +# 檢查左邊是否為右邊的子集 +{1, 2} <= {1, 2, 3} # => True + +# 用 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 迴圈會遞迴整的List +下面的程式碼會輸出: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # 你可以用{0}來組合0出格式化字串 (見上面.) + print "{0} is a mammal".format(animal) + +""" +"range(number)" 回傳一個包含從0到給定值的數字List, +下面的程式碼會輸出: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" 回傳一個包含從給定的下限 +到給定的上限的數字List +下面的程式碼會輸出: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + 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。通常這邊會讓你做對例外的處理 +except (TypeError, NameError): + pass # 有需要的話,多種例外可以一起處理 +else: # else 可有可無,但必須寫在所有的except後 + print "All good!" # 只有在try的時候沒有產生任何except才會被執行 +finally: # 不管什麼情況下一定會被執行 + print "We can clean up resources here" + +# 除了try/finally以外,你可以用 with 來簡單的處理清理動作 +with open("myfile.txt") as f: + for line in f: + print line + +#################################################### +## 4. 函式 +#################################################### + +# 用 "def" 來建立新函式 +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # 用 "return" 來回傳值 + +# 用參數來呼叫函式 +add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 + +# 你也可以寫上參數名稱來呼叫函式 +add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行 + + +# 你可以定義接受多個變數的函式,用*來表示參數tuple +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# 你可以定義接受多個變數的函式,用**來表示參數dictionary +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} +""" + +# 呼叫函式時,你可以做反向的操作 +# 用 * 將變數展開為順序排序的變數 +# 用 ** 將變數展開為Keyword排序的變數 +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) + +# 你可以把args跟kwargs傳到下一個函式內 +# 分別用 * 跟 ** 將它展開就可以了 +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# 函式範圍 +x = 5 + +def set_x(num): + # 區域變數 x 和全域變數 x 不是同一個東西 + x = num # => 43 + print x # => 43 + +def set_global_x(num): + global x + print x # => 5 + x = num # 全域變數 x 在set_global_x(6)被設定為 6 + print x # => 6 + +set_x(43) +set_global_x(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 +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# 還有內建的高階函式 +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] + +# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用 +[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" + + # 基礎建構函式,當class被實體化的時候會被呼叫 + # 注意前後的雙底線 + # 代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 + def __init__(self, name): + # 將函式引入的參數 name 指定給實體的 name 參數 + self.name = name + + # 初始化屬性 + self.age = 0 + + + # 一個實體的方法(method)。 所有的method都以self為第一個參數 + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # 一個類別方法會被所有的實體所共用 + # 他們會以類別為第一參數的方式被呼叫 + @classmethod + def get_species(cls): + return cls.species + + # 靜態方法 + @staticmethod + def grunt(): + return "*grunt*" + + # 屬性就像是用getter取值一樣 + # 它將方法 age() 轉為同名的、只能讀取的屬性 + @property + def age(self): + return self._age + + # 這樣寫的話可以讓屬性被寫入新的值 + @age.setter + def age(self, age): + self._age = age + + # 這樣寫的話允許屬性被刪除 + @age.deleter + def age(self): + del self._age + + +# 將類別實體化 +i = Human(name="Ian") +print i.say("hi") # prints out "Ian: hi" + +j = Human("Joel") +print j.say("hello") # prints out "Joel: hello" + +# 呼叫類別方法 +i.get_species() # => "H. sapiens" + +# 更改共用的屬性 +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# 呼叫靜態方法 +Human.grunt() # => "*grunt*" + +# 更新屬性 +i.age = 42 + +# 取得屬性 +i.age # => 42 + +# 移除屬性 +del i.age +i.age # => raises an AttributeError + + +#################################################### +## 6. 模組 +#################################################### + +# 你可以引入模組來做使用 +import math +print math.sqrt(16) # => 4.0 + # math.sqrt()為取根號 + +# 你可以只從模組取出特定幾個函式 +from math import ceil, floor +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# 你可以將所有的函式從模組中引入 +# 注意:不建議這麼做 +from math import * + +# 你可以用 as 簡寫模組名稱 +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# 你也可以測試函示是否相等 +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Python的模組就只是一般的Python檔。 +# 你可以自己的模組自己寫、自己的模組自己引入 +# 模組的名稱和檔案名稱一樣 + +# 你可以用dir()來查看有哪些可用函式和屬性 +import math +dir(math) + + +#################################################### +## 7. 進階 +#################################################### + +# 產生器(Generator)可以讓你寫更懶惰的程式碼 +def double_numbers(iterable): + for i in iterable: + yield i + i + +# 產生器可以讓你即時的產生值 +# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時 +# 產生值。 這也意味著大於15的值不會在double_numbers中產生。 +# 這邊,xrange()做的事情和range()一樣 +# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間 +# xrange() 建立一個產生器物件,而不是如range()建立整個List +# 我們用底線來避免可能和python的關鍵字重複的名稱 +xrange_ = xrange(1, 900000000) + +# 下面的程式碼會把所有的值乘以兩倍,直到出現大於30的值 +for i in double_numbers(xrange_): + print i + if i >= 30: + break + + +# 裝飾子 +# 在這個範例中,beg會綁在say上 +# Beg會呼叫say。 如果say_please為True的話,它會更改回傳的訊息 +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 :( +``` + +## 準備好學更多了嗎? + +### 線上免費資源 + +* [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/) + +### 或買本書? + +* [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) -- cgit v1.2.3