mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-08-08 07:46:46 +02:00
@@ -8,6 +8,8 @@ contributors:
|
|||||||
Brainfuck (not capitalized except at the start of a sentence) is an extremely
|
Brainfuck (not capitalized except at the start of a sentence) is an extremely
|
||||||
minimal Turing-complete programming language with just 8 commands.
|
minimal Turing-complete programming language with just 8 commands.
|
||||||
|
|
||||||
|
You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
|
||||||
|
|
||||||
```
|
```
|
||||||
Any character not "><+-.,[]" (excluding quotation marks) is ignored.
|
Any character not "><+-.,[]" (excluding quotation marks) is ignored.
|
||||||
|
|
||||||
|
@@ -234,7 +234,7 @@ int main() {
|
|||||||
// same with j-- and --j
|
// same with j-- and --j
|
||||||
|
|
||||||
// Bitwise operators!
|
// Bitwise operators!
|
||||||
~0x0F; // => 0xF0 (bitwise negation, "1's complement")
|
~0x0F; // => 0xFFFFFFF0 (bitwise negation, "1's complement", example result for 32-bit int)
|
||||||
0x0F & 0xF0; // => 0x00 (bitwise AND)
|
0x0F & 0xF0; // => 0x00 (bitwise AND)
|
||||||
0x0F | 0xF0; // => 0xFF (bitwise OR)
|
0x0F | 0xF0; // => 0xFF (bitwise OR)
|
||||||
0x04 ^ 0x0F; // => 0x0B (bitwise XOR)
|
0x04 ^ 0x0F; // => 0x0B (bitwise XOR)
|
||||||
@@ -242,7 +242,7 @@ int main() {
|
|||||||
0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
|
0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
|
||||||
|
|
||||||
// Be careful when shifting signed integers - the following are undefined:
|
// Be careful when shifting signed integers - the following are undefined:
|
||||||
// - shifting into the sign bit of a signed integer (int a = 1 << 32)
|
// - shifting into the sign bit of a signed integer (int a = 1 << 31)
|
||||||
// - left-shifting a negative number (int a = -1 << 2)
|
// - left-shifting a negative number (int a = -1 << 2)
|
||||||
// - shifting by an offset which is >= the width of the type of the LHS:
|
// - shifting by an offset which is >= the width of the type of the LHS:
|
||||||
// int a = 1 << 32; // UB if int is 32 bits wide
|
// int a = 1 << 32; // UB if int is 32 bits wide
|
||||||
|
@@ -5,34 +5,34 @@ contributors:
|
|||||||
- ["Joseph Adams", "https://github.com/jcla1"]
|
- ["Joseph Adams", "https://github.com/jcla1"]
|
||||||
lang: de-de
|
lang: de-de
|
||||||
---
|
---
|
||||||
Go wurde entwickelt um probleme zu lösen. Sie ist zwar nicht der neuste Trend in
|
Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in
|
||||||
der Informatik, aber sie ist eine der neusten und schnellsten Wege um Aufgabe in
|
der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in
|
||||||
der realen Welt zu lösen.
|
der realen Welt zu lösen.
|
||||||
|
|
||||||
Sie hat vertraute Elemente von imperativen Sprachen mit statisher Typisierung
|
Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung
|
||||||
und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu
|
und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu
|
||||||
verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern
|
verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern
|
||||||
Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große
|
Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große
|
||||||
Programmierprojekte.
|
Programmierprojekte.
|
||||||
|
|
||||||
Außerdem beinhaltet Go eine gut ausgestattete standard bibliothek und hat eine
|
Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine
|
||||||
aktive community.
|
aktive Community.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// Einzeiliger Kommentar
|
// Einzeiliger Kommentar
|
||||||
/* Mehr-
|
/* Mehr-
|
||||||
zeiliger Kommentar */
|
zeiliger Kommentar */
|
||||||
|
|
||||||
// Eine jede Quelldatei beginnt mit einer Packet-Klausel.
|
// Eine jede Quelldatei beginnt mit einer Paket-Klausel.
|
||||||
// "main" ist ein besonderer Packetname, da er ein ausführbares Programm
|
// "main" ist ein besonderer Pkaetname, da er ein ausführbares Programm
|
||||||
// einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek
|
// einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek
|
||||||
// deklariert.
|
// deklariert.
|
||||||
package main
|
package main
|
||||||
|
|
||||||
// Ein "import" wird verwendet um Packte zu deklarieren, die in dieser
|
// Ein "import" wird verwendet, um Pakete zu deklarieren, die in dieser
|
||||||
// Quelldatei Anwendung finden.
|
// Quelldatei Anwendung finden.
|
||||||
import (
|
import (
|
||||||
"fmt" // Ein Packet in der Go standard Bibliothek
|
"fmt" // Ein Paket in der Go Standardbibliothek
|
||||||
"net/http" // Ja, ein Webserver.
|
"net/http" // Ja, ein Webserver.
|
||||||
"strconv" // Zeichenkettenmanipulation
|
"strconv" // Zeichenkettenmanipulation
|
||||||
)
|
)
|
||||||
@@ -42,10 +42,10 @@ import (
|
|||||||
// Programms. Vergessen Sie nicht die geschweiften Klammern!
|
// Programms. Vergessen Sie nicht die geschweiften Klammern!
|
||||||
func main() {
|
func main() {
|
||||||
// Println gibt eine Zeile zu stdout aus.
|
// Println gibt eine Zeile zu stdout aus.
|
||||||
// Der Prefix "fmt" bestimmt das Packet aus welchem die Funktion stammt.
|
// Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt.
|
||||||
fmt.Println("Hello world!")
|
fmt.Println("Hello world!")
|
||||||
|
|
||||||
// Aufruf einer weiteren Funktion definiert innerhalb dieses Packets.
|
// Aufruf einer weiteren Funktion definiert innerhalb dieses Pakets.
|
||||||
beyondHello()
|
beyondHello()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ func main() {
|
|||||||
func beyondHello() {
|
func beyondHello() {
|
||||||
var x int // Deklaration einer Variable, muss vor Gebrauch geschehen.
|
var x int // Deklaration einer Variable, muss vor Gebrauch geschehen.
|
||||||
x = 3 // Zuweisung eines Werts.
|
x = 3 // Zuweisung eines Werts.
|
||||||
// Kurze Deklaration: Benutzen Sie ":=" um die Typisierung automatisch zu
|
// Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu
|
||||||
// folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen.
|
// folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen.
|
||||||
y := 4
|
y := 4
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ func learnMultiple(x, y int) (sum, prod int) {
|
|||||||
return x + y, x * y // Wiedergabe zweier Werte
|
return x + y, x * y // Wiedergabe zweier Werte
|
||||||
}
|
}
|
||||||
|
|
||||||
// Überblick ueber einige eingebaute Typen und Literale.
|
// Überblick über einige eingebaute Typen und Literale.
|
||||||
func learnTypes() {
|
func learnTypes() {
|
||||||
// Kurze Deklarationen sind die Norm.
|
// Kurze Deklarationen sind die Norm.
|
||||||
s := "Lernen Sie Go!" // Zeichenketten-Typ
|
s := "Lernen Sie Go!" // Zeichenketten-Typ
|
||||||
@@ -111,7 +111,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ
|
|||||||
m["eins"] = 1
|
m["eins"] = 1
|
||||||
|
|
||||||
// Ungebrauchte Variablen sind Fehler in Go
|
// Ungebrauchte Variablen sind Fehler in Go
|
||||||
// Der Unterstrich wird verwendet um einen Wert zu verwerfen.
|
// Der Unterstrich wird verwendet, um einen Wert zu verwerfen.
|
||||||
_, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
|
_, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
|
||||||
// Die Ausgabe zählt natürlich auch als Gebrauch
|
// Die Ausgabe zählt natürlich auch als Gebrauch
|
||||||
fmt.Println(s, c, a4, s3, d2, m)
|
fmt.Println(s, c, a4, s3, d2, m)
|
||||||
@@ -142,7 +142,7 @@ func learnFlowControl() {
|
|||||||
if true {
|
if true {
|
||||||
fmt.Println("hab's dir ja gesagt!")
|
fmt.Println("hab's dir ja gesagt!")
|
||||||
}
|
}
|
||||||
// Die Formattierung ist durch den Befehl "go fmt" standardisiert
|
// Die Formatierung ist durch den Befehl "go fmt" standardisiert
|
||||||
if false {
|
if false {
|
||||||
// nicht hier
|
// nicht hier
|
||||||
} else {
|
} else {
|
||||||
@@ -170,7 +170,7 @@ func learnFlowControl() {
|
|||||||
continue // wird nie ausgeführt
|
continue // wird nie ausgeführt
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wie bei for, bedeutet := in einer Bedingten Anweisung zunächst die
|
// Wie bei for, bedeutet := in einer bedingten Anweisung zunächst die
|
||||||
// Zuweisung und erst dann die Überprüfung der Bedingung.
|
// Zuweisung und erst dann die Überprüfung der Bedingung.
|
||||||
if y := expensiveComputation(); y > x {
|
if y := expensiveComputation(); y > x {
|
||||||
x = y
|
x = y
|
||||||
@@ -217,8 +217,8 @@ func learnInterfaces() {
|
|||||||
// Aufruf der String Methode von i, gleiche Ausgabe wie zuvor.
|
// Aufruf der String Methode von i, gleiche Ausgabe wie zuvor.
|
||||||
fmt.Println(i.String())
|
fmt.Println(i.String())
|
||||||
|
|
||||||
// Funktionen des fmt-Packets rufen die String() Methode auf um eine
|
// Funktionen des fmt-Pakets rufen die String() Methode auf um eine
|
||||||
// druckbare variante des Empfängers zu erhalten.
|
// druckbare Variante des Empfängers zu erhalten.
|
||||||
fmt.Println(p) // gleiche Ausgabe wie zuvor
|
fmt.Println(p) // gleiche Ausgabe wie zuvor
|
||||||
fmt.Println(i) // und wieder die gleiche Ausgabe wie zuvor
|
fmt.Println(i) // und wieder die gleiche Ausgabe wie zuvor
|
||||||
|
|
||||||
@@ -244,18 +244,18 @@ func learnErrorHandling() {
|
|||||||
learnConcurrency()
|
learnConcurrency()
|
||||||
}
|
}
|
||||||
|
|
||||||
// c ist ein Kannal, ein sicheres Kommunikationsmedium.
|
// c ist ein Kanal, ein sicheres Kommunikationsmedium.
|
||||||
func inc(i int, c chan int) {
|
func inc(i int, c chan int) {
|
||||||
c <- i + 1 // <- ist der "send" Operator, wenn ein Kannal auf der Linken ist
|
c <- i + 1 // <- ist der "send" Operator, wenn ein Kanal auf der Linken ist
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wir verwenden "inc" um Zahlen parallel zu erhöhen.
|
// Wir verwenden "inc" um Zahlen parallel zu erhöhen.
|
||||||
func learnConcurrency() {
|
func learnConcurrency() {
|
||||||
// Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für
|
// Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für
|
||||||
// maps, slices und Kannäle.
|
// maps, slices und Kanäle.
|
||||||
c := make(chan int)
|
c := make(chan int)
|
||||||
// Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently)
|
// Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently)
|
||||||
// erhöht. Alle drei senden ihr Ergebnis in den gleichen Kannal.
|
// erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal.
|
||||||
go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine
|
go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine
|
||||||
go inc(10, c)
|
go inc(10, c)
|
||||||
go inc(-805, c)
|
go inc(-805, c)
|
||||||
@@ -269,16 +269,16 @@ func learnConcurrency() {
|
|||||||
|
|
||||||
// Start einer neuen Goroutine, nur um einen Wert zu senden
|
// Start einer neuen Goroutine, nur um einen Wert zu senden
|
||||||
go func() { c <- 84 }()
|
go func() { c <- 84 }()
|
||||||
go func() { cs <- "wortreich" }() // schon wider, diesmal für
|
go func() { cs <- "wortreich" }() // schon wieder, diesmal für
|
||||||
// "select" hat eine Syntax wie ein switch Statement, aber jeder Fall ist
|
// "select" hat eine Syntax wie ein switch Statement, aber jeder Fall ist
|
||||||
// eine Kannaloperation. Es wählt eine Fall zufällig aus allen die
|
// eine Kanaloperation. Es wählt einen Fall zufällig aus allen, die
|
||||||
// kommunikationsbereit sind aus.
|
// kommunikationsbereit sind, aus.
|
||||||
select {
|
select {
|
||||||
case i := <-c: // der empfangene Wert kann einer Variable zugewiesen werden
|
case i := <-c: // der empfangene Wert kann einer Variable zugewiesen werden
|
||||||
fmt.Printf("es ist ein: %T", i)
|
fmt.Printf("es ist ein: %T", i)
|
||||||
case <-cs: // oder der Wert kann verworfen werden
|
case <-cs: // oder der Wert kann verworfen werden
|
||||||
fmt.Println("es ist eine Zeichenkette!")
|
fmt.Println("es ist eine Zeichenkette!")
|
||||||
case <-cc: // leerer Kannal, nicht bereit für den Empfang
|
case <-cc: // leerer Kanal, nicht bereit für den Empfang
|
||||||
fmt.Println("wird nicht passieren.")
|
fmt.Println("wird nicht passieren.")
|
||||||
}
|
}
|
||||||
// Hier wird eine der beiden Goroutines fertig sein, die andere nicht.
|
// Hier wird eine der beiden Goroutines fertig sein, die andere nicht.
|
||||||
@@ -287,16 +287,16 @@ func learnConcurrency() {
|
|||||||
learnWebProgramming() // Go kann es und Sie hoffentlich auch bald.
|
learnWebProgramming() // Go kann es und Sie hoffentlich auch bald.
|
||||||
}
|
}
|
||||||
|
|
||||||
// Eine einzige Funktion aus dem http-Packet kann einen Webserver starten.
|
// Eine einzige Funktion aus dem http-Paket kann einen Webserver starten.
|
||||||
func learnWebProgramming() {
|
func learnWebProgramming() {
|
||||||
// Der erste Parameter von "ListenAndServe" ist eine TCP Addresse an die
|
// Der erste Parameter von "ListenAndServe" ist eine TCP Addresse, an die
|
||||||
// sich angeschlossen werden soll.
|
// sich angeschlossen werden soll.
|
||||||
// Der zweite Parameter ist ein Interface, speziell: ein http.Handler
|
// Der zweite Parameter ist ein Interface, speziell: ein http.Handler
|
||||||
err := http.ListenAndServe(":8080", pair{})
|
err := http.ListenAndServe(":8080", pair{})
|
||||||
fmt.Println(err) // Fehler sollte man nicht ignorieren!
|
fmt.Println(err) // Fehler sollte man nicht ignorieren!
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wir lassen "pair" das http.Handler Interface erfüllen indem wir seine einzige
|
// Wir lassen "pair" das http.Handler Interface erfüllen, indem wir seine einzige
|
||||||
// Methode implementieren: ServeHTTP
|
// Methode implementieren: ServeHTTP
|
||||||
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
// Senden von Daten mit einer Methode des http.ResponseWriter
|
// Senden von Daten mit einer Methode des http.ResponseWriter
|
||||||
@@ -313,6 +313,6 @@ Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr
|
|||||||
kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen
|
kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen
|
||||||
ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/).
|
ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/).
|
||||||
Gut documentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil
|
Gut documentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil
|
||||||
verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktions-
|
verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen
|
||||||
Namen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/).
|
in der [offiziellen Dokumentation von Go](http://golang.org/pkg/).
|
||||||
|
|
||||||
|
@@ -149,7 +149,7 @@ li[0] #=> 1
|
|||||||
# Das letzte Element ansehen
|
# Das letzte Element ansehen
|
||||||
li[-1] #=> 3
|
li[-1] #=> 3
|
||||||
|
|
||||||
# Bei Zugriffen außerhal der Liste kommt es jedoch zu einem IndexError
|
# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError
|
||||||
li[4] # Raises an IndexError
|
li[4] # Raises an IndexError
|
||||||
|
|
||||||
# Wir können uns Ranges mit Slice-Syntax ansehen
|
# Wir können uns Ranges mit Slice-Syntax ansehen
|
||||||
@@ -188,7 +188,7 @@ tup[:2] #=> (1, 2)
|
|||||||
|
|
||||||
# Wir können Tupel (oder Listen) in Variablen entpacken
|
# 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
|
a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3
|
||||||
# Tuple werden standardmäßig erstellt, wenn wir uns die Klammern sparen
|
# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen
|
||||||
d, e, f = 4, 5, 6
|
d, e, f = 4, 5, 6
|
||||||
# Es ist kinderleicht zwei Werte zu tauschen
|
# Es ist kinderleicht zwei Werte zu tauschen
|
||||||
e, d = d, e # d is now 5 and e is now 4
|
e, d = d, e # d is now 5 and e is now 4
|
||||||
|
@@ -206,7 +206,7 @@ max(X, Y) ->
|
|||||||
if
|
if
|
||||||
X > Y -> X;
|
X > Y -> X;
|
||||||
X < Y -> Y;
|
X < Y -> Y;
|
||||||
true -> nil;
|
true -> nil
|
||||||
end.
|
end.
|
||||||
|
|
||||||
% Warning: at least one of the guards in the `if` expression must evaluate to true;
|
% Warning: at least one of the guards in the `if` expression must evaluate to true;
|
||||||
|
439
fr-fr/go-fr.html.markdown
Normal file
439
fr-fr/go-fr.html.markdown
Normal file
@@ -0,0 +1,439 @@
|
|||||||
|
---
|
||||||
|
name: Go
|
||||||
|
category: language
|
||||||
|
language: Go
|
||||||
|
lang: fr-fr
|
||||||
|
filename: learngo.go
|
||||||
|
contributors:
|
||||||
|
- ["Sonia Keys", "https://github.com/soniakeys"]
|
||||||
|
- ["Christopher Bess", "https://github.com/cbess"]
|
||||||
|
- ["Jesse Johnson", "https://github.com/holocronweaver"]
|
||||||
|
- ["Quint Guvernator", "https://github.com/qguv"]
|
||||||
|
- ["Jose Donizetti", "https://github.com/josedonizetti"]
|
||||||
|
- ["Alexej Friesen", "https://github.com/heyalexej"]
|
||||||
|
- ["Jean-Philippe Monette", "http://blogue.jpmonette.net/"]
|
||||||
|
---
|
||||||
|
|
||||||
|
Go a été créé dans l'optique de développer de façon efficace. Ce n'est pas la
|
||||||
|
dernière tendance en ce qui est au développement, mais c'est la nouvelle façon
|
||||||
|
de régler des défis réels de façon rapide.
|
||||||
|
|
||||||
|
Le langage possède des concepts familiers à la programmation impérative avec
|
||||||
|
typage. Il est rapide à compiler et exécuter, ajoute une concurrence facile à
|
||||||
|
comprendre, pour les processeurs multi coeurs d'aujourd'hui et apporte des
|
||||||
|
fonctionnalités facilitant le développement à grande échelle.
|
||||||
|
|
||||||
|
Développer avec Go, c'est bénéficier d'une riche bibliothèque standard et d'une
|
||||||
|
communauté active.
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Commentaire ligne simple
|
||||||
|
/* Commentaire
|
||||||
|
multiligne */
|
||||||
|
|
||||||
|
// Un paquet débute avec une clause "package"
|
||||||
|
// "Main" est un nom spécial déclarant un paquet de type exécutable plutôt
|
||||||
|
// qu'une bibliothèque
|
||||||
|
package main
|
||||||
|
|
||||||
|
// "Import" déclare les paquets référencés dans ce fichier.
|
||||||
|
import (
|
||||||
|
"fmt" // Un paquet dans la bibliothèque standard.
|
||||||
|
"io/ioutil" // Implémente des fonctions utilitaires I/O.
|
||||||
|
m "math" // Bibliothèque mathématique utilisant un alias local "m".
|
||||||
|
"net/http" // Un serveur Web!
|
||||||
|
"strconv" // Bibliothèque pour convertir les chaînes de caractères.
|
||||||
|
)
|
||||||
|
|
||||||
|
// Une définition de fonction. La fonction "main" est spéciale - c'est le point
|
||||||
|
// d'entrée du binaire.
|
||||||
|
func main() {
|
||||||
|
// Println retournera la valeur à la console.
|
||||||
|
// Associez la fonction avec son paquet respectif, fmt.
|
||||||
|
fmt.Println("Hello world!")
|
||||||
|
|
||||||
|
// Appelez une fonction différente à partir de ce paquet.
|
||||||
|
beyondHello()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Les fonctions ont des paramètres entre parenthèses.
|
||||||
|
// Les parenthèses sont nécessaires avec ou sans paramètre.
|
||||||
|
func beyondHello() {
|
||||||
|
var x int // Déclaration de variable. Les variables doivent être déclarées
|
||||||
|
// avant leur utilisation.
|
||||||
|
x = 3 // Assignation de valeur.
|
||||||
|
// Les déclarations courtes utilisent := pour inférer le type, déclarer et
|
||||||
|
// assigner.
|
||||||
|
y := 4
|
||||||
|
sum, prod := learnMultiple(x, y) // La fonction retourne deux valeurs.
|
||||||
|
fmt.Println("sum:", sum, "prod:", prod) // Affichage simple.
|
||||||
|
learnTypes() // < y minutes, en savoir plus!
|
||||||
|
}
|
||||||
|
|
||||||
|
// Les fonctions peuvent avoir des paramètres et plusieurs valeurs retournées.
|
||||||
|
func learnMultiple(x, y int) (sum, prod int) {
|
||||||
|
return x + y, x * y // Deux valeurs retournées.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quelques types inclus et littéraux.
|
||||||
|
func learnTypes() {
|
||||||
|
// Une déclaration courte infère généralement le type désiré.
|
||||||
|
str := "Learn Go!" // Type string.
|
||||||
|
|
||||||
|
s2 := `Une chaîne de caractères peut contenir des
|
||||||
|
sauts de ligne.` // Chaîne de caractère.
|
||||||
|
|
||||||
|
// Littéral non-ASCII. Les sources Go utilisent le charset UTF-8.
|
||||||
|
g := 'Σ' // type rune, un alias pour le type int32, contenant un caractère
|
||||||
|
// unicode.
|
||||||
|
|
||||||
|
f := 3.14195 // float64, un nombre flottant IEEE-754 de 64-bit.
|
||||||
|
c := 3 + 4i // complex128, considéré comme deux float64 par le compilateur.
|
||||||
|
|
||||||
|
// Syntaxe "var" avec une valeur d'initialisation.
|
||||||
|
var u uint = 7 // Non signé, mais la taille dépend selon l'entier.
|
||||||
|
var pi float32 = 22. / 7
|
||||||
|
|
||||||
|
// Conversion avec syntaxe courte.
|
||||||
|
n := byte('\n') // byte est un alias du type uint8.
|
||||||
|
|
||||||
|
// Les tableaux ont une taille fixe déclarée à la compilation.
|
||||||
|
var a4 [4]int // Un tableau de 4 ints, tous initialisés à 0.
|
||||||
|
a3 := [...]int{3, 1, 5} // Un tableau initialisé avec une taille fixe de 3
|
||||||
|
// éléments, contenant les valeurs 3, 1 et 5.
|
||||||
|
|
||||||
|
// Les slices ont des tailles dynamiques. Les tableaux et slices ont chacun
|
||||||
|
// des avantages, mais les cas d'utilisation des slices sont plus fréquents.
|
||||||
|
s3 := []int{4, 5, 9} // Comparable à a3.
|
||||||
|
s4 := make([]int, 4) // Alloue un slice de 4 ints, initialisés à 0.
|
||||||
|
var d2 [][]float64 // Déclaration seulement, sans allocation de mémoire.
|
||||||
|
bs := []byte("a slice") // Conversion d'une chaîne en slice de bytes.
|
||||||
|
|
||||||
|
// Parce qu'elles sont dynamiques, les slices peuvent être jointes sur
|
||||||
|
// demande. Pour joindre un élément à une slice, la fonction standard append()
|
||||||
|
// est utilisée. Le premier argument est la slice à utiliser. Habituellement,
|
||||||
|
// la variable tableau est mise à jour sur place, voir ci-bas.
|
||||||
|
s := []int{1, 2, 3} // Le résultat est une slice de taille 3.
|
||||||
|
s = append(s, 4, 5, 6) // Ajout de 3 valeurs. La taille est de 6.
|
||||||
|
fmt.Println(s) // La valeur est de [1 2 3 4 5 6]
|
||||||
|
|
||||||
|
// Pour ajouter une slice à une autre, au lieu d'utiliser une liste de valeurs
|
||||||
|
// atomiques, il est possible de mettre en argument une référence de
|
||||||
|
// slice littérale grâce aux points de suspension.
|
||||||
|
s = append(s, []int{7, 8, 9}...) // Le deuxième argument est une slice
|
||||||
|
// littérale.
|
||||||
|
fmt.Println(s) // La slice contient [1 2 3 4 5 6 7 8 9]
|
||||||
|
|
||||||
|
p, q := learnMemory() // Déclare p, q comme étant des pointeurs de type int.
|
||||||
|
fmt.Println(*p, *q) // * suit un pointeur. Ceci retourne deux ints.
|
||||||
|
|
||||||
|
// Les maps sont des tableaux associatifs de taille dynamique, comme les
|
||||||
|
// hash ou les types dictionnaires de certains langages.
|
||||||
|
m := map[string]int{"trois": 3, "quatre": 4}
|
||||||
|
m["un"] = 1
|
||||||
|
|
||||||
|
// Les valeurs inutilisées sont considérées comme des erreurs en Go.
|
||||||
|
// Un tiret bas permet d'ignorer une valeur inutilisée, évitant une erreur.
|
||||||
|
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
|
||||||
|
|
||||||
|
// Cependant, son affichage en console est considéré comme une utilisation,
|
||||||
|
// ce qui ne sera pas considéré comme une erreur à la compilation.
|
||||||
|
fmt.Println(s, c, a4, s3, d2, m)
|
||||||
|
|
||||||
|
learnFlowControl() // De retour dans le flux.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Il est possible, à l'opposé de plusieurs autres langages, de retourner des
|
||||||
|
// variables par leur nom à partir de fonctions.
|
||||||
|
// Assigner un nom à un type retourné par une fonction permet de retrouver sa
|
||||||
|
// valeur ainsi que d'utiliser le mot-clé "return" uniquement, sans plus.
|
||||||
|
func learnNamedReturns(x, y int) (z int) {
|
||||||
|
z = x * y
|
||||||
|
return // z est implicite, car la variable a été définie précédemment.
|
||||||
|
}
|
||||||
|
|
||||||
|
// La récupération de la mémoire est automatique en Go. Le langage possède des
|
||||||
|
// pointeurs, mais aucune arithmétique des pointeurs (*(a + b) en C). Vous
|
||||||
|
// pouvez produire une erreur avec un pointeur nil, mais pas en incrémentant un
|
||||||
|
// pointeur.
|
||||||
|
func learnMemory() (p, q *int) {
|
||||||
|
// Les valeurs retournées p et q auront le type pointeur int.
|
||||||
|
p = new(int) // Fonction standard "new" alloue la mémoire.
|
||||||
|
// Le int alloué est initialisé à 0, p n'est plus nil.
|
||||||
|
s := make([]int, 20) // Alloue 20 ints en un seul bloc de mémoire.
|
||||||
|
s[3] = 7 // Assigne l'un des entiers.
|
||||||
|
r := -2 // Déclare une autre variable locale.
|
||||||
|
return &s[3], &r // & retourne l'adresse d'un objet.
|
||||||
|
}
|
||||||
|
|
||||||
|
func expensiveComputation() float64 {
|
||||||
|
return m.Exp(10)
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnFlowControl() {
|
||||||
|
// Bien que les "if" requièrent des accolades, les parenthèses ne sont pas
|
||||||
|
// nécessaires pour contenir le test booléen.
|
||||||
|
if true {
|
||||||
|
fmt.Println("voilà!")
|
||||||
|
}
|
||||||
|
// Le formatage du code est standardisé par la commande shell "go fmt."
|
||||||
|
if false {
|
||||||
|
// bing.
|
||||||
|
} else {
|
||||||
|
// bang.
|
||||||
|
}
|
||||||
|
// Utilisez "switch" au lieu des "if" en chaîne
|
||||||
|
x := 42.0
|
||||||
|
switch x {
|
||||||
|
case 0:
|
||||||
|
case 1:
|
||||||
|
case 42:
|
||||||
|
// Les "case" n'ont pas besoin de "break;".
|
||||||
|
case 43:
|
||||||
|
// Non-exécuté.
|
||||||
|
}
|
||||||
|
// Comme les "if", les "for" n'utilisent pas de parenthèses.
|
||||||
|
// Les variables déclarées dans les "for" et les "if" sont locales à leur
|
||||||
|
// portée.
|
||||||
|
for x := 0; x < 3; x++ { // ++ est une incrémentation.
|
||||||
|
fmt.Println("itération ", x)
|
||||||
|
}
|
||||||
|
// x == 42 ici.
|
||||||
|
|
||||||
|
// "For" est le seul type de boucle en Go, mais possède différentes formes.
|
||||||
|
for { // Boucle infinie
|
||||||
|
break // C'est une farce
|
||||||
|
continue // Non atteint.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vous pouvez utiliser une "range" pour itérer dans un tableau, une slice, une
|
||||||
|
// chaîne, une map ou un canal. Les "range" retournent un canal ou deux
|
||||||
|
// valeurs (tableau, slice, chaîne et map).
|
||||||
|
for key, value := range map[string]int{"une": 1, "deux": 2, "trois": 3} {
|
||||||
|
// pour chaque pair dans une map, affichage de la valeur et clé
|
||||||
|
fmt.Printf("clé=%s, valeur=%d\n", key, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// À l'opposé du "for", := dans un "if" signifie la déclaration et
|
||||||
|
// l'assignation y en premier, et ensuite y > x
|
||||||
|
if y := expensiveComputation(); y > x {
|
||||||
|
x = y
|
||||||
|
}
|
||||||
|
// Les fonctions littérales sont des fermetures.
|
||||||
|
xBig := func() bool {
|
||||||
|
return x > 10000
|
||||||
|
}
|
||||||
|
fmt.Println("xBig:", xBig()) // true (la valeur e^10 a été assignée à x).
|
||||||
|
x = 1.3e3 // Ceci fait x == 1300
|
||||||
|
fmt.Println("xBig:", xBig()) // Maintenant false.
|
||||||
|
|
||||||
|
// De plus, les fonctions littérales peuvent être définies et appelées
|
||||||
|
// sur la même ligne, agissant comme argument à cette fonction, tant que:
|
||||||
|
// a) la fonction littérale est appelée suite à (),
|
||||||
|
// b) le résultat correspond au type de l'argument.
|
||||||
|
fmt.Println("Ajoute + multiplie deux nombres : ",
|
||||||
|
func(a, b int) int {
|
||||||
|
return (a + b) * 2
|
||||||
|
}(10, 2)) // Appelle la fonction avec les arguments 10 et 2
|
||||||
|
// => Ajoute + double deux nombres : 24
|
||||||
|
|
||||||
|
// Quand vous en aurez besoin, vous allez l'adorer.
|
||||||
|
goto love
|
||||||
|
love:
|
||||||
|
|
||||||
|
learnFunctionFactory() // func retournant func correspondant à fun(3)(3).
|
||||||
|
learnDefer() // Un survol de cette instruction importante.
|
||||||
|
learnInterfaces() // Incontournable !
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnFunctionFactory() {
|
||||||
|
// Les deux syntaxes sont identiques, bien que la seconde soit plus pratique.
|
||||||
|
fmt.Println(sentenceFactory("été")("Une matinée d'", "agréable!"))
|
||||||
|
|
||||||
|
d := sentenceFactory("été")
|
||||||
|
fmt.Println(d("Une matinée d'", "agréable!"))
|
||||||
|
fmt.Println(d("Une soirée d'", "relaxante!"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Le décorateur est un patron de conception commun dans d'autres langages.
|
||||||
|
// Il est possible de faire de même en Go avec des fonctions littérales
|
||||||
|
// acceptant des arguments.
|
||||||
|
func sentenceFactory(mystring string) func(before, after string) string {
|
||||||
|
return func(before, after string) string {
|
||||||
|
return fmt.Sprintf("%s %s %s", before, mystring, after) // nouvelle chaîne
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnDefer() (ok bool) {
|
||||||
|
// Les déclarations différées sont exécutées avant la sortie d'une fonction.
|
||||||
|
defer fmt.Println("les déclarations différées s'exécutent en ordre LIFO.")
|
||||||
|
defer fmt.Println("\nCette ligne est affichée en premier parce que")
|
||||||
|
// Les déclarations différées sont utilisées fréquemment pour fermer un
|
||||||
|
// fichier, afin que la fonction ferme le fichier en fin d'exécution.
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Défini Stringer comme étant une interface avec une méthode, String.
|
||||||
|
type Stringer interface {
|
||||||
|
String() string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Défini pair comme étant une structure contenant deux entiers, x et y.
|
||||||
|
type pair struct {
|
||||||
|
x, y int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Défini une méthode associée au type pair. Pair implémente maintenant Stringer
|
||||||
|
func (p pair) String() string { // p s'appelle le "destinataire"
|
||||||
|
// Sprintf est une autre fonction publique dans le paquet fmt.
|
||||||
|
// La syntaxe avec point permet de faire référence aux valeurs de p.
|
||||||
|
return fmt.Sprintf("(%d, %d)", p.x, p.y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnInterfaces() {
|
||||||
|
// La syntaxe avec accolade défini une "structure littérale". Celle-ci
|
||||||
|
// s'évalue comme étant une structure. La syntaxe := déclare et initialise p
|
||||||
|
// comme étant une instance.
|
||||||
|
p := pair{3, 4}
|
||||||
|
fmt.Println(p.String()) // Appelle la méthode String de p, de type pair.
|
||||||
|
var i Stringer // Déclare i instance de l'interface Stringer.
|
||||||
|
i = p // Valide, car pair implémente Stringer.
|
||||||
|
// Appelle la méthode String de i, de type Stringer. Retourne la même valeur
|
||||||
|
// que ci-haut.
|
||||||
|
fmt.Println(i.String())
|
||||||
|
|
||||||
|
// Les fonctions dans le paquet fmt appellent la méthode String, demandant
|
||||||
|
// aux objets d'afficher une représentation de leur structure.
|
||||||
|
fmt.Println(p) // Affiche la même chose que ci-haut. Println appelle la
|
||||||
|
// méthode String.
|
||||||
|
fmt.Println(i) // Affiche la même chose que ci-haut.
|
||||||
|
|
||||||
|
learnVariadicParams("apprentissage", "génial", "ici!")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Les fonctions peuvent être définie de façon à accepter un ou plusieurs
|
||||||
|
// paramètres grâce aux points de suspension, offrant une flexibilité lors de
|
||||||
|
// son appel.
|
||||||
|
func learnVariadicParams(myStrings ...interface{}) {
|
||||||
|
// Itère chaque paramètre dans la range.
|
||||||
|
// Le tiret bas sert à ignorer l'index retourné du tableau.
|
||||||
|
for _, param := range myStrings {
|
||||||
|
fmt.Println("paramètre:", param)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Passe une valeur variadique comme paramètre variadique.
|
||||||
|
fmt.Println("paramètres:", fmt.Sprintln(myStrings...))
|
||||||
|
|
||||||
|
learnErrorHandling()
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnErrorHandling() {
|
||||||
|
// ", ok" idiome utilisée pour définir si l'opération s'est déroulée avec
|
||||||
|
// succès ou non
|
||||||
|
m := map[int]string{3: "trois", 4: "quatre"}
|
||||||
|
if x, ok := m[1]; !ok { // ok sera faux, car 1 n'est pas dans la map.
|
||||||
|
fmt.Println("inexistant")
|
||||||
|
} else {
|
||||||
|
fmt.Print(x) // x serait la valeur, si elle se trouvait dans la map.
|
||||||
|
}
|
||||||
|
// Une erreur ne retourne qu'un "ok", mais également plus d'information
|
||||||
|
// par rapport à un problème survenu.
|
||||||
|
if _, err := strconv.Atoi("non-int"); err != nil { // _ discarte la valeur
|
||||||
|
// retourne: 'strconv.ParseInt: parsing "non-int": invalid syntax'
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
// Nous réviserons les interfaces un peu plus tard. Pour l'instant,
|
||||||
|
learnConcurrency()
|
||||||
|
}
|
||||||
|
|
||||||
|
// c est un canal, un objet permettant de communiquer en simultané de façon
|
||||||
|
// sécurisée.
|
||||||
|
func inc(i int, c chan int) {
|
||||||
|
c <- i + 1 // <- est l'opérateur "envoi" quand un canal apparaît à
|
||||||
|
// gauche.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nous utiliserons inc pour incrémenter des nombres en même temps.
|
||||||
|
func learnConcurrency() {
|
||||||
|
// La fonction "make" utilisée précédemment pour générer un slice. Elle
|
||||||
|
// alloue et initialise les slices, maps et les canaux.
|
||||||
|
c := make(chan int)
|
||||||
|
// Démarrage de trois goroutines simultanées. Les nombres seront incrémentés
|
||||||
|
// simultanément, peut-être en paralèle si la machine le permet et configurée
|
||||||
|
// correctement. Les trois utilisent le même canal.
|
||||||
|
go inc(0, c) // go est une instruction démarrant une nouvelle goroutine.
|
||||||
|
go inc(10, c)
|
||||||
|
go inc(-805, c)
|
||||||
|
// Lis et affiche trois résultats du canal - impossible de savoir dans quel
|
||||||
|
// ordre !
|
||||||
|
fmt.Println(<-c, <-c, <-c) // Canal à droite, <- est l'opérateur de
|
||||||
|
// "réception".
|
||||||
|
|
||||||
|
cs := make(chan string) // Un autre canal, celui-ci gère des chaînes.
|
||||||
|
ccs := make(chan chan string) // Un canal de canaux de chaînes.
|
||||||
|
go func() { c <- 84 }() // Démarre une nouvelle goroutine, pour
|
||||||
|
// envoyer une valeur.
|
||||||
|
go func() { cs <- "wordy" }() // De nouveau, pour cs cette fois-ci.
|
||||||
|
// Select possède une syntaxe similaire au switch, mais chaque cas requiert
|
||||||
|
// une opération impliquant un canal. Il sélectionne un cas aléatoirement
|
||||||
|
// prêt à communiquer.
|
||||||
|
select {
|
||||||
|
case i := <-c: // La valeur reçue peut être assignée à une variable,
|
||||||
|
fmt.Printf("c'est un %T", i)
|
||||||
|
case <-cs: // ou la valeur reçue peut être ignorée.
|
||||||
|
fmt.Println("c'est une chaîne")
|
||||||
|
case <-ccs: // Un canal vide, indisponible à la communication.
|
||||||
|
fmt.Println("ne surviendra pas.")
|
||||||
|
}
|
||||||
|
// À ce point, une valeur a été prise de c ou cs. L'une des deux goroutines
|
||||||
|
// démarrée plus haut a complétée, la seconde restera bloquée.
|
||||||
|
|
||||||
|
learnWebProgramming() // Go permet la programmation Web.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Une seule fonction du paquet http démarre un serveur Web.
|
||||||
|
func learnWebProgramming() {
|
||||||
|
|
||||||
|
// Le premier paramètre de ListenAndServe est une adresse TCP à écouter.
|
||||||
|
// Le second est une interface, de type http.Handler.
|
||||||
|
go func() {
|
||||||
|
err := http.ListenAndServe(":8080", pair{})
|
||||||
|
fmt.Println(err) // n'ignorez pas les erreurs !
|
||||||
|
}()
|
||||||
|
|
||||||
|
requestServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implémente la méthode ServeHTTP de http.Handler à pair, la rendant compatible
|
||||||
|
// avec les opérations utilisant l'interface http.Handler.
|
||||||
|
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Répondez à une requête à l'aide de la méthode http.ResponseWriter.
|
||||||
|
w.Write([]byte("Vous avez appris Go en Y minutes!"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestServer() {
|
||||||
|
resp, err := http.Get("http://localhost:8080")
|
||||||
|
fmt.Println(err)
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
|
fmt.Printf("\nLe serveur Web a dit: `%s`", string(body))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## En savoir plus
|
||||||
|
|
||||||
|
La référence Go se trouve sur [le site officiel de Go](http://golang.org/).
|
||||||
|
Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus.
|
||||||
|
|
||||||
|
Une lecture de la documentation du langage est grandement conseillée. C'est
|
||||||
|
facile à lire et très court (comparé aux autres langages).
|
||||||
|
|
||||||
|
Vous pouvez exécuter et modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go.
|
||||||
|
|
||||||
|
Sur la liste de lecteur des étudiants de Go se trouve le [code source de la
|
||||||
|
librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre
|
||||||
|
le meilleur de la clarté de Go, le style ainsi que ses expressions. Sinon, vous
|
||||||
|
pouvez cliquer sur le nom d'une fonction dans [la
|
||||||
|
documentation](http://golang.org/pkg/) et le code source apparaît!
|
||||||
|
|
||||||
|
Une autre excellente ressource pour apprendre est [Go par l'exemple](https://gobyexample.com/).
|
@@ -148,7 +148,7 @@ add 1 2 -- 3
|
|||||||
|
|
||||||
-- Guards: an easy way to do branching in functions
|
-- Guards: an easy way to do branching in functions
|
||||||
fib x
|
fib x
|
||||||
| x < 2 = x
|
| x < 2 = 1
|
||||||
| otherwise = fib (x - 1) + fib (x - 2)
|
| otherwise = fib (x - 1) + fib (x - 2)
|
||||||
|
|
||||||
-- Pattern matching is similar. Here we have given three different
|
-- Pattern matching is similar. Here we have given three different
|
||||||
@@ -202,19 +202,20 @@ foo = (*5) . (+10)
|
|||||||
foo 5 -- 75
|
foo 5 -- 75
|
||||||
|
|
||||||
-- fixing precedence
|
-- fixing precedence
|
||||||
-- Haskell has another function called `$`. This changes the precedence
|
-- Haskell has another operator called `$`. This operator applies a function
|
||||||
-- so that everything to the left of it gets computed first and then applied
|
-- to a given parameter. In contrast to standard function application, which
|
||||||
-- to everything on the right. You can use `$` (often in combination with `.`)
|
-- has highest possible priority of 10 and is left-associative, the `$` operator
|
||||||
-- to get rid of a lot of parentheses:
|
-- has priority of 0 and is right-associative. Such a low priority means that
|
||||||
|
-- the expression on its right is applied as the parameter to the function on its left.
|
||||||
|
|
||||||
-- before
|
-- before
|
||||||
(even (fib 7)) -- true
|
(even (fib 7)) -- false
|
||||||
|
|
||||||
-- after
|
-- after
|
||||||
even . fib $ 7 -- true
|
even . fib $ 7 -- false
|
||||||
|
|
||||||
-- equivalently
|
-- equivalently
|
||||||
even $ fib 7 -- true
|
even $ fib 7 -- false
|
||||||
|
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
-- 5. Type signatures
|
-- 5. Type signatures
|
||||||
|
@@ -3,6 +3,7 @@ language: haxe
|
|||||||
filename: LearnHaxe3.hx
|
filename: LearnHaxe3.hx
|
||||||
contributors:
|
contributors:
|
||||||
- ["Justin Donaldson", "https://github.com/jdonaldson/"]
|
- ["Justin Donaldson", "https://github.com/jdonaldson/"]
|
||||||
|
- ["Dan Korostelev", "https://github.com/nadako/"]
|
||||||
---
|
---
|
||||||
|
|
||||||
Haxe is a web-oriented language that provides platform support for C++, C#,
|
Haxe is a web-oriented language that provides platform support for C++, C#,
|
||||||
@@ -34,16 +35,20 @@ references.
|
|||||||
/*
|
/*
|
||||||
This is your first actual haxe code coming up, it's declaring an empty
|
This is your first actual haxe code coming up, it's declaring an empty
|
||||||
package. A package isn't necessary, but it's useful if you want to create a
|
package. A package isn't necessary, but it's useful if you want to create a
|
||||||
namespace for your code (e.g. org.module.ClassName).
|
namespace for your code (e.g. org.yourapp.ClassName).
|
||||||
|
|
||||||
|
Omitting package declaration is the same as declaring an empty package.
|
||||||
*/
|
*/
|
||||||
package; // empty package, no namespace.
|
package; // empty package, no namespace.
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Packages define modules for your code. Each module (e.g. org.module) must
|
Packages are directories that contain modules. Each module is a .hx file
|
||||||
be lower case, and should exist as a folder structure containing the class.
|
that contains types defined in a package. Package names (e.g. org.yourapp)
|
||||||
Class (and type) names must be capitalized. E.g, the class "org.module.Foo"
|
must be lower case while module names are capitalized. A module contain one
|
||||||
should have the folder structure org/module/Foo.hx, as accessible from the
|
or more types whose names are also capitalized.
|
||||||
compiler's working directory or class path.
|
|
||||||
|
E.g, the class "org.yourapp.Foo" should have the folder structure org/module/Foo.hx,
|
||||||
|
as accessible from the compiler's working directory or class path.
|
||||||
|
|
||||||
If you import code from other files, it must be declared before the rest of
|
If you import code from other files, it must be declared before the rest of
|
||||||
the code. Haxe provides a lot of common default classes to get you started:
|
the code. Haxe provides a lot of common default classes to get you started:
|
||||||
@@ -53,6 +58,12 @@ import haxe.ds.ArraySort;
|
|||||||
// you can import many classes/modules at once with "*"
|
// you can import many classes/modules at once with "*"
|
||||||
import haxe.ds.*;
|
import haxe.ds.*;
|
||||||
|
|
||||||
|
// you can import static fields
|
||||||
|
import Lambda.array;
|
||||||
|
|
||||||
|
// you can also use "*" to import all static fields
|
||||||
|
import Math.*;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
You can also import classes in a special way, enabling them to extend the
|
You can also import classes in a special way, enabling them to extend the
|
||||||
functionality of other classes like a "mixin". More on 'using' later.
|
functionality of other classes like a "mixin". More on 'using' later.
|
||||||
@@ -172,7 +183,8 @@ class LearnHaxe3{
|
|||||||
Regexes are also supported, but there's not enough space to go into
|
Regexes are also supported, but there's not enough space to go into
|
||||||
much detail.
|
much detail.
|
||||||
*/
|
*/
|
||||||
trace((~/foobar/.match('foo')) + " is the value for (~/foobar/.match('foo')))");
|
var re = ~/foobar/;
|
||||||
|
trace(re.match('foo') + " is the value for (~/foobar/.match('foo')))");
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Arrays are zero-indexed, dynamic, and mutable. Missing values are
|
Arrays are zero-indexed, dynamic, and mutable. Missing values are
|
||||||
@@ -383,11 +395,7 @@ class LearnHaxe3{
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// if statements
|
// if statements
|
||||||
var k = if (true){
|
var k = if (true) 10 else 20;
|
||||||
10;
|
|
||||||
} else {
|
|
||||||
20;
|
|
||||||
}
|
|
||||||
|
|
||||||
trace("K equals ", k); // outputs 10
|
trace("K equals ", k); // outputs 10
|
||||||
|
|
||||||
@@ -628,6 +636,7 @@ enum ComplexEnum{
|
|||||||
ComplexEnumEnum(c:ComplexEnum);
|
ComplexEnumEnum(c:ComplexEnum);
|
||||||
}
|
}
|
||||||
// Note: The enum above can include *other* enums as well, including itself!
|
// Note: The enum above can include *other* enums as well, including itself!
|
||||||
|
// Note: This is what's called *Algebraic data type* in some other languages.
|
||||||
|
|
||||||
class ComplexEnumTest{
|
class ComplexEnumTest{
|
||||||
public static function example(){
|
public static function example(){
|
||||||
|
@@ -103,15 +103,15 @@ public class LearnJava {
|
|||||||
// Arrays
|
// Arrays
|
||||||
//The array size must be decided upon instantiation
|
//The array size must be decided upon instantiation
|
||||||
//The following formats work for declaring an array
|
//The following formats work for declaring an array
|
||||||
//<datatype> [] <var name> = new <datatype>[<array size>];
|
//<datatype>[] <var name> = new <datatype>[<array size>];
|
||||||
//<datatype> <var name>[] = new <datatype>[<array size>];
|
//<datatype> <var name>[] = new <datatype>[<array size>];
|
||||||
int [] intArray = new int[10];
|
int[] intArray = new int[10];
|
||||||
String [] stringArray = new String[1];
|
String[] stringArray = new String[1];
|
||||||
boolean boolArray [] = new boolean[100];
|
boolean boolArray[] = new boolean[100];
|
||||||
|
|
||||||
// Another way to declare & initialize an array
|
// Another way to declare & initialize an array
|
||||||
int [] y = {9000, 1000, 1337};
|
int[] y = {9000, 1000, 1337};
|
||||||
String names [] = {"Bob", "John", "Fred", "Juan Pedro"};
|
String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
|
||||||
boolean bools[] = new boolean[] {true, false, false};
|
boolean bools[] = new boolean[] {true, false, false};
|
||||||
|
|
||||||
// Indexing an array - Accessing an element
|
// Indexing an array - Accessing an element
|
||||||
|
@@ -253,7 +253,9 @@ given "foo bar" {
|
|||||||
when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True,
|
when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True,
|
||||||
# so you can also put "normal" conditionals.
|
# so you can also put "normal" conditionals.
|
||||||
# This when is equivalent to this `if`:
|
# This when is equivalent to this `if`:
|
||||||
# if ($_.chars > 50) ~~ True {...}
|
# if $_ ~~ ($_.chars > 50) {...}
|
||||||
|
# Which means:
|
||||||
|
# if $_.chars > 50 {...}
|
||||||
say "Quite a long string !";
|
say "Quite a long string !";
|
||||||
}
|
}
|
||||||
default { # same as `when *` (using the Whatever Star)
|
default { # same as `when *` (using the Whatever Star)
|
||||||
@@ -560,7 +562,7 @@ subset VeryBigInteger of Int where * > 500;
|
|||||||
multi sub sayit(Int $n) { # note the `multi` keyword here
|
multi sub sayit(Int $n) { # note the `multi` keyword here
|
||||||
say "Number: $n";
|
say "Number: $n";
|
||||||
}
|
}
|
||||||
multi sayit(Str $s) } # a multi is a `sub` by default
|
multi sayit(Str $s) { # a multi is a `sub` by default
|
||||||
say "String: $s";
|
say "String: $s";
|
||||||
}
|
}
|
||||||
sayit("foo"); # prints "String: foo"
|
sayit("foo"); # prints "String: foo"
|
||||||
@@ -963,7 +965,7 @@ say join ',', gather if False {
|
|||||||
# But consider:
|
# But consider:
|
||||||
constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything
|
constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything
|
||||||
# versus:
|
# versus:
|
||||||
constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 3 4
|
constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2
|
||||||
|
|
||||||
# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)
|
# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)
|
||||||
# Not yet implemented !!
|
# Not yet implemented !!
|
||||||
|
84
pt-br/brainfuck-pt.html.markdown
Normal file
84
pt-br/brainfuck-pt.html.markdown
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
---
|
||||||
|
language: brainfuck
|
||||||
|
contributors:
|
||||||
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||||
|
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||||
|
translators:
|
||||||
|
- ["Suzane Sant Ana", "http://github.com/suuuzi"]
|
||||||
|
lang: pt-br
|
||||||
|
---
|
||||||
|
|
||||||
|
Brainfuck (em letras minúsculas, eceto no início de frases) é uma linguagem de
|
||||||
|
programação Turing-completa extremamente simples com apenas 8 comandos.
|
||||||
|
|
||||||
|
```
|
||||||
|
Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado.
|
||||||
|
|
||||||
|
Brainfuck é representado por um vetor com 30 000 células inicializadas em zero
|
||||||
|
e um ponteiro de dados que aponta para a célula atual.
|
||||||
|
|
||||||
|
Existem 8 comandos:
|
||||||
|
+ : Incrementa o vaor da célula atual em 1.
|
||||||
|
- : Decrementa o valor da célula atual em 1.
|
||||||
|
> : Move o ponteiro de dados para a célula seguinte (célula à direita).
|
||||||
|
< : Move o ponteiro de dados para a célula anterior (célula à esquerda).
|
||||||
|
. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A').
|
||||||
|
, : Lê um único caractere para a célula atual.
|
||||||
|
[ : Se o valor da célula atual for zero, salta para o ] correspondente.
|
||||||
|
Caso contrário, passa para a instrução seguinte.
|
||||||
|
] : Se o valor da célula atual for zero, passa para a instrução seguinte.
|
||||||
|
Caso contrário, volta para a instrução relativa ao [ correspondente.
|
||||||
|
|
||||||
|
[ e ] formam um ciclo while. Obviamente, devem ser equilibrados.
|
||||||
|
|
||||||
|
Vamos ver alguns exemplos básicos em brainfuck:
|
||||||
|
|
||||||
|
++++++ [ > ++++++++++ < - ] > +++++ .
|
||||||
|
|
||||||
|
Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6.
|
||||||
|
A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se
|
||||||
|
o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10
|
||||||
|
vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se
|
||||||
|
a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para
|
||||||
|
a célula #1 chegar a 0, momento em que se salta para o ] correspondente,
|
||||||
|
continuando com a instrução seguinte).
|
||||||
|
|
||||||
|
Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2
|
||||||
|
tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5
|
||||||
|
vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor
|
||||||
|
65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal.
|
||||||
|
|
||||||
|
, [ > + < - ] > .
|
||||||
|
|
||||||
|
Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é
|
||||||
|
iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na
|
||||||
|
célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente
|
||||||
|
decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser
|
||||||
|
igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de
|
||||||
|
dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a
|
||||||
|
célula #2 e imprimimos o valor em ASCII.
|
||||||
|
|
||||||
|
Os espaços servem apenas para tornar o programa mais legível. Podemos escrever
|
||||||
|
o mesmo programa da seguinte maneira:
|
||||||
|
|
||||||
|
,[>+<-]>.
|
||||||
|
|
||||||
|
Tente descobrir o que este programa faz:
|
||||||
|
|
||||||
|
,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
|
||||||
|
|
||||||
|
Este programa lê dois números e os multiplica.
|
||||||
|
|
||||||
|
Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um
|
||||||
|
ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados
|
||||||
|
para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula
|
||||||
|
#2, incrementando o valor da célula #3. Porém existe um problema, no final do
|
||||||
|
ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da
|
||||||
|
célula #4 é também incrementado e copiado para a célula #2.
|
||||||
|
```
|
||||||
|
|
||||||
|
E isto é brainfuck. Simples, não? Por divertimento você pode escrever os
|
||||||
|
seus próprios programas em brainfuck, ou então escrever um interpretador de
|
||||||
|
brainfuck em outra linguagem. O interpretador é relativamente fácil de se
|
||||||
|
implementar, mas caso você seja masoquista, tente escrever um interpretador de
|
||||||
|
brainfuck… em brainfuck.
|
@@ -1,110 +1,119 @@
|
|||||||
---
|
---
|
||||||
category: tool
|
category: tool
|
||||||
tool: git
|
tool: git
|
||||||
|
lang: pt-br
|
||||||
|
filename: LearnGit.txt
|
||||||
contributors:
|
contributors:
|
||||||
- ["Jake Prather", "http://github.com/JakeHP"]
|
- ["Jake Prather", "http://github.com/JakeHP"]
|
||||||
translators:
|
translators:
|
||||||
- ["Miguel Araújo", "https://github.com/miguelarauj1o"]
|
- ["Suzane Sant Ana", "http://github.com/suuuzi"]
|
||||||
lang: pt-br
|
|
||||||
filename: learngit-pt.txt
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Git é um sistema de controle de versão distribuído e de gerenciamento de código-fonte.
|
Git é um sistema distribuido de gestão para código fonte e controle de versões.
|
||||||
|
|
||||||
Ele faz isso através de uma série de momentos instantâneos de seu projeto, e ele funciona
|
Funciona através de uma série de registos de estado do projeto e usa esse
|
||||||
com esses momentos para lhe fornecer a funcionalidade para a versão e
|
registo para permitir funcionalidades de versionamento e gestão de código
|
||||||
gerenciar o seu código-fonte.
|
fonte.
|
||||||
|
|
||||||
## Versionando Conceitos
|
## Conceitos de versionamento
|
||||||
|
|
||||||
### O que é controle de versão?
|
### O que é controle de versão
|
||||||
|
|
||||||
O controle de versão é um sistema que registra alterações em um arquivo ou conjunto
|
Controle de versão (*source control*) é um processo de registo de alterações
|
||||||
de arquivos, ao longo do tempo.
|
a um arquivo ou conjunto de arquivos ao longo do tempo.
|
||||||
|
|
||||||
### Versionamento Centralizado VS Versionamento Distribuído
|
### Controle de versão: Centralizado VS Distribuído
|
||||||
|
|
||||||
* Controle de versão centralizado concentra-se na sincronização, controle e backup de arquivos.
|
* Controle de versão centralizado foca na sincronização, registo e *backup*
|
||||||
* Controle de versão distribuído concentra-se na partilha de mudanças. Toda mudança tem um ID único.
|
de arquivos.
|
||||||
* Sistemas Distribuídos não têm estrutura definida. Você poderia facilmente ter um estilo SVN,
|
* Controle de versão distribuído foca em compartilhar alterações. Cada
|
||||||
sistema centralizado, com git.
|
alteração é associada a um *id* único.
|
||||||
|
* Sistemas distribuídos não tem estrutura definida. É possivel ter um sistema
|
||||||
|
centralizado ao estilo SVN usando git.
|
||||||
|
|
||||||
[Informação Adicional](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
|
[Informação adicional (EN)](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
|
||||||
|
|
||||||
### Porque usar o Git?
|
### Por que usar git?
|
||||||
|
|
||||||
* Possibilidade de trabalhar offline
|
* Permite trabalhar offline.
|
||||||
* Colaborar com os outros é fácil!
|
* Colaborar com outros é fácil!
|
||||||
* Ramificação é fácil
|
* Criar *branches* é fácil!
|
||||||
* Mesclagem é fácil
|
* Fazer *merge* é fácil!
|
||||||
* Git é rápido
|
* Git é rápido.
|
||||||
* Git é flexível.
|
* Git é flexivel.
|
||||||
|
|
||||||
|
## Git - Arquitetura
|
||||||
|
|
||||||
## Arquitetura Git
|
|
||||||
|
|
||||||
### Repositório
|
### Repositório
|
||||||
|
|
||||||
Um conjunto de arquivos, diretórios, registros históricos, cometes, e cabeças. Imagine-o
|
Um conjunto de arquivos, diretórios, registos históricos, *commits* e
|
||||||
como uma estrutura de dados de código-fonte, com o atributo que cada "elemento" do
|
referências. Pode ser descrito como uma estrutura de dados de código fonte
|
||||||
código-fonte dá-lhe acesso ao seu histórico de revisão, entre outras coisas.
|
com a particularidade de cada elemento do código fonte permitir acesso ao
|
||||||
|
histórico das suas alterações, entre outras coisas.
|
||||||
|
|
||||||
Um repositório git é composto do diretório git. e árvore de trabalho.
|
Um repositório git é constituido pelo diretório .git e a *working tree*
|
||||||
|
|
||||||
### Diretório .git (componente do repositório)
|
### Diretório .git (componente do repositório)
|
||||||
|
|
||||||
O diretório git. contém todas as configurações, registros, galhos, cabeça(HEAD) e muito mais.
|
O repositório .git contém todas as configurações, *logs*, *branches*,
|
||||||
[Lista Detalhada](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
|
referências e outros.
|
||||||
|
|
||||||
### Árvore de trabalho (componente do repositório)
|
[Lista detalhada (EN)](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
|
||||||
|
|
||||||
Esta é, basicamente, os diretórios e arquivos no seu repositório. Ele é muitas vezes referida
|
### *Working Tree* (componente do repositório)
|
||||||
como seu diretório de trabalho.
|
|
||||||
|
|
||||||
### Índice (componente do diretório .git)
|
A *Working Tree* é basicamente a listagem dos diretórios e arquivos do repositório. É chamada também de diretório do projeto.
|
||||||
|
|
||||||
O Índice é a área de teste no git. É basicamente uma camada que separa a sua árvore de trabalho
|
### *Index* (componente do diretório .git)
|
||||||
a partir do repositório Git. Isso dá aos desenvolvedores mais poder sobre o que é enviado para o
|
|
||||||
repositório Git.
|
|
||||||
|
|
||||||
### Comete (commit)
|
O *Index* é a camada da interface no git. É o elemento que separa
|
||||||
|
o diretório do projeto do repositório git. Isto permite aos programadores um
|
||||||
|
maior controle sobre o que é registado no repositório git.
|
||||||
|
|
||||||
A commit git é um instantâneo de um conjunto de alterações ou manipulações a sua árvore de trabalho.
|
### *Commit*
|
||||||
Por exemplo, se você adicionou 5 imagens, e removeu outros dois, estas mudanças serão contidas
|
|
||||||
em um commit (ou instantâneo). Esta confirmação pode ser empurrado para outros repositórios, ou não!
|
|
||||||
|
|
||||||
### Ramo (branch)
|
Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos arquivos do projeto.
|
||||||
|
Por exemplo, ao adicionar cinco arquivos e remover outros 2, estas alterações
|
||||||
|
serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado
|
||||||
|
para outros repositórios ou não!
|
||||||
|
|
||||||
Um ramo é, essencialmente, um ponteiro que aponta para o último commit que você fez. Como
|
### *Branch*
|
||||||
você se comprometer, este ponteiro irá atualizar automaticamente e apontar para o último commit.
|
|
||||||
|
|
||||||
### Cabeça (HEAD) e cabeça (head) (componente do diretório .git)
|
Um *branch* é essencialmente uma referência que aponta para o último *commit*
|
||||||
|
efetuado. Na medida que são feitos novos commits, esta referência é atualizada
|
||||||
|
automaticamente e passa a apontar para o commit mais recente.
|
||||||
|
|
||||||
HEAD é um ponteiro que aponta para o ramo atual. Um repositório tem apenas 1 * ativo * HEAD.
|
### *HEAD* e *head* (componentes do diretório .git)
|
||||||
head é um ponteiro que aponta para qualquer commit. Um repositório pode ter qualquer número de commits.
|
|
||||||
|
|
||||||
### Recursos Conceituais
|
*HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem
|
||||||
|
uma *HEAD* activa.
|
||||||
|
*head* é uma referência que aponta para qualquer *commit*. Um repositório pode
|
||||||
|
ter um número indefinido de *heads*
|
||||||
|
|
||||||
* [Git para Cientistas da Computação](http://eagain.net/articles/git-for-computer-scientists/)
|
### Recursos conceituais (EN)
|
||||||
|
|
||||||
|
* [Git para Cientistas de Computação](http://eagain.net/articles/git-for-computer-scientists/)
|
||||||
* [Git para Designers](http://hoth.entp.com/output/git_for_designers.html)
|
* [Git para Designers](http://hoth.entp.com/output/git_for_designers.html)
|
||||||
|
|
||||||
## Comandos
|
## Comandos
|
||||||
|
|
||||||
### init
|
### *init*
|
||||||
|
|
||||||
Criar um repositório Git vazio. As configurações do repositório Git, informações armazenadas,
|
Cria um repositório Git vazio. As definições, informação guardada e outros do
|
||||||
e mais são armazenados em um diretório (pasta) com o nome ". git".
|
repositório git são guardados em uma pasta chamada ".git".
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ git init
|
$ git init
|
||||||
```
|
```
|
||||||
|
|
||||||
### config
|
### *config*
|
||||||
|
|
||||||
Para configurar as definições. Quer seja para o repositório, o próprio sistema, ou
|
Permite configurar as definições, sejam as definições do repositório, sistema
|
||||||
configurações globais.
|
ou configurações globais.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Impressão e definir algumas variáveis de configuração básica (global)
|
# Imprime e define algumas variáveis de configuração básicas (global)
|
||||||
$ git config --global user.email
|
$ git config --global user.email
|
||||||
$ git config --global user.name
|
$ git config --global user.name
|
||||||
|
|
||||||
@@ -112,22 +121,21 @@ $ git config --global user.email "MyEmail@Zoho.com"
|
|||||||
$ git config --global user.name "My Name"
|
$ git config --global user.name "My Name"
|
||||||
```
|
```
|
||||||
|
|
||||||
[Saiba mais sobre o git config.](http://git-scm.com/docs/git-config)
|
[Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config)
|
||||||
|
|
||||||
### help
|
### help
|
||||||
|
|
||||||
Para lhe dar um acesso rápido a um guia extremamente detalhada de cada comando. ou
|
Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da semântica.
|
||||||
apenas dar-lhe um rápido lembrete de algumas semânticas.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Rapidamente verificar os comandos disponíveis
|
# Ver rapidamente os comandos disponiveis
|
||||||
$ git help
|
$ git help
|
||||||
|
|
||||||
# Confira todos os comandos disponíveis
|
# Ver todos os comandos disponiveis
|
||||||
$ git help -a
|
$ git help -a
|
||||||
|
|
||||||
# Ajuda específica de comando - manual do usuário
|
# Usar o *help* para um comando especifico
|
||||||
# git help <command_here>
|
# git help <comando_aqui>
|
||||||
$ git help add
|
$ git help add
|
||||||
$ git help commit
|
$ git help commit
|
||||||
$ git help init
|
$ git help init
|
||||||
@@ -135,85 +143,89 @@ $ git help init
|
|||||||
|
|
||||||
### status
|
### status
|
||||||
|
|
||||||
Para mostrar as diferenças entre o arquivo de índice (basicamente o trabalho de
|
Apresenta as diferenças entre o arquivo *index* (a versão corrente
|
||||||
copiar/repo) e a HEAD commit corrente.
|
do repositório) e o *commit* da *HEAD* atual.
|
||||||
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Irá exibir o ramo, os arquivos não monitorados, as alterações e outras diferenças
|
# Apresenta o *branch*, arquivos não monitorados, alterações e outras
|
||||||
|
# difereças
|
||||||
$ git status
|
$ git status
|
||||||
|
|
||||||
# Para saber outras "tid bits" sobre git status
|
# Para aprender mais detalhes sobre git *status*
|
||||||
$ git help status
|
$ git help status
|
||||||
```
|
```
|
||||||
|
|
||||||
### add
|
### add
|
||||||
|
|
||||||
Para adicionar arquivos para a atual árvore/directory/repo trabalho. Se você não
|
Adiciona arquivos ao repositório corrente. Se os arquivos novos não forem
|
||||||
der `git add` nos novos arquivos para o trabalhando árvore/diretório, eles não serão
|
adicionados através de `git add` ao repositório, então eles não serão
|
||||||
incluídos em commits!
|
incluidos nos commits!
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Adicionar um arquivo no seu diretório de trabalho atual
|
# adiciona um arquivo no diretório do projeto atual
|
||||||
$ git add HelloWorld.java
|
$ git add HelloWorld.java
|
||||||
|
|
||||||
# Adicionar um arquivo em um diretório aninhado
|
# adiciona um arquivo num sub-diretório
|
||||||
$ git add /path/to/file/HelloWorld.c
|
$ git add /path/to/file/HelloWorld.c
|
||||||
|
|
||||||
# Suporte a expressões regulares!
|
# permite usar expressões regulares!
|
||||||
$ git add ./*.java
|
$ git add ./*.java
|
||||||
```
|
```
|
||||||
|
|
||||||
### branch
|
### branch
|
||||||
|
|
||||||
Gerenciar seus ramos. Você pode visualizar, editar, criar, apagar ramos usando este comando.
|
Gerencia os *branches*. É possível ver, editar, criar e apagar branches com este
|
||||||
|
comando.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Lista ramos e controles remotos existentes
|
# listar *branches* existentes e remotos
|
||||||
$ git branch -a
|
$ git branch -a
|
||||||
|
|
||||||
# Criar um novo ramo
|
# criar um novo *branch*
|
||||||
$ git branch myNewBranch
|
$ git branch myNewBranch
|
||||||
|
|
||||||
# Apagar um ramo
|
# apagar um *branch*
|
||||||
$ git branch -d myBranch
|
$ git branch -d myBranch
|
||||||
|
|
||||||
# Renomear um ramo
|
# alterar o nome de um *branch*
|
||||||
# git branch -m <oldname> <newname>
|
# git branch -m <oldname> <newname>
|
||||||
$ git branch -m myBranchName myNewBranchName
|
$ git branch -m myBranchName myNewBranchName
|
||||||
|
|
||||||
# Editar a descrição de um ramo
|
# editar a descrição de um *branch*
|
||||||
$ git branch myBranchName --edit-description
|
$ git branch myBranchName --edit-description
|
||||||
```
|
```
|
||||||
|
|
||||||
### checkout
|
### checkout
|
||||||
|
|
||||||
Atualiza todos os arquivos na árvore de trabalho para corresponder à versão no
|
Atualiza todos os arquivos no diretório do projeto para que fiquem iguais
|
||||||
índice, ou árvore especificada.
|
à versão do index ou do *branch* especificado.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Finalizar um repo - padrão de ramo mestre
|
# Checkout de um repositório - por padrão para o branch master
|
||||||
$ git checkout
|
$ git checkout
|
||||||
# Checa um ramo especificado
|
# Checkout de um branch especifico
|
||||||
$ git checkout branchName
|
$ git checkout branchName
|
||||||
# Criar um novo ramo e mudar para ela, como: "<nome> git branch; git checkout <nome>"
|
# Cria um novo branch e faz checkout para ele.
|
||||||
|
# Equivalente a: "git branch <name>; git checkout <name>"
|
||||||
$ git checkout -b newBranch
|
$ git checkout -b newBranch
|
||||||
```
|
```
|
||||||
|
|
||||||
### clone
|
### clone
|
||||||
|
|
||||||
Clones, ou cópias, de um repositório existente para um novo diretório. Ele também adiciona
|
Clona ou copia um repositório existente para um novo diretório. Também
|
||||||
filiais remotas de rastreamento para cada ramo no repo clonado, que permite que você empurre
|
adiciona *branches* de monitoramento remoto para cada *branch* no repositório
|
||||||
a um ramo remoto.
|
clonado o que permite enviar alterações para um *branch* remoto.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Clone learnxinyminutes-docs
|
# Clona learnxinyminutes-docs
|
||||||
$ git clone https://github.com/adambard/learnxinyminutes-docs.git
|
$ git clone https://github.com/adambard/learnxinyminutes-docs.git
|
||||||
```
|
```
|
||||||
|
|
||||||
### commit
|
### commit
|
||||||
|
|
||||||
Armazena o conteúdo atual do índice em um novo "commit". Este commit contém
|
Guarda o conteudo atual do index num novo *commit*. Este *commit* contém
|
||||||
as alterações feitas e uma mensagem criada pelo utilizador.
|
as alterações feitas e a mensagem criada pelo usuário.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# commit com uma mensagem
|
# commit com uma mensagem
|
||||||
@@ -222,170 +234,170 @@ $ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
|
|||||||
|
|
||||||
### diff
|
### diff
|
||||||
|
|
||||||
Mostra as diferenças entre um arquivo no diretório, o índice de trabalho e commits.
|
Apresenta as diferenças entre um arquivo no repositório do projeto, *index*
|
||||||
|
e *commits*
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Mostrar diferença entre o seu diretório de trabalho e o índice.
|
# Apresenta a diferença entre o diretório atual e o index
|
||||||
$ git diff
|
$ git diff
|
||||||
|
|
||||||
# Mostrar diferenças entre o índice e o commit mais recente.
|
# Apresenta a diferença entre o index e os commits mais recentes
|
||||||
$ git diff --cached
|
$ git diff --cached
|
||||||
|
|
||||||
# Mostrar diferenças entre o seu diretório de trabalho e o commit mais recente.
|
# Apresenta a diferença entre o diretório atual e o commit mais recente
|
||||||
$ git diff HEAD
|
$ git diff HEAD
|
||||||
```
|
```
|
||||||
|
|
||||||
### grep
|
### grep
|
||||||
|
|
||||||
Permite procurar rapidamente um repositório.
|
Permite procurar facilmente num repositório
|
||||||
|
|
||||||
Configurações opcionais:
|
Configurações opcionais:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Obrigado ao Travis Jeffery por isto
|
# Define a apresentação de números de linha nos resultados do grep
|
||||||
# Configure os números de linha a serem mostrados nos resultados de busca grep
|
|
||||||
$ git config --global grep.lineNumber true
|
$ git config --global grep.lineNumber true
|
||||||
|
|
||||||
# Fazer resultados de pesquisa mais legível, incluindo agrupamento
|
# Agrupa os resultados da pesquisa para facilitar a leitura
|
||||||
$ git config --global alias.g "grep --break --heading --line-number"
|
$ git config --global alias.g "grep --break --heading --line-number"
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Procure por "variableName" em todos os arquivos java
|
# Pesquisa por "variableName" em todos os arquivos java
|
||||||
$ git grep 'variableName' -- '*.java'
|
$ git grep 'variableName' -- '*.java'
|
||||||
|
|
||||||
# Procure por uma linha que contém "arrayListName" e "adicionar" ou "remover"
|
# Pesquisa por uma linha que contém "arrayListName" e "add" ou "remove"
|
||||||
$ git grep -e 'arrayListName' --and \( -e add -e remove \)
|
$ git grep -e 'arrayListName' --and \( -e add -e remove \)
|
||||||
```
|
```
|
||||||
|
|
||||||
Google é seu amigo; para mais exemplos
|
O Google é seu amigo; para mais exemplos:
|
||||||
[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
|
[Git Grep Ninja (EN)](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
|
||||||
|
|
||||||
### log
|
### log
|
||||||
|
|
||||||
Mostrar commits para o repositório.
|
Apresenta commits do repositório.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Mostrar todos os commits
|
# Apresenta todos os commits
|
||||||
$ git log
|
$ git log
|
||||||
|
|
||||||
# Mostrar um número X de commits
|
# Apresenta X commits
|
||||||
$ git log -n 10
|
$ git log -n 10
|
||||||
|
|
||||||
# Mostrar somente commits mesclados
|
# Apresenta apenas commits de merge
|
||||||
$ git log --merges
|
$ git log --merges
|
||||||
```
|
```
|
||||||
|
|
||||||
### merge
|
### merge
|
||||||
|
|
||||||
"Merge" em mudanças de commits externos no branch atual.
|
"Merge" junta as alterações de commits externos com o *branch* atual.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Mesclar o ramo especificado para o atual.
|
# Junta o branch especificado com o atual
|
||||||
$ git merge branchName
|
$ git merge branchName
|
||||||
|
|
||||||
# Gera sempre uma mesclagem commit ao mesclar
|
# Para gerar sempre um commit ao juntar os branches
|
||||||
$ git merge --no-ff branchName
|
$ git merge --no-ff branchName
|
||||||
```
|
```
|
||||||
|
|
||||||
### mv
|
### mv
|
||||||
|
|
||||||
Renomear ou mover um arquivo
|
Alterar o nome ou mover um arquivo.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Renomear um arquivo
|
# Alterar o nome de um arquivo
|
||||||
$ git mv HelloWorld.c HelloNewWorld.c
|
$ git mv HelloWorld.c HelloNewWorld.c
|
||||||
|
|
||||||
# Mover um arquivo
|
# Mover um arquivo
|
||||||
$ git mv HelloWorld.c ./new/path/HelloWorld.c
|
$ git mv HelloWorld.c ./new/path/HelloWorld.c
|
||||||
|
|
||||||
# Força renomear ou mover
|
# Forçar a alteração de nome ou mudança local
|
||||||
# "ExistingFile" já existe no diretório, será substituído
|
# "existingFile" já existe no directório, será sobrescrito.
|
||||||
$ git mv -f myFile existingFile
|
$ git mv -f myFile existingFile
|
||||||
```
|
```
|
||||||
|
|
||||||
### pull
|
### pull
|
||||||
|
|
||||||
Puxa de um repositório e se funde com outro ramo.
|
Puxa alterações de um repositório e as junta com outro branch
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Atualize seu repo local, através da fusão de novas mudanças
|
# Atualiza o repositório local, juntando as novas alterações
|
||||||
# A partir da "origem" remoto e ramo "master (mestre)".
|
# do repositório remoto 'origin' e branch 'master'
|
||||||
# git pull <remote> <branch>
|
# git pull <remote> <branch>
|
||||||
# git pull => implícito por padrão => git pull origin master
|
# git pull => aplica a predefinição => git pull origin master
|
||||||
$ git pull origin master
|
$ git pull origin master
|
||||||
|
|
||||||
# Mesclar em mudanças de ramo remoto e rebase
|
# Juntar alterações do branch remote e fazer rebase commits do branch
|
||||||
# Ramo commita em seu repo local, como: "git pull <remote> <branch>, git rebase <branch>"
|
# no repositório local, como: "git pull <remote> <branch>, git rebase <branch>"
|
||||||
$ git pull origin master --rebase
|
$ git pull origin master --rebase
|
||||||
```
|
```
|
||||||
|
|
||||||
### push
|
### push
|
||||||
|
|
||||||
Empurre e mesclar as alterações de uma ramificação para uma remota e ramo.
|
Enviar e juntar alterações de um branch para o seu branch correspondente
|
||||||
|
num repositório remoto.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Pressione e mesclar as alterações de um repo local para um
|
# Envia e junta as alterações de um repositório local
|
||||||
# Chamado remoto "origem" e ramo de "mestre".
|
# para um remoto denominado "origin" no branch "master".
|
||||||
# git push <remote> <branch>
|
# git push <remote> <branch>
|
||||||
# git push => implícito por padrão => git push origin master
|
# git push => aplica a predefinição => git push origin master
|
||||||
$ git push origin master
|
$ git push origin master
|
||||||
|
|
||||||
# Para ligar atual filial local com uma filial remota, bandeira add-u:
|
|
||||||
$ git push -u origin master
|
|
||||||
# Agora, a qualquer hora que você quer empurrar a partir desse mesmo ramo local, uso de atalho:
|
|
||||||
$ git push
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### rebase (CAUTELA)
|
### rebase (cautela!)
|
||||||
|
|
||||||
Tire todas as alterações que foram commitadas em um ramo, e reproduzi-las em outro ramo.
|
Pega em todas as alterações que foram registadas num branch e volta a
|
||||||
* Não rebase commits que você tenha empurrado a um repo público *.
|
aplicá-las em outro branch.
|
||||||
|
*Não deve ser feito rebase de commits que foram enviados para um repositório
|
||||||
|
público*
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Rebase experimentBranch para mestre
|
# Faz Rebase de experimentBranch para master
|
||||||
# git rebase <basebranch> <topicbranch>
|
# git rebase <basebranch> <topicbranch>
|
||||||
$ git rebase master experimentBranch
|
$ git rebase master experimentBranch
|
||||||
```
|
```
|
||||||
|
|
||||||
[Leitura Adicional.](http://git-scm.com/book/en/Git-Branching-Rebasing)
|
[Leitura adicional (EN).](http://git-scm.com/book/en/Git-Branching-Rebasing)
|
||||||
|
|
||||||
### reset (CAUTELA)
|
### reset (cuidado!)
|
||||||
|
|
||||||
Repor o atual HEAD de estado especificado. Isto permite-lhe desfazer fusões (merge),
|
Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*,
|
||||||
puxa (push), commits, acrescenta (add), e muito mais. É um grande comando, mas também
|
*pulls*, *commits*, *adds* e outros. É um comando muito poderoso mas também
|
||||||
perigoso se não saber o que se está fazendo.
|
perigoso quando não há certeza do que se está fazendo.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Repor a área de teste, para coincidir com o último commit (deixa diretório inalterado)
|
# Restabelece a camada intermediária de registo para o último
|
||||||
|
# commit (o directório fica sem alterações)
|
||||||
$ git reset
|
$ git reset
|
||||||
|
|
||||||
# Repor a área de teste, para coincidir com o último commit, e substituir diretório trabalhado
|
# Restabelece a camada intermediária de registo para o último commit, e
|
||||||
|
# sobrescreve o projeto atual
|
||||||
$ git reset --hard
|
$ git reset --hard
|
||||||
|
|
||||||
# Move a ponta ramo atual para o especificado commit (deixa diretório inalterado)
|
# Move a head do branch atual para o commit especificado, sem alterar o projeto.
|
||||||
# Todas as alterações ainda existem no diretório.
|
# todas as alterações ainda existem no projeto
|
||||||
$ git reset 31f2bb1
|
$ git reset 31f2bb1
|
||||||
|
|
||||||
# Move a ponta ramo atual para trás, para o commit especificado
|
# Inverte a head do branch atual para o commit especificado
|
||||||
# E faz o jogo dir trabalho (exclui mudanças não commitadas e todos os commits
|
# fazendo com que este esteja em sintonia com o diretório do projeto
|
||||||
# Após o commit especificado).
|
# Remove alterações não registadas e todos os commits após o commit especificado
|
||||||
$ git reset --hard 31f2bb1
|
$ git reset --hard 31f2bb1
|
||||||
```
|
```
|
||||||
|
|
||||||
### rm
|
### rm
|
||||||
|
|
||||||
O oposto do git add, git rm remove arquivos da atual árvore de trabalho.
|
O oposto de git add, git rm remove arquivos do branch atual.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# remove HelloWorld.c
|
# remove HelloWorld.c
|
||||||
$ git rm HelloWorld.c
|
$ git rm HelloWorld.c
|
||||||
|
|
||||||
# Remove um arquivo de um diretório aninhado
|
# Remove um arquivo de um sub-directório
|
||||||
$ git rm /pather/to/the/file/HelloWorld.c
|
$ git rm /pather/to/the/file/HelloWorld.c
|
||||||
```
|
```
|
||||||
|
|
||||||
# # Mais informações
|
## Informação complementar (EN)
|
||||||
|
|
||||||
* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
|
* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
|
||||||
|
|
||||||
@@ -398,5 +410,3 @@ $ git rm /pather/to/the/file/HelloWorld.c
|
|||||||
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
|
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
|
||||||
|
|
||||||
* [GitGuys](http://www.gitguys.com/)
|
* [GitGuys](http://www.gitguys.com/)
|
||||||
|
|
||||||
* [Git - guia prático](http://rogerdudler.github.io/git-guide/index.pt_BR.html)
|
|
@@ -74,8 +74,7 @@ maior controlo sobre o que é registado no repositório git.
|
|||||||
|
|
||||||
### *Commit*
|
### *Commit*
|
||||||
|
|
||||||
Um *commit** de git é um registo de um cojunto de alterações ou manipulações
|
Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos ficheiros do projecto.
|
||||||
no nos ficheiros do projecto.
|
|
||||||
Por exemplo, ao adicionar cinco ficheiros e remover outros 2, estas alterações
|
Por exemplo, ao adicionar cinco ficheiros e remover outros 2, estas alterações
|
||||||
serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado
|
serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado
|
||||||
para outros repositórios ou não!
|
para outros repositórios ou não!
|
||||||
@@ -83,7 +82,7 @@ para outros repositórios ou não!
|
|||||||
### *Branch*
|
### *Branch*
|
||||||
|
|
||||||
Um *branch* é essencialmente uma referência que aponta para o último *commit*
|
Um *branch* é essencialmente uma referência que aponta para o último *commit*
|
||||||
efetuado. à medida que são feitos novos commits, esta referência é atualizada
|
efetuado. À medida que são feitos novos commits, esta referência é atualizada
|
||||||
automaticamente e passa a apontar para o commit mais recente.
|
automaticamente e passa a apontar para o commit mais recente.
|
||||||
|
|
||||||
### *HEAD* e *head* (componentes do directório .git)
|
### *HEAD* e *head* (componentes do directório .git)
|
||||||
@@ -115,7 +114,7 @@ Permite configurar as definições, sejam as definições do repositório, siste
|
|||||||
ou configurações globais.
|
ou configurações globais.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Imprime & Define Algumas Variáveis de Configuração Básicas (Global)
|
# Imprime e define algumas variáveis de configuração básicas (global)
|
||||||
$ git config --global user.email
|
$ git config --global user.email
|
||||||
$ git config --global user.name
|
$ git config --global user.name
|
||||||
|
|
||||||
@@ -123,7 +122,7 @@ $ git config --global user.email "MyEmail@Zoho.com"
|
|||||||
$ git config --global user.name "My Name"
|
$ git config --global user.name "My Name"
|
||||||
```
|
```
|
||||||
|
|
||||||
[Aprenda Mais Sobre git config. (EN)](http://git-scm.com/docs/git-config)
|
[Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config)
|
||||||
|
|
||||||
### help
|
### help
|
||||||
|
|
||||||
@@ -166,7 +165,7 @@ adicionados através de `git add` ao repositório, então eles não serão
|
|||||||
incluidos nos commits!
|
incluidos nos commits!
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# adiciona um ficheiro no directório do project atual
|
# adiciona um ficheiro no directório do projecto atual
|
||||||
$ git add HelloWorld.java
|
$ git add HelloWorld.java
|
||||||
|
|
||||||
# adiciona um ficheiro num sub-directório
|
# adiciona um ficheiro num sub-directório
|
||||||
@@ -371,7 +370,7 @@ Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*,
|
|||||||
perigoso se não há certeza quanto ao que se está a fazer.
|
perigoso se não há certeza quanto ao que se está a fazer.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Restabelece a camada intermediária dr registo para o último
|
# Restabelece a camada intermediária de registo para o último
|
||||||
# commit (o directório fica sem alterações)
|
# commit (o directório fica sem alterações)
|
||||||
$ git reset
|
$ git reset
|
||||||
|
|
||||||
|
@@ -14,7 +14,7 @@ executable pseudocode.
|
|||||||
Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
|
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
|
Note: This article applies to Python 2.7 specifically, but should be applicable
|
||||||
to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial.
|
to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|
||||||
|
@@ -13,7 +13,7 @@ executable pseudocode.
|
|||||||
|
|
||||||
Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
|
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 3 specifically. Check out the other tutorial if you want to learn the old Python 2.7
|
Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|
||||||
@@ -276,7 +276,7 @@ empty_set = set()
|
|||||||
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
|
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
|
||||||
some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
|
some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
|
||||||
|
|
||||||
#Can set new variables to a set
|
# Can set new variables to a set
|
||||||
filled_set = some_set
|
filled_set = some_set
|
||||||
|
|
||||||
# Add one more item to the set
|
# Add one more item to the set
|
||||||
@@ -394,7 +394,6 @@ our_iterator.__next__() # Raises StopIteration
|
|||||||
list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
|
list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
####################################################
|
####################################################
|
||||||
## 4. Functions
|
## 4. Functions
|
||||||
####################################################
|
####################################################
|
||||||
@@ -410,7 +409,6 @@ add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
|
|||||||
# Another way to call functions is with keyword arguments
|
# Another way to call functions is with keyword arguments
|
||||||
add(y=6, x=5) # Keyword arguments can arrive in any order.
|
add(y=6, x=5) # Keyword arguments can arrive in any order.
|
||||||
|
|
||||||
|
|
||||||
# You can define functions that take a variable number of
|
# You can define functions that take a variable number of
|
||||||
# positional arguments
|
# positional arguments
|
||||||
def varargs(*args):
|
def varargs(*args):
|
||||||
@@ -418,7 +416,6 @@ def varargs(*args):
|
|||||||
|
|
||||||
varargs(1, 2, 3) # => (1, 2, 3)
|
varargs(1, 2, 3) # => (1, 2, 3)
|
||||||
|
|
||||||
|
|
||||||
# You can define functions that take a variable number of
|
# You can define functions that take a variable number of
|
||||||
# keyword arguments, as well
|
# keyword arguments, as well
|
||||||
def keyword_args(**kwargs):
|
def keyword_args(**kwargs):
|
||||||
@@ -501,7 +498,9 @@ class Human(object):
|
|||||||
# Basic initializer, this is called when this class is instantiated.
|
# Basic initializer, this is called when this class is instantiated.
|
||||||
# Note that the double leading and trailing underscores denote objects
|
# Note that the double leading and trailing underscores denote objects
|
||||||
# or attributes that are used by python but that live in user-controlled
|
# or attributes that are used by python but that live in user-controlled
|
||||||
# namespaces. You should not invent such names on your own.
|
# namespaces. Methods(or objects or attributes) like: __init__, __str__,
|
||||||
|
# __repr__ etc. are called magic methods (or sometimes called dunder methods)
|
||||||
|
# You should not invent such names on your own.
|
||||||
def __init__(self, name):
|
def __init__(self, name):
|
||||||
# Assign the argument to the instance's name attribute
|
# Assign the argument to the instance's name attribute
|
||||||
self.name = name
|
self.name = name
|
||||||
@@ -636,6 +635,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
|
|||||||
* [The Official Docs](http://docs.python.org/3/)
|
* [The Official Docs](http://docs.python.org/3/)
|
||||||
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
|
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
|
||||||
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
|
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
|
||||||
|
* [Python Course](http://www.python-course.eu/index.php)
|
||||||
|
|
||||||
### Dead Tree
|
### Dead Tree
|
||||||
|
|
||||||
|
@@ -22,8 +22,8 @@ Google Chrome, становится все более популярной.
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
// Си-подобные комментарии. Однострочные комментарии начинаются с двух символов слэш,
|
// Си-подобные комментарии. Однострочные комментарии начинаются с двух символов слэш,
|
||||||
/* а многострочные комментарии начинаются с звёздочка-слэш
|
/* а многострочные комментарии начинаются с последовательности слэш-звёздочка
|
||||||
и заканчиваются символами слэш-звёздочка */
|
и заканчиваются символами звёздочка-слэш */
|
||||||
|
|
||||||
// Инструкции могут заканчиваться точкой с запятой ;
|
// Инструкции могут заканчиваться точкой с запятой ;
|
||||||
doStuff();
|
doStuff();
|
||||||
|
@@ -593,7 +593,7 @@ def double_numbers(iterable):
|
|||||||
range_ = range(1, 900000000)
|
range_ = range(1, 900000000)
|
||||||
|
|
||||||
# Будет удваивать все числа, пока результат не превысит 30
|
# Будет удваивать все числа, пока результат не превысит 30
|
||||||
for i in double_numbers(xrange_):
|
for i in double_numbers(range_):
|
||||||
print(i)
|
print(i)
|
||||||
if i >= 30:
|
if i >= 30:
|
||||||
break
|
break
|
||||||
|
@@ -11,6 +11,7 @@ contributors:
|
|||||||
- ["Ariel Krakowski", "http://www.learneroo.com"]
|
- ["Ariel Krakowski", "http://www.learneroo.com"]
|
||||||
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
|
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
|
||||||
- ["Levi Bostian", "https://github.com/levibostian"]
|
- ["Levi Bostian", "https://github.com/levibostian"]
|
||||||
|
- ["Rahil Momin", "https://github.com/iamrahil"]
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -169,6 +170,9 @@ array[1..3] #=> [2, 3, 4]
|
|||||||
# Add to an array like this
|
# Add to an array like this
|
||||||
array << 6 #=> [1, 2, 3, 4, 5, 6]
|
array << 6 #=> [1, 2, 3, 4, 5, 6]
|
||||||
|
|
||||||
|
# Check if an item exists in an array
|
||||||
|
array.include?(1) #=> true
|
||||||
|
|
||||||
# Hashes are Ruby's primary dictionary with keys/value pairs.
|
# Hashes are Ruby's primary dictionary with keys/value pairs.
|
||||||
# Hashes are denoted with curly braces:
|
# Hashes are denoted with curly braces:
|
||||||
hash = { 'color' => 'green', 'number' => 5 }
|
hash = { 'color' => 'green', 'number' => 5 }
|
||||||
@@ -188,6 +192,10 @@ new_hash = { defcon: 3, action: true }
|
|||||||
|
|
||||||
new_hash.keys #=> [:defcon, :action]
|
new_hash.keys #=> [:defcon, :action]
|
||||||
|
|
||||||
|
# Check existence of keys and values in hash
|
||||||
|
new_hash.has_key?(:defcon) #=> true
|
||||||
|
new_hash.has_value?(3) #=> true
|
||||||
|
|
||||||
# Tip: Both Arrays and Hashes are Enumerable
|
# Tip: Both Arrays and Hashes are Enumerable
|
||||||
# They share a lot of useful methods such as each, map, count, and more
|
# They share a lot of useful methods such as each, map, count, and more
|
||||||
|
|
||||||
|
251
tr-tr/markdown-tr.html.markdown
Normal file
251
tr-tr/markdown-tr.html.markdown
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
---
|
||||||
|
language: markdown
|
||||||
|
contributors:
|
||||||
|
- ["Dan Turkel", "http://danturkel.com/"]
|
||||||
|
translators:
|
||||||
|
- ["Eray AYDIN", "http://erayaydin.me/"]
|
||||||
|
lang: tr-tr
|
||||||
|
filename: markdown-tr.md
|
||||||
|
---
|
||||||
|
|
||||||
|
Markdown, 2004 yılında John Gruber tarafından oluşturuldu. Asıl amacı kolay okuma ve yazmayı sağlamakla beraber kolayca HTML (artık bir çok diğer formatlara) dönüşüm sağlamaktır.
|
||||||
|
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
<!-- Markdown, HTML'i kapsar, yani her HTML dosyası geçerli bir Markdown dosyasıdır, bu demektir
|
||||||
|
ki Markdown içerisinde HTML etiketleri kullanabiliriz, örneğin bu yorum elementi, ve
|
||||||
|
markdown işleyicisinde etki etmezler. Fakat, markdown dosyası içerisinde HTML elementi oluşturursanız,
|
||||||
|
bu elementin içeriğinde markdown söz dizimlerini kullanamazsınız. -->
|
||||||
|
|
||||||
|
<!-- Markdown ayrıca işleyiciden işleyiciye farklılık gösterebilir. Bu rehberde
|
||||||
|
evrensel özelliklere uygun anlatımlar olacaktır. Bir çok işleyici bu rehberdeki
|
||||||
|
anlatımları destekler -->
|
||||||
|
|
||||||
|
<!-- Başlıklar -->
|
||||||
|
<!-- Kolayca <h1>'den <h6>'ya HTML etiketleri oluşturabilirsiniz.
|
||||||
|
Kare (#) sayısı bu elementin numarasını belirleyecek ve devamında getirdiğiniz
|
||||||
|
yazı bu elementin içeriği olacaktır
|
||||||
|
-->
|
||||||
|
# Bu bir <h1>
|
||||||
|
## Bu bir <h2>
|
||||||
|
### Bu bir <h3>
|
||||||
|
#### Bu bir <h4>
|
||||||
|
##### Bu bir <h5>
|
||||||
|
###### Bu bir <h6>
|
||||||
|
|
||||||
|
<!-- Markdown ayrıca h1 ve h2 için 2 alternatif yol daha taşır -->
|
||||||
|
Bu bir h1
|
||||||
|
=========
|
||||||
|
|
||||||
|
Bu bir h2
|
||||||
|
---------
|
||||||
|
|
||||||
|
<!-- Basit yazı stilleri -->
|
||||||
|
<!-- Markdown ile yazılar kolayca italik ve kalın belirtilebilir -->
|
||||||
|
*Bu yazı italik.*
|
||||||
|
_Bu yazı da italik._
|
||||||
|
|
||||||
|
**Bu yazı kalın.**
|
||||||
|
__Bu yazı da kalın.__
|
||||||
|
|
||||||
|
***Bu yazı hem kalın hem italik.***
|
||||||
|
**_Bu da öyle!_**
|
||||||
|
*__Hatta bu bile!__*
|
||||||
|
|
||||||
|
<!-- Github Flavored Markdown'da ayrıca üstü çizgili karakter de desteklenir: -->
|
||||||
|
~~Bu yazı üstü çizili olarak gözükecek.~~
|
||||||
|
|
||||||
|
<!-- Paragraflar bir veya daha fazla boş satırla ayrılır. -->
|
||||||
|
|
||||||
|
Bu bir paragraf. Paragrafın içeriğine devam ediyorum, eğlenceli değil mi?
|
||||||
|
|
||||||
|
Şimdi 2. paragrafıma geçtim.
|
||||||
|
Hala 2. paragraftayım, çünkü boş bir satır bırakmadım.
|
||||||
|
|
||||||
|
Bu da 3. paragrafım!
|
||||||
|
|
||||||
|
<!-- HTML'de her satır için <br /> etiketi kullanmak ister misiniz, Bir
|
||||||
|
paragrafı bitirdikten sonra 2 veya daha fazla boşluk bırakın ve yeni paragrafa
|
||||||
|
başlayın, bu bir <br /> etiketi sayılacaktır -->
|
||||||
|
|
||||||
|
Bu yazının sonunda 2 boşluk var (bu satırı seçerek kontrol edebilirsiniz).
|
||||||
|
|
||||||
|
Bir üst satırda <br /> etiketi var!
|
||||||
|
|
||||||
|
<!-- Blok yazılarının yapımı oldukça kolay, (>) karakteri ile yapabilirsiniz -->
|
||||||
|
|
||||||
|
> Bu bir blok etiketi. Satırlara ayırmak için
|
||||||
|
> her satırın başında `>` karakter yerleştirmeli veya tek satırda bütün içeriği yazabilirsiniz.
|
||||||
|
> Satır `>` karakteri ile başladığı sürece sorun yok.
|
||||||
|
|
||||||
|
> Ayrıca alt alta da blok elementi açabilirsiniz
|
||||||
|
>> iç içe yani
|
||||||
|
> düzgün değil mi ?
|
||||||
|
|
||||||
|
<!-- Listeler -->
|
||||||
|
<!-- Numarasız listeler için yıldız, artı, veya tire kullanabilirsiniz -->
|
||||||
|
|
||||||
|
* Nesne
|
||||||
|
* Nesne
|
||||||
|
* Bir başka nesne
|
||||||
|
|
||||||
|
veya
|
||||||
|
|
||||||
|
+ Nesne
|
||||||
|
+ Nesne
|
||||||
|
+ Bir başka nesne
|
||||||
|
|
||||||
|
veya
|
||||||
|
|
||||||
|
- Nesne
|
||||||
|
- Nesne
|
||||||
|
- Son bir nesne
|
||||||
|
|
||||||
|
<!-- Numaralı liste için başına sıralı bir şekilde sayı eklemeniz yeterli -->
|
||||||
|
|
||||||
|
1. İlk nesne
|
||||||
|
2. İkinci nesne
|
||||||
|
3. Üçüncü nesne
|
||||||
|
|
||||||
|
<!-- İsterseniz sıralı bir şekilde yazmak zorunda değilsiniz, markdown
|
||||||
|
biçimlendirirken sizin için sıralayacaktır, fakat bunu önermiyorum. Markdown dosyasının
|
||||||
|
düzgün gözükmesi için önerilen metodu uygulamanızı tavsiye ederim -->
|
||||||
|
|
||||||
|
1. İlk nesne
|
||||||
|
1. İkinci nesne
|
||||||
|
1. Üçüncü nesne
|
||||||
|
|
||||||
|
<!-- (Bunun çıktısı ile, sıralı olarak yazdığımız örneğin çıktısı aynı olacaktır) -->
|
||||||
|
|
||||||
|
<!-- Ayrıca alt alta liste oluşturabilirsiniz -->
|
||||||
|
|
||||||
|
1. İlk nesne
|
||||||
|
2. İkinci nesne
|
||||||
|
3. Üçüncü nesne
|
||||||
|
* Alt nesne
|
||||||
|
* Alt nesne
|
||||||
|
4. Dördüncü nesne
|
||||||
|
|
||||||
|
<!-- Ayrıca görev listeleri de bulunmakta. HTML seçim kutusu(checkbox) oluşturacaktır. -->
|
||||||
|
Kutunun içerisinde `x` yoksa eğer seçim kutusu boş olacaktır.
|
||||||
|
- [ ] Yapılacak ilk görev.
|
||||||
|
- [ ] Yapılması gereken bir başka görev
|
||||||
|
Aşağıdaki seçim kutusu ise içi dolu olacaktır.
|
||||||
|
- [x] Bu görev başarıyla yapıldı
|
||||||
|
|
||||||
|
<!-- Kod blokları -->
|
||||||
|
<!-- Kod bloklarını(<code> elementi) belirtmek için 4 adet boşluk veya bir
|
||||||
|
tab karakterini kullanabilirsiniz -->
|
||||||
|
|
||||||
|
Bu bir kod
|
||||||
|
öyle mi?
|
||||||
|
|
||||||
|
<!-- Ayrıca kod içerisinde girinti kullanmak istiyorsanız tekrar `tab` veya `4 boşluk`
|
||||||
|
kullanabilirsiniz -->
|
||||||
|
|
||||||
|
my_array.each do |item|
|
||||||
|
puts item
|
||||||
|
end
|
||||||
|
|
||||||
|
<!-- Yazı içerisinde kod belirtmek için sorgu tırnağı (`) kullanabilirsiniz -->
|
||||||
|
|
||||||
|
Ahmet `go_to()` fonksiyonun ne yaptığını bilmiyor!
|
||||||
|
|
||||||
|
<!-- Github Flavored Markdown'da, kod içerisinde aydınlatma kullanabilirsiniz -->
|
||||||
|
|
||||||
|
\`\`\`ruby <!-- buradaki ters slaş (\) işaretlerini kullanmayın, sadece ```ruby ! -->
|
||||||
|
def foobar
|
||||||
|
puts "Hello world!"
|
||||||
|
end
|
||||||
|
\`\`\` <!-- burada da (\) işaretlerini kullanmayın, sadece ``` -->
|
||||||
|
|
||||||
|
<!-- Yukarıdaki örnekte girinti kullanmanıza gerek yok, Github da
|
||||||
|
``` işaretinden sonra belirttiğiniz yazılım diline göre gerekli
|
||||||
|
syntax aydınlatmaları uygulanacaktır -->
|
||||||
|
|
||||||
|
<!-- Düz çizgi (<hr />) -->
|
||||||
|
<!-- Düz çizgiler 3 veya daha fazla yıldız/çizgi ile yapılabilir. Boşluklar önemsiz. -->
|
||||||
|
|
||||||
|
***
|
||||||
|
---
|
||||||
|
- - -
|
||||||
|
****************
|
||||||
|
|
||||||
|
<!-- Linkler -->
|
||||||
|
<!-- Markdown'daki en güzel şeylerden biri kolayca link oluşturmaktır.
|
||||||
|
Linkte göstermek istediğiniz yazıyı [] içerisine yerleştirin ve sonuna parantezler içerisinde ()
|
||||||
|
gideceği adresi belirtin -->
|
||||||
|
|
||||||
|
[Bana tıkla!](http://test.com)
|
||||||
|
|
||||||
|
<!-- Ayrıca linke `title` özelliği eklemek için tırnakları kullanabilirsiniz -->
|
||||||
|
|
||||||
|
[Bana tıkla!](http://test.com "Test.com'a gider")
|
||||||
|
|
||||||
|
<!-- Bağıl yollar da çalışıyor. -->
|
||||||
|
[Müzik dinle](/muzik/).
|
||||||
|
|
||||||
|
<!-- Markdown ayrıca referans linklerini de destekler -->
|
||||||
|
|
||||||
|
[Bu linke tıklayarak][link1] daha detaylı bilgi alabilirsiniz!
|
||||||
|
[Ayrıca bu linki de inceleyin][foobar] tabi istiyorsanız.
|
||||||
|
|
||||||
|
[link1]: http://test.com/ "harika!"
|
||||||
|
[foobar]: http://foobar.biz/ "okey!"
|
||||||
|
|
||||||
|
<!--Başlık ayrıca tek tırnak veya parantez içinde olabilir, veya direk yazılabilir.
|
||||||
|
Referans döküman içerisindeki herhangi bir yer olabilir ve referans IDsi
|
||||||
|
benzersiz olduğu sürece sorunsuz çalışacaktır. -->
|
||||||
|
|
||||||
|
<!-- Ayrıca "dolaylı adlandırma" bulunmaktadır, "dolaylı adlandırma", linkin yazısının
|
||||||
|
aynı zamanda onun idsi olmasıdır -->
|
||||||
|
|
||||||
|
[Bu][] bir link.
|
||||||
|
[bu]: http://bubirlink.com
|
||||||
|
|
||||||
|
<!-- Fakat bu çok tercih edilen bir yöntem değil. -->
|
||||||
|
|
||||||
|
<!-- Resimler -->
|
||||||
|
<!-- Resimler aslında linklere çok benziyor fakat başında ünlem bulunuyor! -->
|
||||||
|

|
||||||
|
|
||||||
|
<!-- Referanslar resimler için de geçerli -->
|
||||||
|
![Bu alt etiketi.][resmim]
|
||||||
|
|
||||||
|
[resmim]: bagil/linkler/de/calisiyor.jpg "Başlık isterseniz buraya girebilirsiniz"
|
||||||
|
|
||||||
|
<!-- Çeşitli -->
|
||||||
|
<!-- Oto-linkler -->
|
||||||
|
|
||||||
|
<http://testwebsite.com/> ile
|
||||||
|
[http://testwebsite.com/](http://testwebsite.com) aynı şeyler
|
||||||
|
|
||||||
|
<!-- Oto-linkler epostaları da destekler -->
|
||||||
|
|
||||||
|
<foo@bar.com>
|
||||||
|
|
||||||
|
<!-- Kaçış karakterleri -->
|
||||||
|
|
||||||
|
Bu yazının *yıldızlar arasında gözükmesini* istiyorum fakat italik olmamasını istiyorum,
|
||||||
|
bunun için, şu şekilde: \*bu yazı italik değil, yıldızlar arasında\*.
|
||||||
|
|
||||||
|
<!-- Tablolar -->
|
||||||
|
<!-- Tablolar sadece Github Flavored Markdown'da destekleniyor ve açıkçası
|
||||||
|
performansı çok yoruyorlar, fakat illa ki kullanmak isterseniz: -->
|
||||||
|
|
||||||
|
| Sütun1 | Sütun 2 | Sütün 3 |
|
||||||
|
| :----------- | :------: | ------------: |
|
||||||
|
| Sola dayalı | Ortalı | Sağa dayalı |
|
||||||
|
| test | test | test |
|
||||||
|
|
||||||
|
<!-- ayrıca, bunun aynısı -->
|
||||||
|
|
||||||
|
Sütun 1 | Sütun 2 | Sütun 3
|
||||||
|
:-- | :-: | --:
|
||||||
|
Çok çirkin göözüküyor | değil | mi?
|
||||||
|
|
||||||
|
<!-- Bitiş! -->
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Daha detaylı bilgi için, John Gruber'in resmi söz dizimi yazısını [buradan](http://daringfireball.net/projects/markdown/syntax) veya Adam Pritchard'ın mükemmel hatırlatma kağıdını [buradan](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) inceleyebilirsiniz.
|
635
tr-tr/python3-tr.html.markdown
Normal file
635
tr-tr/python3-tr.html.markdown
Normal file
@@ -0,0 +1,635 @@
|
|||||||
|
---
|
||||||
|
language: python3
|
||||||
|
contributors:
|
||||||
|
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
|
||||||
|
- ["Steven Basart", "http://github.com/xksteven"]
|
||||||
|
- ["Andre Polykanine", "https://github.com/Oire"]
|
||||||
|
- ["Andre Polykanine", "https://github.com/Oire"]
|
||||||
|
translators:
|
||||||
|
- ["Eray AYDIN", "http://erayaydin.me/"]
|
||||||
|
lang: tr-tr
|
||||||
|
filename: learnpython3-tr.py
|
||||||
|
---
|
||||||
|
|
||||||
|
Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur.
|
||||||
|
|
||||||
|
Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz.
|
||||||
|
|
||||||
|
```python
|
||||||
|
|
||||||
|
# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır.
|
||||||
|
|
||||||
|
""" Çok satırlı olmasını istediğiniz yorumlar
|
||||||
|
üç adet tırnak(") işareti ile
|
||||||
|
yapılmaktadır
|
||||||
|
"""
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 1. Temel Veri Türleri ve Operatörler
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Sayılar
|
||||||
|
3 # => 3
|
||||||
|
|
||||||
|
# Tahmin edebileceğiniz gibi matematik
|
||||||
|
1 + 1 # => 2
|
||||||
|
8 - 1 # => 7
|
||||||
|
10 * 2 # => 20
|
||||||
|
|
||||||
|
# Bölme işlemi varsayılan olarak onluk döndürür
|
||||||
|
35 / 5 # => 7.0
|
||||||
|
|
||||||
|
# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar
|
||||||
|
5 // 3 # => 1
|
||||||
|
5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir
|
||||||
|
-5 // 3 # => -2
|
||||||
|
-5.0 // 3.0 # => -2.0
|
||||||
|
|
||||||
|
# Onluk kullanırsanız, sonuç da onluk olur
|
||||||
|
3 * 2.0 # => 6.0
|
||||||
|
|
||||||
|
# Kalan operatörü
|
||||||
|
7 % 3 # => 1
|
||||||
|
|
||||||
|
# Üs (2 üzeri 4)
|
||||||
|
2**4 # => 16
|
||||||
|
|
||||||
|
# Parantez ile önceliği değiştirebilirsiniz
|
||||||
|
(1 + 3) * 2 # => 8
|
||||||
|
|
||||||
|
# Boolean(Doğru-Yanlış) değerleri standart
|
||||||
|
True
|
||||||
|
False
|
||||||
|
|
||||||
|
# 'değil' ile terse çevirme
|
||||||
|
not True # => False
|
||||||
|
not False # => True
|
||||||
|
|
||||||
|
# Boolean Operatörleri
|
||||||
|
# "and" ve "or" büyük küçük harf duyarlıdır
|
||||||
|
True and False #=> False
|
||||||
|
False or True #=> True
|
||||||
|
|
||||||
|
# Bool operatörleri ile sayı kullanımı
|
||||||
|
0 and 2 #=> 0
|
||||||
|
-5 or 0 #=> -5
|
||||||
|
0 == False #=> True
|
||||||
|
2 == True #=> False
|
||||||
|
1 == True #=> True
|
||||||
|
|
||||||
|
# Eşitlik kontrolü ==
|
||||||
|
1 == 1 # => True
|
||||||
|
2 == 1 # => False
|
||||||
|
|
||||||
|
# Eşitsizlik Kontrolü !=
|
||||||
|
1 != 1 # => False
|
||||||
|
2 != 1 # => True
|
||||||
|
|
||||||
|
# Diğer karşılaştırmalar
|
||||||
|
1 < 10 # => True
|
||||||
|
1 > 10 # => False
|
||||||
|
2 <= 2 # => True
|
||||||
|
2 >= 2 # => True
|
||||||
|
|
||||||
|
# Zincirleme şeklinde karşılaştırma da yapabilirsiniz!
|
||||||
|
1 < 2 < 3 # => True
|
||||||
|
2 < 3 < 2 # => False
|
||||||
|
|
||||||
|
# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir
|
||||||
|
"Bu bir yazı."
|
||||||
|
'Bu da bir yazı.'
|
||||||
|
|
||||||
|
# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem.
|
||||||
|
"Merhaba " + "dünya!" # => "Merhaba dünya!"
|
||||||
|
|
||||||
|
# Bir yazı(string) karakter listesi gibi işlenebilir
|
||||||
|
"Bu bir yazı"[0] # => 'B'
|
||||||
|
|
||||||
|
# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde:
|
||||||
|
"{} da ayrıca {}".format("yazılar", "işlenebilir")
|
||||||
|
|
||||||
|
# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz.
|
||||||
|
"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu")
|
||||||
|
#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir"
|
||||||
|
|
||||||
|
# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz.
|
||||||
|
"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor"
|
||||||
|
|
||||||
|
# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız,
|
||||||
|
# eski stil formatlamayı kullanabilirsiniz:
|
||||||
|
"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir")
|
||||||
|
|
||||||
|
|
||||||
|
# Hiçbir şey(none) da bir objedir
|
||||||
|
None # => None
|
||||||
|
|
||||||
|
# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın
|
||||||
|
# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir.
|
||||||
|
"vb" is None # => False
|
||||||
|
None is None # => True
|
||||||
|
|
||||||
|
# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü.
|
||||||
|
# Diğer veriler ise True değeri döndürür
|
||||||
|
bool(0) # => False
|
||||||
|
bool("") # => False
|
||||||
|
bool([]) #=> False
|
||||||
|
bool({}) #=> False
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 2. Değişkenler ve Koleksiyonlar
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Python bir yazdırma fonksiyonuna sahip
|
||||||
|
print("Ben Python. Tanıştığıma memnun oldum!")
|
||||||
|
|
||||||
|
# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok.
|
||||||
|
# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin
|
||||||
|
bir_degisken = 5
|
||||||
|
bir_degisken # => 5
|
||||||
|
|
||||||
|
# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır.
|
||||||
|
# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz.
|
||||||
|
bir_bilinmeyen_degisken # NameError hatası oluşturur
|
||||||
|
|
||||||
|
# Listeler ile sıralamaları tutabilirsiniz
|
||||||
|
li = []
|
||||||
|
# Önceden doldurulmuş listeler ile başlayabilirsiniz
|
||||||
|
diger_li = [4, 5, 6]
|
||||||
|
|
||||||
|
# 'append' ile listenin sonuna ekleme yapabilirsiniz
|
||||||
|
li.append(1) # li artık [1] oldu
|
||||||
|
li.append(2) # li artık [1, 2] oldu
|
||||||
|
li.append(4) # li artık [1, 2, 4] oldu
|
||||||
|
li.append(3) # li artık [1, 2, 4, 3] oldu
|
||||||
|
# 'pop' ile listenin son elementini kaldırabilirsiniz
|
||||||
|
li.pop() # => 3 ve li artık [1, 2, 4]
|
||||||
|
# Çıkarttığımız tekrardan ekleyelim
|
||||||
|
li.append(3) # li yeniden [1, 2, 4, 3] oldu.
|
||||||
|
|
||||||
|
# Dizi gibi listeye erişim sağlayın
|
||||||
|
li[0] # => 1
|
||||||
|
# Son elemente bakın
|
||||||
|
li[-1] # => 3
|
||||||
|
|
||||||
|
# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur
|
||||||
|
li[4] # IndexError hatası oluşturur
|
||||||
|
|
||||||
|
# Bir kısmını almak isterseniz.
|
||||||
|
li[1:3] # => [2, 4]
|
||||||
|
# Başlangıç belirtmezseniz
|
||||||
|
li[2:] # => [4, 3]
|
||||||
|
# Sonu belirtmesseniz
|
||||||
|
li[:3] # => [1, 2, 4]
|
||||||
|
# Her ikişer objeyi seçme
|
||||||
|
li[::2] # =>[1, 4]
|
||||||
|
# Listeyi tersten almak
|
||||||
|
li[::-1] # => [3, 4, 2, 1]
|
||||||
|
# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz
|
||||||
|
# li[baslangic:son:adim]
|
||||||
|
|
||||||
|
# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz
|
||||||
|
del li[2] # li artık [1, 2, 3] oldu
|
||||||
|
|
||||||
|
# Listelerde de ekleme yapabilirsiniz
|
||||||
|
# Not: değerler üzerinde değişiklik yapılmaz.
|
||||||
|
li + diger_li # => [1, 2, 3, 4, 5, 6]
|
||||||
|
|
||||||
|
# Listeleri birbirine bağlamak için "extend()" kullanılabilir
|
||||||
|
li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu
|
||||||
|
|
||||||
|
# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir
|
||||||
|
1 in li # => True
|
||||||
|
|
||||||
|
# Uzunluğu öğrenmek için "len()" kullanılabilir
|
||||||
|
len(li) # => 6
|
||||||
|
|
||||||
|
|
||||||
|
# Tüpler listeler gibidir fakat değiştirilemez.
|
||||||
|
tup = (1, 2, 3)
|
||||||
|
tup[0] # => 1
|
||||||
|
tup[0] = 3 # TypeError hatası oluşturur
|
||||||
|
|
||||||
|
# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz
|
||||||
|
len(tup) # => 3
|
||||||
|
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
|
||||||
|
tup[:2] # => (1, 2)
|
||||||
|
2 in tup # => True
|
||||||
|
|
||||||
|
# Tüpleri(veya listeleri) değişkenlere açabilirsiniz
|
||||||
|
a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3
|
||||||
|
# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur
|
||||||
|
d, e, f = 4, 5, 6
|
||||||
|
# 2 değeri birbirine değiştirmek bu kadar kolay
|
||||||
|
e, d = d, e # 'd' artık 5 ve 'e' artık 4
|
||||||
|
|
||||||
|
|
||||||
|
# Sözlükler anahtar kodlarla verileri tutar
|
||||||
|
bos_sozl = {}
|
||||||
|
# Önceden doldurulmuş sözlük oluşturma
|
||||||
|
dolu_sozl = {"bir": 1, "iki": 2, "uc": 3}
|
||||||
|
|
||||||
|
# Değere bakmak için [] kullanalım
|
||||||
|
dolu_sozl["bir"] # => 1
|
||||||
|
|
||||||
|
# Bütün anahtarları almak için "keys()" kullanılabilir.
|
||||||
|
# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz.
|
||||||
|
# Not - Sözlük anahtarlarının sıralaması kesin değildir.
|
||||||
|
# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir.
|
||||||
|
list(dolu_sozl.keys()) # => ["uc", "iki", "bir"]
|
||||||
|
|
||||||
|
|
||||||
|
# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor
|
||||||
|
# Not - Sıralama değişebilir.
|
||||||
|
list(dolu_sozl.values()) # => [3, 2, 1]
|
||||||
|
|
||||||
|
|
||||||
|
# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz
|
||||||
|
"bir" in dolu_sozl # => True
|
||||||
|
1 in dolu_sozl # => False
|
||||||
|
|
||||||
|
# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır.
|
||||||
|
dolu_sozl["dort"] # KeyError hatası oluşturur
|
||||||
|
|
||||||
|
# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz
|
||||||
|
dolu_sozl.get("bir") # => 1
|
||||||
|
dolu_sozl.get("dort") # => None
|
||||||
|
# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz.
|
||||||
|
dolu_sozl.get("bir", 4) # => 1
|
||||||
|
dolu_sozl.get("dort", 4) # => 4
|
||||||
|
|
||||||
|
# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır
|
||||||
|
dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip
|
||||||
|
dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip
|
||||||
|
|
||||||
|
# Sözlüğe ekleme
|
||||||
|
dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4}
|
||||||
|
#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu
|
||||||
|
|
||||||
|
# Sözlükten anahtar silmek için 'del' kullanılabilir
|
||||||
|
del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir
|
||||||
|
|
||||||
|
|
||||||
|
# Setler ... set işte :D
|
||||||
|
bos_set = set()
|
||||||
|
# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm.
|
||||||
|
bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4}
|
||||||
|
|
||||||
|
# Sete yeni setler ekleyebilirsiniz
|
||||||
|
dolu_set = bir_set
|
||||||
|
|
||||||
|
# Sete bir diğer öğe ekleme
|
||||||
|
dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu
|
||||||
|
|
||||||
|
# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz
|
||||||
|
diger_set = {3, 4, 5, 6}
|
||||||
|
dolu_set & diger_set # => {3, 4, 5}
|
||||||
|
|
||||||
|
# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz
|
||||||
|
dolu_set | diger_set # => {1, 2, 3, 4, 5, 6}
|
||||||
|
|
||||||
|
# Farklılıkları almak için "-" kullanabilirsiniz
|
||||||
|
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
|
||||||
|
|
||||||
|
# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir
|
||||||
|
2 in dolu_set # => True
|
||||||
|
10 in dolu_set # => False
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 3. Kontrol Akışları ve Temel Soyutlandırma
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Bir değişken oluşturalım
|
||||||
|
bir_degisken = 5
|
||||||
|
|
||||||
|
# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir!
|
||||||
|
# çıktı olarak "bir_degisken 10 dan küçük" yazar
|
||||||
|
if bir_degisken > 10:
|
||||||
|
print("bir_degisken 10 dan büyük")
|
||||||
|
elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir.
|
||||||
|
print("bir_degisken 10 dan küçük")
|
||||||
|
else: # Bu ifade de zorunlu değil.
|
||||||
|
print("bir_degisken değeri 10")
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
Döngülerle lsiteleri döngüye alabilirsiniz
|
||||||
|
çıktı:
|
||||||
|
köpek bir memeli hayvandır
|
||||||
|
kedi bir memeli hayvandır
|
||||||
|
fare bir memeli hayvandır
|
||||||
|
"""
|
||||||
|
for hayvan in ["köpek", "kedi, "fare"]:
|
||||||
|
# format ile kolayca yazıyı biçimlendirelim
|
||||||
|
print("{} bir memeli hayvandır".format(hayvan))
|
||||||
|
|
||||||
|
"""
|
||||||
|
"range(sayi)" bir sayı listesi döndür
|
||||||
|
0'dan belirttiğiniz sayıyıa kadar
|
||||||
|
çıktı:
|
||||||
|
0
|
||||||
|
1
|
||||||
|
2
|
||||||
|
3
|
||||||
|
"""
|
||||||
|
for i in range(4):
|
||||||
|
print(i)
|
||||||
|
|
||||||
|
"""
|
||||||
|
'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir.
|
||||||
|
çıktı:
|
||||||
|
0
|
||||||
|
1
|
||||||
|
2
|
||||||
|
3
|
||||||
|
"""
|
||||||
|
x = 0
|
||||||
|
while x < 4:
|
||||||
|
print(x)
|
||||||
|
x += 1 # Uzun hali x = x + 1
|
||||||
|
|
||||||
|
# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz
|
||||||
|
try:
|
||||||
|
# Bir hata oluşturmak için "raise" kullanabilirsiniz
|
||||||
|
raise IndexError("Bu bir index hatası")
|
||||||
|
except IndexError as e:
|
||||||
|
pass # Önemsiz, devam et.
|
||||||
|
except (TypeError, NameError):
|
||||||
|
pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse.
|
||||||
|
else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır
|
||||||
|
print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı
|
||||||
|
|
||||||
|
# Temel Soyutlandırma, bir objenin işlenmiş halidir.
|
||||||
|
# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi.
|
||||||
|
|
||||||
|
dolu_sozl = {"bir": 1, "iki": 2, "uc": 3}
|
||||||
|
temel_soyut = dolu_sozl.keys()
|
||||||
|
print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu
|
||||||
|
|
||||||
|
# Temel Soyutlandırılmış objeyi döngüye sokabiliriz.
|
||||||
|
for i in temel_soyut:
|
||||||
|
print(i) # Çıktısı: bir, iki, uc
|
||||||
|
|
||||||
|
# Fakat, elementin anahtarına değerine.
|
||||||
|
temel_soyut[1] # TypeError hatası!
|
||||||
|
|
||||||
|
# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır.
|
||||||
|
iterator = iter(temel_soyut)
|
||||||
|
|
||||||
|
# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır
|
||||||
|
# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz.
|
||||||
|
iterator.__next__() #=> "bir"
|
||||||
|
|
||||||
|
# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir
|
||||||
|
iterator.__next__() #=> "iki"
|
||||||
|
iterator.__next__() #=> "uc"
|
||||||
|
|
||||||
|
# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır.
|
||||||
|
iterator.__next__() # StopIteration hatası
|
||||||
|
|
||||||
|
# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz.
|
||||||
|
list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"]
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 4. Fonksiyonlar
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# "def" ile yeni fonksiyonlar oluşturabilirsiniz
|
||||||
|
def topla(x, y):
|
||||||
|
print("x = {} ve y = {}".format(x, y))
|
||||||
|
return x + y # Değer döndürmek için 'return' kullanmalısınız
|
||||||
|
|
||||||
|
# Fonksiyonu parametleri ile çağırıyoruz
|
||||||
|
topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür
|
||||||
|
|
||||||
|
# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek
|
||||||
|
topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz.
|
||||||
|
|
||||||
|
# Sınırsız sayıda argüman da alabilirsiniz
|
||||||
|
def argumanlar(*argumanlar):
|
||||||
|
return argumanlar
|
||||||
|
|
||||||
|
argumanlar(1, 2, 3) # => (1, 2, 3)
|
||||||
|
|
||||||
|
# Parametrelerin anahtar değerlerini almak isterseniz
|
||||||
|
def anahtar_par(**anahtarlar):
|
||||||
|
return anahtar
|
||||||
|
|
||||||
|
# Çalıştırdığımızda
|
||||||
|
anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"}
|
||||||
|
|
||||||
|
|
||||||
|
# İsterseniz, bu ikisini birden kullanabilirsiniz
|
||||||
|
def tum_argumanlar(*argumanlar, **anahtarla):
|
||||||
|
print(argumanlar)
|
||||||
|
print(anahtarla)
|
||||||
|
"""
|
||||||
|
tum_argumanlar(1, 2, a=3, b=4) çıktı:
|
||||||
|
(1, 2)
|
||||||
|
{"a": 3, "b": 4}
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Fonksiyonu çağırırken de aynısını kullanabilirsiniz
|
||||||
|
argumanlar = (1, 2, 3, 4)
|
||||||
|
anahtarla = {"a": 3, "b": 4}
|
||||||
|
tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4)
|
||||||
|
tum_argumanlar(**anahtarla) # = foo(a=3, b=4)
|
||||||
|
tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4)
|
||||||
|
|
||||||
|
|
||||||
|
# Fonksiyonlarda kullanacağımız bir değişken oluşturalım
|
||||||
|
x = 5
|
||||||
|
|
||||||
|
def belirleX(sayi):
|
||||||
|
# Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil
|
||||||
|
x = sayi # => 43
|
||||||
|
print (x) # => 43
|
||||||
|
|
||||||
|
def globalBelirleX(sayi):
|
||||||
|
global x
|
||||||
|
print (x) # => 5
|
||||||
|
x = sayi # global olan x değişkeni artık 6
|
||||||
|
print (x) # => 6
|
||||||
|
|
||||||
|
belirleX(43)
|
||||||
|
globalBelirleX(6)
|
||||||
|
|
||||||
|
|
||||||
|
# Sınıf fonksiyonları oluşturma
|
||||||
|
def toplama_olustur(x):
|
||||||
|
def topla(y):
|
||||||
|
return x + y
|
||||||
|
return topla
|
||||||
|
|
||||||
|
ekle_10 = toplama_olustur(10)
|
||||||
|
ekle_10(3) # => 13
|
||||||
|
|
||||||
|
# Bilinmeyen fonksiyon
|
||||||
|
(lambda x: x > 2)(3) # => True
|
||||||
|
|
||||||
|
# TODO - Fix for iterables
|
||||||
|
# Belirli sayıdan yükseğini alma fonksiyonu
|
||||||
|
map(ekle_10, [1, 2, 3]) # => [11, 12, 13]
|
||||||
|
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||||
|
|
||||||
|
# Filtreleme işlemi için liste comprehensions da kullanabiliriz
|
||||||
|
[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
|
||||||
|
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 5. Sınıflar
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
|
||||||
|
# Sınıf oluşturmak için objeden alt sınıf oluşturacağız.
|
||||||
|
class Insan(obje):
|
||||||
|
|
||||||
|
# Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir
|
||||||
|
tur = "H. sapiens"
|
||||||
|
|
||||||
|
# Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir.
|
||||||
|
# Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar
|
||||||
|
# python tarafından tanımlanan isimlerdir.
|
||||||
|
# Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız!
|
||||||
|
def __init__(self, isim):
|
||||||
|
# Parametreyi sınıfın değerine atayalım
|
||||||
|
self.isim = isim
|
||||||
|
|
||||||
|
# Bir metot. Bütün metotlar ilk parametre olarak "self "alır.
|
||||||
|
def soyle(self, mesaj):
|
||||||
|
return "{isim}: {mesaj}".format(isim=self.name, mesaj=mesaj)
|
||||||
|
|
||||||
|
# Bir sınıf metotu bütün nesnelere paylaştırılır
|
||||||
|
# İlk parametre olarak sınıf alırlar
|
||||||
|
@classmethod
|
||||||
|
def getir_tur(snf):
|
||||||
|
return snf.tur
|
||||||
|
|
||||||
|
# Bir statik metot, sınıf ve nesnesiz çağrılır
|
||||||
|
@staticmethod
|
||||||
|
def grunt():
|
||||||
|
return "*grunt*"
|
||||||
|
|
||||||
|
|
||||||
|
# Sınıfı çağıralım
|
||||||
|
i = Insan(isim="Ahmet")
|
||||||
|
print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba"
|
||||||
|
|
||||||
|
j = Insan("Ali")
|
||||||
|
print(j.soyle("selam")) # çıktı "Ali: selam"
|
||||||
|
|
||||||
|
# Sınıf metodumuzu çağıraim
|
||||||
|
i.getir_tur() # => "H. sapiens"
|
||||||
|
|
||||||
|
# Paylaşılan değeri değiştirelim
|
||||||
|
Insan.tur = "H. neanderthalensis"
|
||||||
|
i.getir_tur() # => "H. neanderthalensis"
|
||||||
|
j.getir_tur() # => "H. neanderthalensis"
|
||||||
|
|
||||||
|
# Statik metodumuzu çağıralım
|
||||||
|
Insan.grunt() # => "*grunt*"
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 6. Moduller
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Modülleri içe aktarabilirsiniz
|
||||||
|
import math
|
||||||
|
print(math.sqrt(16)) # => 4
|
||||||
|
|
||||||
|
# Modülden belirli bir fonksiyonları alabilirsiniz
|
||||||
|
from math import ceil, floor
|
||||||
|
print(ceil(3.7)) # => 4.0
|
||||||
|
print(floor(3.7)) # => 3.0
|
||||||
|
|
||||||
|
# Modüldeki tüm fonksiyonları içe aktarabilirsiniz
|
||||||
|
# Dikkat: bunu yapmanızı önermem.
|
||||||
|
from math import *
|
||||||
|
|
||||||
|
# Modül isimlerini değiştirebilirsiniz.
|
||||||
|
# Not: Modül ismini kısaltmanız çok daha iyi olacaktır
|
||||||
|
import math as m
|
||||||
|
math.sqrt(16) == m.sqrt(16) # => True
|
||||||
|
|
||||||
|
# Python modulleri aslında birer python dosyalarıdır.
|
||||||
|
# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün
|
||||||
|
# ismi ile dosyanın ismi aynı olacaktır.
|
||||||
|
|
||||||
|
# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz.
|
||||||
|
import math
|
||||||
|
dir(math)
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 7. Gelişmiş
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır
|
||||||
|
def kare_sayilar(nesne):
|
||||||
|
for i in nesne:
|
||||||
|
yield i + i
|
||||||
|
|
||||||
|
# Bir oluşturucu(generator) değerleri anında oluşturur.
|
||||||
|
# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan
|
||||||
|
# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük
|
||||||
|
# değerler işlenmeyecektir.
|
||||||
|
# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda
|
||||||
|
# çok fazla vakit alacaktır.
|
||||||
|
# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir.
|
||||||
|
range_ = range(1, 900000000)
|
||||||
|
# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım
|
||||||
|
for i in kare_sayilar(range_):
|
||||||
|
print(i)
|
||||||
|
if i >= 30:
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
# Dekoratörler
|
||||||
|
# Bu örnekte,
|
||||||
|
# Eğer lutfen_soyle True ise dönen değer değişecektir.
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
|
||||||
|
def yalvar(hedef_fonksiyon):
|
||||||
|
@wraps(hedef_fonksiyon)
|
||||||
|
def metot(*args, **kwargs):
|
||||||
|
msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs)
|
||||||
|
if lutfen_soyle:
|
||||||
|
return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(")
|
||||||
|
return msj
|
||||||
|
|
||||||
|
return metot
|
||||||
|
|
||||||
|
|
||||||
|
@yalvar
|
||||||
|
def soyle(lutfen_soyle=False):
|
||||||
|
msj = "Bana soda alır mısın?"
|
||||||
|
return msj, lutfen_soyle
|
||||||
|
|
||||||
|
|
||||||
|
print(soyle()) # Bana soda alır mısın?
|
||||||
|
print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :(
|
||||||
|
```
|
||||||
|
|
||||||
|
## Daha Fazlasına Hazır Mısınız?
|
||||||
|
|
||||||
|
### Ücretsiz Online
|
||||||
|
|
||||||
|
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
|
||||||
|
* [Dive Into Python](http://www.diveintopython.net/)
|
||||||
|
* [Ideas for Python Projects](http://pythonpracticeprojects.com)
|
||||||
|
|
||||||
|
* [The Official Docs](http://docs.python.org/3/)
|
||||||
|
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
|
||||||
|
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
|
||||||
|
* [Python Course](http://www.python-course.eu/index.php)
|
||||||
|
|
||||||
|
### Kitaplar
|
||||||
|
|
||||||
|
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
|
||||||
|
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
|
||||||
|
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
|
||||||
|
|
@@ -14,100 +14,111 @@ This article will focus only on TypeScript extra syntax, as oposed to [JavaScrip
|
|||||||
To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript.
|
To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
//There are 3 basic types in TypeScript
|
// There are 3 basic types in TypeScript
|
||||||
var isDone: boolean = false;
|
var isDone: boolean = false;
|
||||||
var lines: number = 42;
|
var lines: number = 42;
|
||||||
var name: string = "Anders";
|
var name: string = "Anders";
|
||||||
|
|
||||||
//..When it's impossible to know, there is the "Any" type
|
// When it's impossible to know, there is the "Any" type
|
||||||
var notSure: any = 4;
|
var notSure: any = 4;
|
||||||
notSure = "maybe a string instead";
|
notSure = "maybe a string instead";
|
||||||
notSure = false; // okay, definitely a boolean
|
notSure = false; // okay, definitely a boolean
|
||||||
|
|
||||||
//For collections, there are typed arrays and generic arrays
|
// For collections, there are typed arrays and generic arrays
|
||||||
var list: number[] = [1, 2, 3];
|
var list: number[] = [1, 2, 3];
|
||||||
//Alternatively, using the generic array type
|
// Alternatively, using the generic array type
|
||||||
var list: Array<number> = [1, 2, 3];
|
var list: Array<number> = [1, 2, 3];
|
||||||
|
|
||||||
//For enumerations:
|
// For enumerations:
|
||||||
enum Color {Red, Green, Blue};
|
enum Color {Red, Green, Blue};
|
||||||
var c: Color = Color.Green;
|
var c: Color = Color.Green;
|
||||||
|
|
||||||
//Lastly, "void" is used in the special case of a function not returning anything
|
// Lastly, "void" is used in the special case of a function returning nothing
|
||||||
function bigHorribleAlert(): void {
|
function bigHorribleAlert(): void {
|
||||||
alert("I'm a little annoying box!");
|
alert("I'm a little annoying box!");
|
||||||
}
|
}
|
||||||
|
|
||||||
//Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference
|
// Functions are first class citizens, support the lambda "fat arrow" syntax and
|
||||||
//All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted
|
// use type inference
|
||||||
var f1 = function(i: number) : number { return i * i; }
|
|
||||||
var f2 = function(i: number) { return i * i; } //Return type infered
|
|
||||||
var f3 = (i : number) : number => { return i * i; }
|
|
||||||
var f4 = (i: number) => { return i * i; } //Return type infered
|
|
||||||
var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed
|
|
||||||
|
|
||||||
//Interfaces are structural, anything that has the properties is compliant with the interface
|
// The following are equivalent, the same signature will be infered by the
|
||||||
|
// compiler, and same JavaScript will be emitted
|
||||||
|
var f1 = function(i: number): number { return i * i; }
|
||||||
|
// Return type inferred
|
||||||
|
var f2 = function(i: number) { return i * i; }
|
||||||
|
var f3 = (i: number): number => { return i * i; }
|
||||||
|
// Return type inferred
|
||||||
|
var f4 = (i: number) => { return i * i; }
|
||||||
|
// Return type inferred, one-liner means no return keyword needed
|
||||||
|
var f5 = (i: number) => i * i;
|
||||||
|
|
||||||
|
// Interfaces are structural, anything that has the properties is compliant with
|
||||||
|
// the interface
|
||||||
interface Person {
|
interface Person {
|
||||||
name: string;
|
name: string;
|
||||||
//Optional properties, marked with a "?"
|
// Optional properties, marked with a "?"
|
||||||
age?: number;
|
age?: number;
|
||||||
//And of course functions
|
// And of course functions
|
||||||
move(): void;
|
move(): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
//..Object that implements the "Person" interface
|
// Object that implements the "Person" interface
|
||||||
var p : Person = { name: "Bobby", move : () => {} }; //Can be treated as a Person since it has the name and age properties
|
// Can be treated as a Person since it has the name and move properties
|
||||||
//..Objects that have the optional property:
|
var p: Person = { name: "Bobby", move: () => {} };
|
||||||
var validPerson : Person = { name: "Bobby", age: 42, move: () => {} };
|
// Objects that have the optional property:
|
||||||
var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number
|
var validPerson: Person = { name: "Bobby", age: 42, move: () => {} };
|
||||||
|
// Is not a person because age is not a number
|
||||||
|
var invalidPerson: Person = { name: "Bobby", age: true };
|
||||||
|
|
||||||
//..Interfaces can also describe a function type
|
// Interfaces can also describe a function type
|
||||||
interface SearchFunc {
|
interface SearchFunc {
|
||||||
(source: string, subString: string): boolean;
|
(source: string, subString: string): boolean;
|
||||||
}
|
}
|
||||||
//..Only the parameters' types are important, names are not important.
|
// Only the parameters' types are important, names are not important.
|
||||||
var mySearch: SearchFunc;
|
var mySearch: SearchFunc;
|
||||||
mySearch = function(src: string, sub: string) {
|
mySearch = function(src: string, sub: string) {
|
||||||
return src.search(sub) != -1;
|
return src.search(sub) != -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Classes - members are public by default
|
// Classes - members are public by default
|
||||||
class Point {
|
class Point {
|
||||||
//Properties
|
// Properties
|
||||||
x: number;
|
x: number;
|
||||||
|
|
||||||
//Constructor - the public/private keywords in this context will generate the boiler plate code
|
// Constructor - the public/private keywords in this context will generate
|
||||||
// for the property and the initialization in the constructor.
|
// the boiler plate code for the property and the initialization in the
|
||||||
|
// constructor.
|
||||||
// In this example, "y" will be defined just like "x" is, but with less code
|
// In this example, "y" will be defined just like "x" is, but with less code
|
||||||
//Default values are also supported
|
// Default values are also supported
|
||||||
|
|
||||||
constructor(x: number, public y: number = 0) {
|
constructor(x: number, public y: number = 0) {
|
||||||
this.x = x;
|
this.x = x;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Functions
|
// Functions
|
||||||
dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
|
dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
|
||||||
|
|
||||||
//Static members
|
// Static members
|
||||||
static origin = new Point(0, 0);
|
static origin = new Point(0, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
var p1 = new Point(10 ,20);
|
var p1 = new Point(10 ,20);
|
||||||
var p2 = new Point(25); //y will be 0
|
var p2 = new Point(25); //y will be 0
|
||||||
|
|
||||||
//Inheritance
|
// Inheritance
|
||||||
class Point3D extends Point {
|
class Point3D extends Point {
|
||||||
constructor(x: number, y: number, public z: number = 0) {
|
constructor(x: number, y: number, public z: number = 0) {
|
||||||
super(x, y); //Explicit call to the super class constructor is mandatory
|
super(x, y); // Explicit call to the super class constructor is mandatory
|
||||||
}
|
}
|
||||||
|
|
||||||
//Overwrite
|
// Overwrite
|
||||||
dist() {
|
dist() {
|
||||||
var d = super.dist();
|
var d = super.dist();
|
||||||
return Math.sqrt(d * d + this.z * this.z);
|
return Math.sqrt(d * d + this.z * this.z);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Modules, "." can be used as separator for sub modules
|
// Modules, "." can be used as separator for sub modules
|
||||||
module Geometry {
|
module Geometry {
|
||||||
export class Square {
|
export class Square {
|
||||||
constructor(public sideLength: number = 0) {
|
constructor(public sideLength: number = 0) {
|
||||||
@@ -120,32 +131,32 @@ module Geometry {
|
|||||||
|
|
||||||
var s1 = new Geometry.Square(5);
|
var s1 = new Geometry.Square(5);
|
||||||
|
|
||||||
//..Local alias for referencing a module
|
// Local alias for referencing a module
|
||||||
import G = Geometry;
|
import G = Geometry;
|
||||||
|
|
||||||
var s2 = new G.Square(10);
|
var s2 = new G.Square(10);
|
||||||
|
|
||||||
//Generics
|
// Generics
|
||||||
//..Classes
|
// Classes
|
||||||
class Tuple<T1, T2> {
|
class Tuple<T1, T2> {
|
||||||
constructor(public item1: T1, public item2: T2) {
|
constructor(public item1: T1, public item2: T2) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//..Interfaces
|
// Interfaces
|
||||||
interface Pair<T> {
|
interface Pair<T> {
|
||||||
item1: T;
|
item1: T;
|
||||||
item2: T;
|
item2: T;
|
||||||
}
|
}
|
||||||
|
|
||||||
//..And functions
|
// And functions
|
||||||
var pairToTuple = function<T>(p: Pair<T>) {
|
var pairToTuple = function<T>(p: Pair<T>) {
|
||||||
return new Tuple(p.item1, p.item2);
|
return new Tuple(p.item1, p.item2);
|
||||||
};
|
};
|
||||||
|
|
||||||
var tuple = pairToTuple({ item1:"hello", item2:"world"});
|
var tuple = pairToTuple({ item1:"hello", item2:"world"});
|
||||||
|
|
||||||
//Including references to a definition file:
|
// Including references to a definition file:
|
||||||
/// <reference path="jquery.d.ts" />
|
/// <reference path="jquery.d.ts" />
|
||||||
|
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user