diff options
-rw-r--r-- | clojure.html.markdown | 2 | ||||
-rw-r--r-- | go.html.markdown | 301 | ||||
-rw-r--r-- | ko-kr/javascript-kr.html.markdown | 6 | ||||
-rw-r--r-- | ko-kr/lua-kr.html.markdown | 2 | ||||
-rw-r--r-- | pt-br/elisp-pt.html.markdown | 359 | ||||
-rw-r--r-- | pt-br/python-pt.html.markdown | 2 | ||||
-rw-r--r-- | ruby.html.markdown | 12 | ||||
-rwxr-xr-x | zh-cn/python-cn.html.markdown | 277 |
8 files changed, 812 insertions, 149 deletions
diff --git a/clojure.html.markdown b/clojure.html.markdown index 6baae0ce..a502a95c 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -365,7 +365,7 @@ my-atom ;=> Atom<#...> (Returns the Atom object) ### Further Reading -This is far from exhaustive, but hopefully it's enought o get you on your feet. +This is far from exhaustive, but hopefully it's enough to get you on your feet. Clojure.org has lots of articles: [http://clojure.org/](http://clojure.org/) diff --git a/go.html.markdown b/go.html.markdown new file mode 100644 index 00000000..e7b35926 --- /dev/null +++ b/go.html.markdown @@ -0,0 +1,301 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] +--- + +Go was created out of the need to get work done. It's not the latest trend +in computer science, but it is the newest fastest way to solve real-world +problems. + +It has familiar concepts of imperative languages with static typing. +It's fast to compile and fast to execute, it adds easy-to-understand +concurrency to leverage today's multi-core CPUs, and has features to +help with large-scale programming. + +Go comes with a great standard library and an enthusiastic community. + +```Go +// Single line comment +/* Multi- + line comment */ + +// A package clause starts every source file. +// Main is a special name declaring an executable rather than a library. +package main + +// Import declaration declares library packages referenced in this file. +import ( + "fmt" // A package in the Go standard library + "net/http" // Yes, a web server! + "strconv" // String conversions +) + +// A function definition. Main is special. It is the entry point for the +// executable program. Love it or hate it, Go uses brace brackets. +func main() { + // Println outputs a line to stdout. + // Qualify it with the package name, fmt. + fmt.Println("Hello world!") + + // Call another function within this package. + beyondHello() +} + +// Functions have parameters in parentheses. +// If there are no parameters, empty parens are still required. +func beyondHello() { + var x int // Variable declaration. Variables must be declared before use. + x = 3 // Variable assignment. + // "Short" declarations use := to infer the type, declare, and assign. + y := 4 + sum, prod := learnMultiple(x, y) // function returns two values + fmt.Println("sum:", sum, "prod:", prod) // simple output + learnTypes() // < y minutes, learn more! +} + +// Functions can have parameters and (multiple!) return values. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // return two values +} + +// Some built-in types and literals. +func learnTypes() { + // Short declaration usually gives you what you want. + s := "Learn Go!" // string type + + s2 := `A "raw" string literal +can include line breaks.` // same string type + + // non-ASCII literal. Go source is UTF-8. + g := 'Σ' // rune type, an alias for uint32, holds a UTF-8 code point + + f := 3.14195 // float64, an IEEE-754 64-bit floating point number + c := 3 + 4i // complex128, represented internally with two float64s + + // Var syntax with an initializers. + var u uint = 7 // unsigned, but implementation dependent size as with int + var pi float32 = 22. / 7 + + // Conversion syntax with a short declaration. + n := byte('\n') // byte is an alias for uint8 + + // Arrays have size fixed at compile time. + var a4 [4]int // an array of 4 ints, initialized to all 0 + a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown + + // Slices have dynamic size. Arrays and slices each have advantages + // but use cases for slices are much more common. + s3 := []int{4, 5, 9} // compare to a3. no ellipsis here + s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0 + var d2 [][]float64 // declaration only, nothing allocated here + bs := []byte("a slice") // type conversion syntax + + p, q := learnMemory() // declares p, q to be type pointer to int. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + + // Maps are a dynamically growable associative array type, like the + // hash or dictionary types of some other languages. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // Unused variables are an error in Go. + // The underbar lets you "use" a variable but discard its value. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Output of course counts as using a variable. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // back in the flow +} + +// Go is fully garbage collected. It has pointers but no pointer arithmetic. +// You can make a mistake with a nil pointer, but not by incrementing a pointer. +func learnMemory() (p, q *int) { + // Named return values p and q have type pointer to int. + p = new(int) // built-in function new allocates memory. + // The allocated int is initialized to 0, p is no longer nil. + s := make([]int, 20) // allocate 20 ints as a single block of memory + s[3] = 7 // assign one of them + r := -2 // declare another local variable + return &s[3], &r // & takes the address of an object. +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // If statements require brace brackets, and do not require parens. + if true { + fmt.Println("told ya") + } + // Formatting is standardized by the command line command "go fmt." + if false { + // pout + } else { + // gloat + } + // Use switch in preference to chained if statements. + x := 1 + switch x { + case 0: + case 1: + // cases don't "fall through" + case 2: + // unreached + } + // Like if, for doesn't use parens either. + for x := 0; x < 3; x++ { // ++ is a statement + fmt.Println("iteration", x) + } + // x == 1 here. + + // For is the only loop statement in Go, but it has alternate forms. + for { // infinite loop + break // just kidding + continue // unreached + } + // As with for, := in an if statement means to declare and assign y first, + // then test y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Function literals are closures. + xBig := func() bool { + return x > 100 // references x declared above switch statement. + } + fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x) + x /= 1e5 // this makes it == 10 + fmt.Println("xBig:", xBig()) // false now + + // When you need it, you'll love it. + goto love +love: + + learnInterfaces() // Good stuff coming up! +} + +// Define Stringer as an interface type with one method, String. +type Stringer interface { + String() string +} + +// Define pair as a struct with two fields, ints named x and y. +type pair struct { + x, y int +} + +// Define a method on type pair. Pair now implements Stringer. +func (p pair) String() string { // p is called the "receiver" + // Sprintf is another public function in package fmt. + // Dot syntax references fields of p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Brace syntax is a "struct literal." It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + p := pair{3, 4} + fmt.Println(p.String()) // call String method of p, of type pair. + var i Stringer // declare i of interface type Stringer. + i = p // valid because pair implements Stringer + // Call String method of i, of type Stringer. Output same as above. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + fmt.Println(p) // output same as above. Println calls String method. + fmt.Println(i) // output same as above + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" idiom used to tell if something worked or not. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. + fmt.Println("no one there") + } else { + fmt.Print(x) // x would be the value, if it were in the map. + } + // An error value communicates not just "ok" but more about the problem. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // prints "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // We'll revisit interfaces a little later. Meanwhile, + learnConcurrency() +} + +// c is a channel, a concurrency-safe communication object. +func inc(i int, c chan int) { + c <- i + 1 // <- is the "send" operator when a channel appears on the left. +} + +// We'll use inc to increment some numbers concurrently. +func learnConcurrency() { + // Same make function used earlier to make a slice. Make allocates and + // initializes slices, maps, and channels. + c := make(chan int) + // Start three concurrent goroutines. Numbers will be incremented + // concurrently, perhaps in parallel if the machine is capable and + // properly configured. All three send to the same channel. + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // Read three results from the channel and print them out. + // There is no telling in what order the results will arrive! + fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. + + cs := make(chan string) // another channel, this one handles strings. + cc := make(chan chan string) // a channel of channels. + go func() { c <- 84 }() // start a new goroutine just to send a value + go func() { cs <- "wordy" }() // again, for cs this time + // Select has syntax like a switch statement but each case involves + // a channel operation. It selects a case at random out of the cases + // that are ready to communicate. + select { + case i := <-c: // the value received can be assigned to a variable + fmt.Println("it's a", i) + case <-cs: // or the value received can be discarded + fmt.Println("it's a string") + case <-cc: // empty channel, not ready for communication. + fmt.Println("didn't happen.") + } + // At this point a value was taken from either c or cs. One of the two + // goroutines started above has completed, the other will remain blocked. + + learnWebProgramming() // Go does it. You want to do it too. +} + +// A single function from package http starts a web server. +func learnWebProgramming() { + // ListenAndServe first parameter is TCP address to listen at. + // Second parameter is an interface, specifically http.Handler. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors +} + +// Make pair an http.Handler by implementing its only method, ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Serve data with a method of http.ResponseWriter + w.Write([]byte("You learned Go in Y minutes!")) +} +``` + +## Further Reading + +The root of all things Go is the [official Go web site](http://golang.org/). +There you can follow the tutorial, play interactively, and read lots. + +The language definition itself is highly recommended. It's easy to read +and amazingly short (as language definitions go these days.) + +On the reading list for students of Go is the source code to the standard +library. Comprehensively documented, it demonstrates the best of readable +and understandable Go, Go style, and Go idioms. Click on a function name +in the documentation and the source code comes up! + diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index 79f5d88b..e5517aa8 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -268,7 +268,7 @@ function sayHelloInFiveSeconds(name){ // 기다리지 않고 실행을 마칩니다. 하지만 5초가 지나면 inner에서도 // prompt의 값에 접근할 수 있습니다. } -sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s +sayHelloInFiveSeconds("Adam") // 5초 내로 "Hello, Adam!"이라고 적힌 팝업이 표시됨 /////////////////////////////////// // 5. 객체 심화; 생성자와 프로토타입 @@ -403,7 +403,7 @@ String.prototype.firstCharacter = function(){ // 예를 들어, Object.create가 모든 구현체에서 사용 가능한 것은 아니라고 // 했지만 아래의 폴리필을 이용해 Object.create를 여전히 사용할 수 있습니다. -if (Object.create === undefined){ // don't overwrite it if it exists +if (Object.create === undefined){ // 이미 존재하면 덮어쓰지 않음 Object.create = function(proto){ // 올바른 프로토타입을 가지고 임시 생성자를 만듬 var Constructor = function(){} @@ -432,4 +432,4 @@ MDN의 ['자바스크립트 재입문'](https://developer.mozilla.org/ko/docs/A_ 더불어 이 글에 직접적으로 기여한 분들로, 내용 중 일부는 이 사이트에 있는 루이 딘(Louie Dihn)의 파이썬 튜토리얼과 모질라 개발자 네트워크에 있는 -[자바스크립트 튜토리얼](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)을 참고했습니다.
\ No newline at end of file +[자바스크립트 튜토리얼](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)을 참고했습니다. diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 2badf734..04d119c4 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -327,7 +327,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- 필요할 경우, 하위 클래스의 new()는 기반 클래스의 new()와 유사합니다. function LoudDog:new() newObj = {} - -- set up newObj + -- newObj를 구성 self.__index = self return setmetatable(newObj, self) end diff --git a/pt-br/elisp-pt.html.markdown b/pt-br/elisp-pt.html.markdown new file mode 100644 index 00000000..9031cad9 --- /dev/null +++ b/pt-br/elisp-pt.html.markdown @@ -0,0 +1,359 @@ +--- +language: elisp +contributors: + - ["Bastien Guerry", "http://bzg.fr"] +translators: + - ["Lucas Tadeu Teixeira", "http://ltt.me"] +lang: pt-br +filename: learn-emacs-lisp-pt.el +--- + +```scheme +;; Introdução ao Emacs Lisp em 15 minutos (v0.2d) +;; +;; Autor: Bastien / @bzg2 / http://bzg.fr +;; +;; Antes de começar, leia este texto escrito Peter Norvig: +;; http://norvig.com/21-days.html +;; +;; Agora instale GNU Emacs 24.3: +;; +;; Debian: apt-get install emacs (ou veja as instruções da sua distribuição) +;; OSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg +;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip +;; +;; Informações mais gerais podem ser encontradas em: +;; http://www.gnu.org/software/emacs/#Obtaining + +;; Aviso importante: +;; +;; Realizar este tutorial não danificará seu computador, a menos +;; que você fique tão irritado a ponto de jogá-lo no chão. Neste caso, +;; me abstenho de qualquer responsabilidade. Divirta-se! + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Abra o Emacs. +;; +;; Aperte a tecla `q' para ocultar a mensagem de boas vindas. +;; +;; Agora olhe para a linha cinza na parte inferior da janela: +;; +;; "*scratch*" é o nome do espaço de edição em que você se encontra. +;; Este espaço de edição é chamado "buffer". +;; +;; O buffer de rascunho (i.e., "scratch") é o buffer padrão quando +;; o Emacs é aberto. Você nunca está editando arquivos: você está +;; editando buffers que você pode salvar em um arquivo. +;; +;; "Lisp interaction" refere-se a um conjunto de comandos disponíveis aqui. +;; +;; O Emacs possui um conjunto de comandos embutidos (disponíveis em +;; qualquer buffer) e vários subconjuntos de comandos disponíveis +;; quando você ativa um modo específico. Aqui nós utilizamos +;; `lisp-interaction-mode', que possui comandos para interpretar e navegar +;; em código Elisp. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Pontos e vírgulas iniciam comentários em qualquer parte de uma linha. +;; +;; Programas codificados em Elisp são compostos por expressões simbólicas +;; (conhecidas também por "sexps"): +(+ 2 2) + +;; Esta expressão simbólica significa "Some 2 e 2". + +;; "Sexps" são envoltas em parêntese, possivelmente aninhados: +(+ 2 (+ 1 1)) + +;; Uma expressão simbólica contém átomos ou outras expressões +;; simbólicas. Nos exemplos acima, 1 e 2 são átomos; +;; (+ 2 (+ 1 1)) e (+ 1 1) são expressões simbólicas. + +;; No modo `lisp-interaction-mode' você pode interpretar "sexps". +;; Posicione o cursor logo após o parêntese de fechamento e, +;; então, segure apertado Ctrl e aperte a tecla j ("C-j", em resumo). + +(+ 3 (+ 1 2)) +;; ^ posicione o cursor aqui +;; `C-j' => 6 + +;; `C-j' insere o resultado da interpretação da expressão no buffer. + +;; `C-xC-e' exibe o mesmo resultado na linha inferior do Emacs, +;; chamada de "mini-buffer". Nós geralmente utilizaremos `C-xC-e', +;; já que não queremos poluir o buffer com texto desnecessário. + +;; `setq' armazena um valor em uma variável: +(setq my-name "Bastien") +;; `C-xC-e' => "Bastien" (texto exibido no mini-buffer) + +;; `insert' insere "Hello!" na posição em que se encontra seu cursor: +(insert "Hello!") +;; `C-xC-e' => "Hello!" + +;; Nós executamos `insert' com apenas um argumento ("Hello!"), mas +;; mais argumentos podem ser passados -- aqui utilizamos dois: + +(insert "Hello" " world!") +;; `C-xC-e' => "Hello world!" + +;; Você pode utilizar variávies no lugar de strings: +(insert "Hello, I am " my-name) +;; `C-xC-e' => "Hello, I am Bastien" + +;; Você pode combinar "sexps" em funções: +(defun hello () (insert "Hello, I am " my-name)) +;; `C-xC-e' => hello + +;; Você pode interpretar chamadas de funções: +(hello) +;; `C-xC-e' => Hello, I am Bastien + +;; Os parêntesis vazios na definição da função significam que ela +;; não aceita argumentos. Mas sempre utilizar `my-name' é um tédio! +;; Vamos dizer à função para aceitar um argumento (o argumento é +;; chamado "name"): + +(defun hello (name) (insert "Hello " name)) +;; `C-xC-e' => hello + +;; Agora vamos executar a função com a string "you" como o valor +;; para seu único parâmetro: +(hello "you") +;; `C-xC-e' => "Hello you" + +;; Aí sim! + +;; Respire um pouco. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Agora mude para um novo buffer chamado "*test*": + +(switch-to-buffer-other-window "*test*") +;; `C-xC-e' +;; => [a tela exibirá duas janelas e o cursor estará no buffer *test*] + +;; Posicione o mouse sobre a janela superior e clique com o botão +;; esquerdo para voltar. Ou você pode utilizar `C-xo' (i.e. segure +;; ctrl-x e aperte o) para voltar para a outra janela, de forma interativa. + +;; Você pode combinar várias "sexps" com `progn': +(progn + (switch-to-buffer-other-window "*test*") + (hello "you")) +;; `C-xC-e' +;; => [A tela exibirá duas janelas e o cursor estará no buffer *test*] + +;; Agora, se você não se importar, pararei de pedir que você aperte +;; `C-xC-e': faça isso para cada "sexp" que escrevermos. + +;; Sempre volte para o buffer *scratch* com o mouse ou `C-xo'. + +;; Frequentemente, é útil apagar o conteúdo do buffer: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "there")) + +;; Ou voltar para a outra janela: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "you") + (other-window 1)) + +;; Você pode armazenar um valor em uma variável local utilizando `let': +(let ((local-name "you")) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello local-name) + (other-window 1)) + +;; Neste caso, não é necessário utilizar `progn' já que `let' combina +;; várias "sexps". + +;; Vamos formatar uma string: +(format "Hello %s!\n" "visitor") + +;; %s é um espaço reservado para uma string, substituído por "visitor". +;; \n é um caractere de nova linha. + +;; Vamos refinar nossa função utilizando `format': +(defun hello (name) + (insert (format "Hello %s!\n" name))) + +(hello "you") + +;; Vamos criar outra função que utilize `let': +(defun greeting (name) + (let ((your-name "Bastien")) + (insert (format "Hello %s!\n\nI am %s." + name ; the argument of the function + your-name ; the let-bound variable "Bastien" + )))) + +;; E executá-la: +(greeting "you") + +;; Algumas funções são interativas: +(read-from-minibuffer "Enter your name: ") + +;; Ao ser interpretada, esta função retorna o que você digitou no prompt. + +;; Vamos fazer nossa função `greeting' pedir pelo seu nome: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (insert (format "Hello!\n\nI am %s and you are %s." + from-name ; the argument of the function + your-name ; the let-bound var, entered at prompt + )))) + +(greeting "Bastien") + +;; Vamos finalizá-la fazendo-a exibir os resultados em outra janela: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (insert (format "Hello %s!\n\nI am %s." your-name from-name)) + (other-window 1))) + +;; Agora teste-a: +(greeting "Bastien") + +;; Respire um pouco. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Vamos armazenar uma lista de nomes: +(setq list-of-names '("Sarah" "Chloe" "Mathilde")) + +;; Pegue o primeiro elemento desta lista utilizando `car': +(car list-of-names) + +;; Pegue uma lista de todos os elementos, exceto o primeiro, utilizando +;; `cdr': +(cdr list-of-names) + +;; Adicione um elemento ao início da lista com `push': +(push "Stephanie" list-of-names) + +;; NOTA: `car' e `cdr' não modificam a lista, `push' sim. +;; Esta é uma diferença importante: algumas funções não têm qualquer +;; efeito colateral (como `car'), enquanto outras sim (como `push'). + +;; Vamos executar `hello' para cada elemento em `list-of-names': +(mapcar 'hello list-of-names) + +;; Refine `greeting' para saudar todos os nomes em `list-of-names': +(defun greeting () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (mapcar 'hello list-of-names) + (other-window 1)) + +(greeting) + +;; Você se lembra da função `hello' que nós definimos lá em cima? Ela +;; recebe um argumento, um nome. `mapcar' executa `hello', sucessivamente, +;; utilizando cada elemento de `list-of-names' como argumento para `hello'. + +;; Agora vamos arrumar, um pouco, o que nós temos escrito no buffer: + +(defun replace-hello-by-bonjour () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (search-forward "Hello") + (replace-match "Bonjour")) + (other-window 1)) + +;; (goto-char (point-min)) vai para o início do buffer. +;; (search-forward "Hello") busca pela string "Hello". +;; (while x y) interpreta a(s) sexp(s) y enquanto x retornar algo. +;; Se x retornar `nil' (nada), nós saímos do laço. + +(replace-hello-by-bonjour) + +;; Você deveria ver todas as ocorrências de "Hello" no buffer *test* +;; substituídas por "Bonjour". + +;; Você deveria, também, receber um erro: "Search failed: Hello". +;; +;; Para evitar este erro, você precisa dizer ao `search-forward' se ele +;; deveria parar de buscar em algum ponto no buffer, e se ele deveria +;; falhar de forma silenciosa quando nada fosse encontrado: + +;; (search-forward "Hello" nil t) dá conta do recado: + +;; O argumento `nil' diz: a busca não está limitada a uma posição. +;; O argumento `t' diz: falhe silenciosamente quando nada for encontrado. + +;; Nós utilizamos esta "sexp" na função abaixo, que não gera um erro: + +(defun hello-to-bonjour () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + ;; Say hello to names in `list-of-names' + (mapcar 'hello list-of-names) + (goto-char (point-min)) + ;; Replace "Hello" by "Bonjour" + (while (search-forward "Hello" nil t) + (replace-match "Bonjour")) + (other-window 1)) + +(hello-to-bonjour) + +;; Vamos colorir os nomes: + +(defun boldify-names () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (re-search-forward "Bonjour \\(.+\\)!" nil t) + (add-text-properties (match-beginning 1) + (match-end 1) + (list 'face 'bold))) + (other-window 1)) + +;; Esta função introduz `re-search-forward': ao invés de buscar +;; pela string "Bonjour", você busca por um padrão utilizando uma +;; "expressão regular" (abreviada pelo prefixo "re-"). + +;; A expressão regular é "Bonjour \\(.+\\)!" e lê-se: +;; a string "Bonjour ", e +;; um grupo de | que é o \\( ... \\) +;; quaisquer caracteres | que é o . +;; possivelmente repetidos | que é o + +;; e a string "!". + +;; Preparado? Teste! + +(boldify-names) + +;; `add-text-properties' adiciona... propriedades de texto, como uma fonte. + +;; OK, terminamos por aqui. Feliz Hacking! + +;; Se você quiser saber mais sobre uma variável ou função: +;; +;; C-h v uma-variável RET +;; C-h f uma-função RET +;; +;; Para ler o manual de Emacs Lisp que vem com o Emacs: +;; +;; C-h i m elisp RET +;; +;; Para ler uma introdução online ao Emacs Lisp: +;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html + +;; Agradecimentos a estas pessoas por seu feedback e sugestões: +;; - Wes Hardaker +;; - notbob +;; - Kevin Montuori +;; - Arne Babenhauserheide +;; - Alan Schmitt +;; - LinXitoW +;; - Aaron Meurer +``` diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown index e08bb5a8..5afd46d0 100644 --- a/pt-br/python-pt.html.markdown +++ b/pt-br/python-pt.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Vilson Vieira", "http://automata.cc"] -lang: pt-bf +lang: pt-br filename: learnpython-pt.py --- diff --git a/ruby.html.markdown b/ruby.html.markdown index 68c5b524..19f2ec86 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] --- ```ruby @@ -117,11 +118,11 @@ status == :approved #=> false # Arrays # This is an array -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can contain different types of items -array = [1, "hello", false] #=> => [1, "hello", false] +[1, "hello", false] #=> [1, "hello", false] # Arrays can be indexed # From the front @@ -173,9 +174,9 @@ new_hash.keys #=> [:defcon, :action] if true "if statement" elsif false - "else if, optional" + "else if, optional" else - "else, also optional" + "else, also optional" end for counter in 1..5 @@ -190,7 +191,8 @@ end # HOWEVER, No-one uses for loops. # Instead you should use the "each" method and pass it a block. # A block is a bunch of code that you can pass to a method like "each". -# It is analogous to lambdas, anonymous functions or closures in other programming languages. +# It is analogous to lambdas, anonymous functions or closures in other +# programming languages. # # The "each" method of a range runs the block once for each element of the range. # The block is passed a counter as a parameter. diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index 764eed54..51efaac3 100755 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -17,6 +17,7 @@ Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语 如果是Python 3,请在网络上寻找其他教程 ```python + # 单行注释 """ 多行字符串可以用 三个引号包裹,不过这也可以被当做 @@ -28,84 +29,84 @@ Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语 #################################################### # 数字类型 -3 #=> 3 +3 # => 3 # 简单的算数 -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 # 整数的除法会自动取整 -5 / 2 #=> 2 +5 / 2 # => 2 # 要做精确的除法,我们需要引入浮点数 2.0 # 浮点数 -11.0 / 4.0 #=> 2.75 好多了 +11.0 / 4.0 # => 2.75 精确多了 # 括号具有最高优先级 -(1 + 3) * 2 #=> 8 +(1 + 3) * 2 # => 8 -# 布尔值也是原始数据类型 +# 布尔值也是基本的数据类型 True False -# 用not来取非 -not True #=> False -not False #=> True +# 用 not 来取非 +not True # => False +not False # => True # 相等 -1 == 1 #=> True -2 == 1 #=> False +1 == 1 # => True +2 == 1 # => False # 不等 -1 != 1 #=> False -2 != 1 #=> True +1 != 1 # => False +2 != 1 # => True # 更多的比较操作符 -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True # 比较运算可以连起来写! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False +1 < 2 < 3 # => True +2 < 3 < 2 # => False -# 字符串通过"或'括起来 +# 字符串通过 " 或 ' 括起来 "This is a string." 'This is also a string.' # 字符串通过加号拼接 -"Hello " + "world!" #=> "Hello world!" +"Hello " + "world!" # => "Hello world!" # 字符串可以被视为字符的列表 -"This is a string"[0] #=> 'T' +"This is a string"[0] # => 'T' # % 可以用来格式化字符串 "%s can be %s" % ("strings", "interpolated") -# 也可以用format方法来格式化字符串 +# 也可以用 format 方法来格式化字符串 # 推荐使用这个方法 "{0} can be {1}".format("strings", "formatted") # 也可以用变量名代替数字 "{name} wants to eat {food}".format(name="Bob", food="lasagna") # None 是对象 -None #=> None +None # => None # 不要用相等 `==` 符号来和None进行比较 -# 要用 `is` -"etc" is None #=> False -None is None #=> True +# 要用 `is` +"etc" is None # => False +None is None # => True # 'is' 可以用来比较对象的相等性 # 这个操作符在比较原始数据时没多少用,但是比较对象时必不可少 -# None, 0, 和空字符串都被算作False -# 其他的均为True -0 == False #=> True -"" == False #=> True +# None, 0, 和空字符串都被算作 False +# 其他的均为 True +0 == False # => True +"" == False # => True #################################################### @@ -116,16 +117,16 @@ None is None #=> True print "I'm Python. Nice to meet you!" -# 给变量赋值前不需要事先生命 -some_var = 5 # 规范用小写字母和下划线来做为变量名 -some_var #=> 5 +# 给变量赋值前不需要事先声明 +some_var = 5 # 一般建议使用小写字母和下划线组合来做为变量名 +some_var # => 5 -# 访问之前为赋值的变量会抛出异常 -# 查看控制流程一节来了解异常处理 -some_other_var # 抛出命名异常 +# 访问未赋值的变量会抛出异常 +# 可以查看控制流程一节来了解如何异常处理 +some_other_var # 抛出 NameError -# if语句可以作为表达式来使用 -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" +# if 语句可以作为表达式来使用 +"yahoo!" if 3 > 2 else 2 # => "yahoo!" # 列表用来保存序列 li = [] @@ -133,64 +134,64 @@ li = [] other_li = [4, 5, 6] # 在列表末尾添加元素 -li.append(1) #li 现在是 [1] -li.append(2) #li 现在是 [1, 2] -li.append(4) #li 现在是 [1, 2, 4] -li.append(3) #li 现在是 [1, 2, 4, 3] +li.append(1) # li 现在是 [1] +li.append(2) # li 现在是 [1, 2] +li.append(4) # li 现在是 [1, 2, 4] +li.append(3) # li 现在是 [1, 2, 4, 3] # 移除列表末尾元素 -li.pop() #=> 3 and li is now [1, 2, 4] -# 放回来 +li.pop() # => 3 li 现在是 [1, 2, 4] +# 重新加进去 li.append(3) # li is now [1, 2, 4, 3] again. # 像其他语言访问数组一样访问列表 -li[0] #=> 1 +li[0] # => 1 # 访问最后一个元素 -li[-1] #=> 3 +li[-1] # => 3 # 越界会抛出异常 -li[4] # 抛出越界异常 +li[4] # 抛出越界异常 # 切片语法需要用到列表的索引访问 # 可以看做数学之中左闭右开区间 -li[1:3] #=> [2, 4] +li[1:3] # => [2, 4] # 省略开头的元素 -li[2:] #=> [4, 3] +li[2:] # => [4, 3] # 省略末尾的元素 -li[:3] #=> [1, 2, 4] +li[:3] # => [1, 2, 4] # 删除特定元素 -del li[2] # li 现在是 [1, 2, 3] +del li[2] # li 现在是 [1, 2, 3] # 合并列表 -li + other_li #=> [1, 2, 3, 4, 5, 6] - 不改变这两个列表 +li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会不改变这两个列表 -# 通过拼接合并列表 -li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] +# 通过拼接来合并列表 +li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] -# 用in来返回元素是否在列表中 -1 in li #=> True +# 用 in 来返回元素是否在列表中 +1 in li # => True # 返回列表长度 -len(li) #=> 6 +len(li) # => 6 -# 元组类似于列表,但是他是不可改变的 +# 元组类似于列表,但它是不可改变的 tup = (1, 2, 3) -tup[0] #=> 1 +tup[0] # => 1 tup[0] = 3 # 类型错误 # 对于大多数的列表操作,也适用于元组 -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True # 你可以将元组解包赋给多个变量 -a, b, c = (1, 2, 3) # a是1,b是2,c是3 -# 如果不加括号,那么会自动视为元组 +a, b, c = (1, 2, 3) # a 是 1,b 是 2,c 是 3 +# 如果不加括号,将会被自动视为元组 d, e, f = 4, 5, 6 # 现在我们可以看看交换两个数字是多么容易的事 -e, d = d, e # d是5,e是4 +e, d = d, e # d 是 5,e 是 4 # 字典用来储存映射关系 @@ -199,59 +200,59 @@ empty_dict = {} filled_dict = {"one": 1, "two": 2, "three": 3} # 字典也用中括号访问元素 -filled_dict["one"] #=> 1 +filled_dict["one"] # => 1 # 把所有的键保存在列表中 -filled_dict.keys() #=> ["three", "two", "one"] +filled_dict.keys() # => ["three", "two", "one"] # 键的顺序并不是唯一的,得到的不一定是这个顺序 # 把所有的值保存在列表中 -filled_dict.values() #=> [3, 2, 1] +filled_dict.values() # => [3, 2, 1] # 和键的顺序相同 # 判断一个键是否存在 -"one" in filled_dict #=> True -1 in filled_dict #=> False +"one" in filled_dict # => True +1 in filled_dict # => False -# 查询一个不存在的键会抛出键异常 -filled_dict["four"] # 键异常 +# 查询一个不存在的键会抛出 KeyError +filled_dict["four"] # KeyError -# 用get方法来避免键异常 -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# get方法支持在不存在的时候返回一个默认值 -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 +# 用 get 方法来避免 KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# get 方法支持在不存在的时候返回一个默认值 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 -# Setdefault是一个更安全的添加字典元素的方法 -filled_dict.setdefault("five", 5) #filled_dict["five"] 的值为 5 -filled_dict.setdefault("five", 6) #filled_dict["five"] 的值仍然是 5 +# setdefault 是一个更安全的添加字典元素的方法 +filled_dict.setdefault("five", 5) # filled_dict["five"] 的值为 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5 # 集合储存无顺序的元素 empty_set = set() -# 出事话一个集合 -some_set = set([1,2,2,3,4]) # filled_set 现在是 set([1, 2, 3, 4]) +# 初始化一个集合 +some_set = set([1, 2, 2, 3, 4]) # filled_set 现在是 set([1, 2, 3, 4]) # Python 2.7 之后,大括号可以用来表示集合 -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} -# 为集合添加元素 -filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} +# 向集合添加元素 +filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} -# 用&来实现集合的交 +# 用 & 来计算集合的交 other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} +filled_set & other_set # => {3, 4, 5} -# 用|来实现集合的并 -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} +# 用 | 来计算集合的并 +filled_set | other_set # => {1, 2, 3, 4, 5, 6} -# 用-来实现集合的差 -{1,2,3,4} - {2,3,5} #=> {1, 4} +# 用 - 来计算集合的差 +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} -# 用in来判断元素是否存在于集合中 -2 in filled_set #=> True -10 in filled_set #=> False +# 用 in 来判断元素是否存在于集合中 +2 in filled_set # => True +10 in filled_set # => False #################################################### @@ -261,13 +262,13 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # 新建一个变量 some_var = 5 -# 这是个if语句,在python中缩进是很重要的。 -# 会输出 "some var is smaller than 10" +# 这是个 if 语句,在 python 中缩进是很重要的。 +# 下面的代码片段将会输出 "some var is smaller than 10" if some_var > 10: print "some_var is totally bigger than 10." elif some_var < 10: # 这个 elif 语句是不必须的 print "some_var is smaller than 10." -else: # 也不是必须的 +else: # 这个 else 也不是必须的 print "some_var is indeed 10." @@ -281,7 +282,7 @@ else: # 也不是必须的 for animal in ["dog", "cat", "mouse"]: # 你可以用 % 来格式化字符串 print "%s is a mammal" % animal - + """ `range(number)` 返回从0到给定数字的列表 输出: @@ -294,7 +295,7 @@ for i in range(4): print i """ -While循环 +while 循环 输出: 0 1 @@ -304,29 +305,29 @@ While循环 x = 0 while x < 4: print x - x += 1 # Shorthand for x = x + 1 + x += 1 # x = x + 1 的简写 -# 用 try/except块来处理异常 +# 用 try/except 块来处理异常 # Python 2.6 及以上适用: try: - # 用raise来抛出异常 + # 用 raise 来抛出异常 raise IndexError("This is an index error") except IndexError as e: - pass # Pass就是什么都不做,不过通常这里会做一些恢复工作 + pass # pass 就是什么都不做,不过通常这里会做一些恢复工作 #################################################### ## 4. 函数 #################################################### -# 用def来新建函数 +# 用 def 来新建函数 def add(x, y): print "x is %s and y is %s" % (x, y) - return x + y # Return values with a return statement + return x + y # 通过 return 来返回值 # 调用带参数的函数 -add(5, 6) #=> 输出 "x is 5 and y is 6" 返回 11 +add(5, 6) # => 输出 "x is 5 and y is 6" 返回 11 # 通过关键字赋值来调用函数 add(y=6, x=5) # 顺序是无所谓的 @@ -335,7 +336,7 @@ add(y=6, x=5) # 顺序是无所谓的 def varargs(*args): return args -varargs(1, 2, 3) #=> (1,2,3) +varargs(1, 2, 3) # => (1,2,3) # 我们也可以定义接受多个变量的函数,这些变量是按照关键字排列的 @@ -343,7 +344,7 @@ def keyword_args(**kwargs): return kwargs # 实际效果: -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # 你也可以同时将一个函数定义成两种形式 def all_the_args(*args, **kwargs): @@ -355,38 +356,38 @@ all_the_args(1, 2, a=3, b=4) prints: {"a": 3, "b": 4} """ -# 当调用函数的时候,我们也可以和之前所做的相反,把元组和字典展开为参数 +# 当调用函数的时候,我们也可以进行相反的操作,把元组和字典展开为参数 args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # 等价于 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 等价于 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 等价于 foo(1, 2, 3, 4, a=3, b=4) -# Python 有一等函数: +# 函数在 python 中是一等公民 def create_adder(x): def adder(y): return x + y return adder add_10 = create_adder(10) -add_10(3) #=> 13 +add_10(3) # => 13 # 匿名函数 -(lambda x: x > 2)(3) #=> True +(lambda x: x > 2)(3) # => True # 内置高阶函数 -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # 可以用列表方法来对高阶函数进行更巧妙的引用 -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### ## 5. 类 #################################################### -# 我们新建的类是从object类中继承的 +# 我们新建的类是从 object 类中继承的 class Human(object): # 类属性,由所有类的对象共享 @@ -397,9 +398,9 @@ class Human(object): # 将参数赋给对象成员属性 self.name = name - # 成员方法,参数要有self + # 成员方法,参数要有 self def say(self, msg): - return "%s: %s" % (self.name, msg) + return "%s: %s" % (self.name, msg) # 类方法由所有类的对象共享 # 这类方法在调用时,会把类本身传给第一个参数 @@ -421,15 +422,15 @@ j = Human("Joel") print j.say("hello") # 输出 "Joel: hello" # 访问类的方法 -i.get_species() #=> "H. sapiens" +i.get_species() # => "H. sapiens" # 改变共享属性 Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" # 访问静态变量 -Human.grunt() #=> "*grunt*" +Human.grunt() # => "*grunt*" #################################################### @@ -438,12 +439,12 @@ Human.grunt() #=> "*grunt*" # 我们可以导入其他模块 import math -print math.sqrt(16) #=> 4 +print math.sqrt(16) # => 4 -# 我们也可以从一个模块中特定的函数 +# 我们也可以从一个模块中导入特定的函数 from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 # 从模块中导入所有的函数 # 警告:不推荐使用 @@ -451,13 +452,13 @@ from math import * # 简写模块名 import math as m -math.sqrt(16) == m.sqrt(16) #=> True +math.sqrt(16) == m.sqrt(16) # => True # Python的模块其实只是普通的python文件 # 你也可以创建自己的模块,并且导入它们 # 模块的名字就和文件的名字相同 -# 以可以通过下面的信息找找要成为模块需要什么属性或方法 +# 也可以通过下面的方法查看模块中有什么属性和方法 import math dir(math) |