Merge pull request #2 from kaernyk/master

Update repo
This commit is contained in:
kaernyk 2014-09-09 22:12:46 -04:00
commit 48d022b54d
26 changed files with 790 additions and 133 deletions

View File

@ -8,6 +8,7 @@ contributors:
- ["Denis Arh", "https://github.com/darh"] - ["Denis Arh", "https://github.com/darh"]
- ["akirahirose", "https://twitter.com/akirahirose"] - ["akirahirose", "https://twitter.com/akirahirose"]
- ["Anton Strömkvist", "http://lutic.org/"] - ["Anton Strömkvist", "http://lutic.org/"]
- ["Rahil Momin", "https://github.com/iamrahil"]
filename: LearnBash.sh filename: LearnBash.sh
--- ---
@ -140,6 +141,12 @@ do
echo "$VARIABLE" echo "$VARIABLE"
done done
# Or write it the "traditional for loop" way:
for ((a=1; a <= 3; a++))
do
echo $a
done
# They can also be used to act on files.. # They can also be used to act on files..
# This will run the command 'cat' on file1 and file2 # This will run the command 'cat' on file1 and file2
for VARIABLE in file1 file2 for VARIABLE in file1 file2

View File

@ -4,6 +4,7 @@ filename: learnc.c
contributors: contributors:
- ["Adam Bard", "http://adambard.com/"] - ["Adam Bard", "http://adambard.com/"]
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
--- ---
@ -175,6 +176,9 @@ int main() {
i2 * i1; // => 2 i2 * i1; // => 2
i1 / i2; // => 0 (0.5, but truncated towards 0) i1 / i2; // => 0 (0.5, but truncated towards 0)
// You need to cast at least one integer to float to get a floating-point result
(float)i1 / i2 // => 0.5f
i1 / (double)i2 // => 0.5 // Same with double
f1 / f2; // => 0.5, plus or minus epsilon f1 / f2; // => 0.5, plus or minus epsilon
// Floating-point numbers and calculations are not exact // Floating-point numbers and calculations are not exact
@ -194,9 +198,11 @@ int main() {
2 >= 2; // => 1 2 >= 2; // => 1
// C is not Python - comparisons don't chain. // C is not Python - comparisons don't chain.
// WRONG: // Warning: The line below will compile, but it means `(0 < a) < 2`.
//int between_0_and_2 = 0 < a < 2; // This expression is always true, because (0 < a) could be either 1 or 0.
// Correct: // In this case it's 1, because (0 < 1).
int between_0_and_2 = 0 < a < 2;
// Instead use:
int between_0_and_2 = 0 < a && a < 2; int between_0_and_2 = 0 < a && a < 2;
// Logic works on ints // Logic works on ints

View File

@ -11,7 +11,7 @@ As one of the succeeders of JavaScript, CoffeeScript tries its best to output re
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript. See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
``` coffeescript ```coffeescript
# CoffeeScript is a hipster language. # CoffeeScript is a hipster language.
# It goes with the trends of many modern languages. # It goes with the trends of many modern languages.
# So comments are like Ruby and Python, they use number symbols. # So comments are like Ruby and Python, they use number symbols.

View File

@ -17,7 +17,7 @@ Another popular and recent book is
```scheme ```common_lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 0. Syntax ;;; 0. Syntax

View File

@ -23,20 +23,22 @@ in Clojure with minimal effort:
(run-server myapp {:port 5000})) (run-server myapp {:port 5000}))
``` ```
Create a project with [Leiningen](http://leiningen.org/): **Step 1:** Create a project with [Leiningen](http://leiningen.org/):
``` ```
lein new myapp lein new myapp
``` ```
Add your dependencies: **Step 2:** Put the above code in `src/myapp/core.clj`
**Step 3:** Add some dependencies to `project.clj`:
``` ```
[compojure "1.1.8"] [compojure "1.1.8"]
[http-kit "2.1.16"] [http-kit "2.1.16"]
``` ```
And run: **Step 4:** Run:
``` ```
lein run -m myapp.core lein run -m myapp.core
@ -81,18 +83,26 @@ The body may be a function, which must accept the request as a parameter:
(GET "/" [] (fn [req] "Do something with req"))) (GET "/" [] (fn [req] "Do something with req")))
``` ```
Route patterns may include named parameters, Or, you can just use the request directly:
```clojure
(defroutes myapp
(GET "/" req "Do something with req"))
```
Route patterns may include named parameters:
```clojure ```clojure
(defroutes myapp (defroutes myapp
(GET "/hello/:name" [name] (str "Hello " name))) (GET "/hello/:name" [name] (str "Hello " name)))
``` ```
You can match entire paths with * You can adjust what each parameter matches by supplying a regex:
```clojure ```clojure
(defroutes myapp (defroutes myapp
(GET "/file/*.*" [*] (str *))) (GET ["/file/:name.:ext" :name #".*", :ext #".*"] [name ext]
(str "File: " name ext))
``` ```
Handlers may utilize query parameters: Handlers may utilize query parameters:
@ -100,10 +110,10 @@ Handlers may utilize query parameters:
```clojure ```clojure
(defroutes myapp (defroutes myapp
(GET "/posts" [] (GET "/posts" []
(fn [req] (fn [req]
(let [title (get (:params req) "title") (let [title (get (:params req) "title")
author (get (:params req) "title")] author (get (:params req) "title")]
" Do something with title and author")))) " Do something with title and author"))))
``` ```
Or, for POST and PUT requests, form parameters Or, for POST and PUT requests, form parameters
@ -111,10 +121,10 @@ Or, for POST and PUT requests, form parameters
```clojure ```clojure
(defroutes myapp (defroutes myapp
(POST "/posts" [] (POST "/posts" []
(fn [req] (fn [req]
(let [title (get (:params req) "title") (let [title (get (:params req) "title")
author (get (:params req) "title")] author (get (:params req) "title")]
"Do something with title and author")))) "Do something with title and author"))))
``` ```
@ -123,16 +133,16 @@ Or, for POST and PUT requests, form parameters
The return value of a route block determines at least the response body The return value of a route block determines at least the response body
passed on to the HTTP client, or at least the next middleware in the passed on to the HTTP client, or at least the next middleware in the
ring stack. Most commonly, this is a string, as in the above examples. ring stack. Most commonly, this is a string, as in the above examples.
But, you may also return a [response body](https://github.com/mmcgrana/ring/blob/master/SPEC): But, you may also return a [response map](https://github.com/mmcgrana/ring/blob/master/SPEC):
```clojure ```clojure
(defroutes myapp (defroutes myapp
(GET "/" [] (GET "/" []
{:status 200 :body "Hello World"}) {:status 200 :body "Hello World"})
(GET "/is-403" [] (GET "/is-403" []
{:status 403 :body ""}) {:status 403 :body ""})
(GET "/is-json" [] (GET "/is-json" []
{:status 200 :headers {"Content-Type" "application/json"} :body "{}"})) {:status 200 :headers {"Content-Type" "application/json"} :body "{}"}))
``` ```
### Static Files ### Static Files
@ -164,7 +174,7 @@ To use templating with Compojure, you'll need a template library. Here are a few
(defroutes myapp (defroutes myapp
(GET "/hello/:name" [name] (GET "/hello/:name" [name]
(render-string "Hello {{name}}" {:name name}))) (render-string "Hello {{name}}" {:name name})))
``` ```
You can easily read in templates from your resources directory. Here's a helper function You can easily read in templates from your resources directory. Here's a helper function
@ -177,7 +187,7 @@ You can easily read in templates from your resources directory. Here's a helper
(defroutes myapp (defroutes myapp
(GET "/hello/:name" [name] (GET "/hello/:name" [name]
(render-string (read-template "templates/hello.html") {:name name}))) (render-string (read-template "templates/hello.html") {:name name})))
``` ```
#### [Selmer](https://github.com/yogthos/Selmer) #### [Selmer](https://github.com/yogthos/Selmer)
@ -189,7 +199,7 @@ You can easily read in templates from your resources directory. Here's a helper
(defroutes myapp (defroutes myapp
(GET "/hello/:name" [name] (GET "/hello/:name" [name]
(render-file "templates/hello.html" {:name name}))) (render-file "templates/hello.html" {:name name})))
``` ```
#### [Hiccup](https://github.com/weavejester/hiccup) #### [Hiccup](https://github.com/weavejester/hiccup)
@ -201,11 +211,11 @@ You can easily read in templates from your resources directory. Here's a helper
(defroutes myapp (defroutes myapp
(GET "/hello/:name" [name] (GET "/hello/:name" [name]
(hiccup/html (hiccup/html
[:html [:html
[:body [:body
[:h1 {:class "title"} [:h1 {:class "title"}
(str "Hello " name)]]]))) (str "Hello " name)]]])))
``` ```
#### [Markdown](https://github.com/yogthos/markdown-clj) #### [Markdown](https://github.com/yogthos/markdown-clj)
@ -217,9 +227,11 @@ You can easily read in templates from your resources directory. Here's a helper
(defroutes myapp (defroutes myapp
(GET "/hello/:name" [name] (GET "/hello/:name" [name]
(md-to-html-string "## Hello, world"))) (md-to-html-string "## Hello, world")))
``` ```
Further reading: Further reading:
[Clojure for the Brave and True](http://www.braveclojure.com/) * [Official Compojure Documentation](https://github.com/weavejester/compojure/wiki)
* [Clojure for the Brave and True](http://www.braveclojure.com/)

View File

@ -14,7 +14,7 @@ fácilmente a HTML (y, actualmente, otros formatos también).
¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! ¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
``` ```markdown
<!-- Markdown está basado en HTML, así que cualquier archivo HTML es Markdown <!-- Markdown está basado en HTML, así que cualquier archivo HTML es Markdown
válido, eso significa que podemos usar elementos HTML en Markdown como, por válido, eso significa que podemos usar elementos HTML en Markdown como, por
ejemplo, el comentario y no serán afectados por un parseador Markdown. Aún ejemplo, el comentario y no serán afectados por un parseador Markdown. Aún

View File

@ -0,0 +1,525 @@
---
language: javascript
contributors:
- ['Adam Brenecki', 'http://adam.brenecki.id.au']
- ['Ariel Krakowski', 'http://www.learneroo.com']
filename: javascript-fr.js
translators:
- ['@nbrugneaux', 'https://nicolasbrugneaux.me']
lang: fr-fr
---
JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995.
Le langage avait à l'origine pour but d'être un langage de scripting simple
pour les sites web, complétant le Java (à ne pas confondre avec JavaScript)
pour des applications web complexes. Mais son intégration très proche et
simple des pages web, ainsi que le support natif des navigateurs a rendu
le JavaScript incontournable aujourd'hui tant bien dans le front-end que
dans le back-end.
En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à
Node.JS, un projet qui offre un environnement indépendant dans lequel un
interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome,
peut être utilisé directement côté serveur pour exécuter des programmes écrits
en JavaScript.
```js
// Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs,
/* et les commentaires sur plusieurs lignes commencent avec slash-étoile
et finissent avec étoile-slash */
// Toutes les expressions peuvent finir par ;
doStuff();
// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés
// lors de linterprétation aux sauts de ligne, sauf exceptions
doStuff()
// Parce que ces cas peuvent produire des effets inattendus, nous utiliserons
// des point-virgules dans ce guide.
///////////////////////////////////
// 1. Nombres, Chaines de caractères et Opérateurs
// JavaScript a un seul type de nombre (qui est un 64-bit IEEE 754 double (décimaux))
// Comme avec le Lua, ne paniquez pas à cause du manque d'int (entiers) : les
// doubles ont un mantisse de 52 bits, ce qui est assez pour stocker des int jusqu'à
// 9 x 10¹⁵ exactement.
3; // = 3
1.5; // = 1.5
// L'arithmétique de base fonctionne comme vous vous y attendriez
1 + 1; // = 2
8 - 1; // = 7
10 * 2; // = 20
35 / 5; // = 7
// Ainsi que les divisions non-entières
5 / 2; // = 2.5
// Les opérations bits à bits fonctionnent aussi, quand vous effectuez une opération
// bits à bits, votre nombre décimal est converti en entier *jusqu'à* 32 bits.
1 << 2; // = 4
// Comme en mathématiques, la priorité est donnée aux parenthèses.
(1 + 3) * 2; // = 8
// Il existe 3 valeurs spéciales pour les nombres:
Infinity; // le résultat de 1/0 par exemple
-Infinity; // le résultat de -1/0 par exemple
NaN; // le résultat de 0/0 par exemple
// Il existe également le type booléen.
true; // vrai
false; // faux
// Les chaines de caractères (strings) sont créees avec " ou ' indifféremment, la seule
// raison de choisir l'un ou l'autre est la cohérence dans votre code.
"abc";
'Hello, world';
// La négation utilise le symbole !
!true; // = false
!false; // = true
// L'égalité est === ou ==
// === compare la valeur exacte 2 === '2' // = false
// == convertit la valeur pour comparer 2 === '2' // = true
// En général, il vaut mieux utiliser === pour ne pas faire d'erreur.
1 === 1; // = true
2 === 1; // = false
// L'inégalité est !== ou !=, basé sur le même principe qu'avant.
1 !== 1; // = false
2 !== 1; // = true
// Plus de comparaisons :
1 < 10; // = true
1 > 10; // = false
2 <= 2; // = true
2 >= 2; // = true
// Les chaines de caractères se concatènent avec +
'Hello ' + 'world!'; // = 'Hello world!'
// et peuvent être comparées alphabétiquement avec < et >
'a' < 'b'; // = true
// Vous pouvez accéder les caractères dans une string avec charAt
'This is a string'.charAt(0); // = 'T'
// ... ou utiliser substring pour avoir un plus gros morceau
'Hello world'.substring(0, 5); // = 'Hello'
// la longueur, length, est une propriété, donc n'utilisez pas de ()
'Hello'.length; // = 5
// Il y a également null et undefined
null; // utilisé pour une non-valeur
undefined; // utilisé pour une valeur actuellement non présente (cependant,
// undefined est aussi une valeur valide)
// false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste
// est 'presque-vrai' (truthy)
// Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0')
///////////////////////////////////
// 2. Variables, Tableaux et Objets
// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est
// dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =.
var someVar = 5;
// si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict)
someOtherVar = 10;
// ... mais la variable aura une portée globale (plus communément trouvé en tant
// que "global scope" en anglais), et non pas une portée limitée à la fonction
// dans laquelle vous l'aviez définie.
// Les variables déclarées et non assignées sont undefined par défaut
var someThirdVar;
var someThirdVar = undefined;
// ... sont deux déclarations identiques.
// Il y a des raccourcis pour les opérations mathématiques:
someVar += 5; // équivalent pour someVar = someVar + 5;
someVar *= 10; // de même, someVar = someVar * 100;
someVar++; // = someVar += 1;
someVar--; // = someVar -= 1;
// Les tableaux (Arrays) sont des listes ordonnées de valeurs, de tous types.
var myArray = ['Hello', 45, true];
// Leurs membres peuvent être accédés en utilisant les crochets
// Les indices commencent à 0.
myArray[1]; // = 45
// Les tableaux sont modifiables, ainsi que leurs longueurs
myArray.push( 'World' );
myArray.length; // = 4
// Ajout/Modification à un index spécifique
myArray[3] = 'Hello';
// Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres
// langages : ils sont une liste non-ordonnée de paires clé-valeur.
var myObj = {key1: 'Hello', key2: 'World'};
// Les clés sont des strings, mais les ' ou " sont optionels si elles sont des
// noms valides en JavaScript. Les valeurs peuvent être de n'importe quel type.
var myObj = {myKey: 'myValue', 'my other key': 4};
// Les attributs d'objets peuvent être accédés avec les crochets
myObj['my other key']; // = 4
// .. ou avec un point si la clé est un identifiant valide.
myObj.myKey; // = 'myValue'
// Les objets sont eux aussi modifiables.
myObj.myThirdKey = true;
// Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined
myObj.myFourthKey; // = undefined
///////////////////////////////////
// 3. Logique et structures de contrôle
// Les si (if) fonctionnent comme vous vous y attendez.
var count = 1;
if (count === 3) {
// seulement quand count est 3
}
else if (count === 4) {
// uniquement quand count est 4
}
else {
// le reste du temps, si ni 3, ni 4.
}
// De même pour while.
while (true) {
// Une boucle infinie !
}
// Les boucles do-while sont pareilles, mais sont exécutées au moins une fois.
var input
do {
input = getInput();
} while (!isValid(input))
// La boucle for est la même qu'en C ou en Java:
// initialisation; condition pour continuer; itération
for (var i = 0; i < 5; i++){
// sera exécutée 5 fois
}
// && est le "et" logique, || est le "ou" logique
if (house.size === 'big' && house.colour === 'blue'){
house.contains = 'bear';
}
if (colour === 'red' || colour === 'blue'){
// colour est soit 'red' soit 'blue'
}
// Les raccourcis && et || sont pratiques pour instancier des valeurs par defaut.
var name = otherName || 'default';
// Ceci est l'équivalent de
var name = otherName;
if (!name){
name = 'default';
}
// Le switch vérifie les égalités avec ===
// utilisez un "break" à la fin de chaque cas
// ou les cas suivants seront eux aussi exécutés
grade = 'B';
switch (grade) {
case 'A':
console.log('Great job');
break;
case 'B':
console.log('OK job');
break;
case 'C':
console.log('You can do better');
break;
default:
console.log('Oy vey');
break;
}
///////////////////////////////////
// 4. Fonctions, Scope (Environnement) et Closures
// Les fonctions sont déclarées avec le mot clé function
function myFunction(thing){
return thing.toUpperCase();
}
myFunction('foo'); // = 'FOO'
// Les fonctions JavaScript sont des objets de première classe, donc peuvent
// être réassignées à d'autres variables et passées en tant que paramètres pour
// d'autres fonctions
function myFunction(){
// ce code s'exécutera dans 5 secondes
}
setTimeout(myFunction, 5000);
// Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi
// que Node.js le rendent disponible
// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être
// anonymes
setTimeout(function(){
// ce code s'exécutera dans 5 secondes
}, 5000);
// Le Javascript crée uniquement un scope, une portée d'action limitée, pour
// les fonctions, et pas dans les autres blocs.
if (true){
var i = 5;
}
i; // = 5 - et non undefined comme vous pourriez vous y attendre
// Cela a mené à un style commun de fonctions anonymes immédiatement exécutée;
// ou "immediately-executing anonymous functions"
(function(){
var temporary = 5;
// Nous pouvons accéder au scope global en assignant à l'objet global,
// qui dans les navigateurs est "window". Il est différent dans Node.js,
// le scope global sera en fait local au module dans lequel vous
// vous trouvez. http://nodejs.org/api/globals.html
window.permanent = 10;
})();
// Cela permet de ne pas avoir de fuites de variables qui polluent
// lenvironnement global.
temporary; // raises ReferenceError
permanent; // = 10
// Une des fonctionnalités les plus puissantes de Javascript est le système de
// closures. Si une fonction est définie dans une autre fonction, alors la
// fonction interne aura accès aux variables de la fonction parente, même si
// celle-ci a déjà finie son exécution.
function sayHelloInFiveSeconds(name){
var prompt = 'Hello, ' + name + '!';
// Fonction interne
function inner(){
alert(prompt);
}
setTimeout(inner, 5000);
// setTimeout is asynchrone, donc la fonction sayHelloInFiveSeconds quittera
// immédiatement, et setTimeout appelera inner après.
}
sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec
///////////////////////////////////
// 5. Encore plus à propos des Objets; Constructeurs and Prototypes
// Les objets peuvent contenir des fonctions.
var myObj = {
myFunc: function(){
return 'Hello world!';
}
};
myObj.myFunc(); // = 'Hello world!'
// Lorsqu'une fonction attachée à un objet est appelée, elle peut accéder à
// l'objet avec le mot clé this.
myObj = {
myString: 'Hello world!',
myFunc: function(){
return this.myString;
}
};
myObj.myFunc(); // = 'Hello world!'
// La valeur de "this" change de par l'endroit où la fonction est appelée, et
// non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle
// est appelée hors du contexte l'objet.
var myFunc = myObj.myFunc;
myFunc(); // = undefined
// A l'inverse, une fonction peut être attachée à un objet et y gagner l'accès
// au travers de "this"
var myOtherFunc = function(){
return this.myString.toUpperCase();
}
myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = 'HELLO WORLD!'
// Le contexte correspond à la valeur de "this".
// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this,
// pour une fonction quand elle est appelée grâce à "call" ou "apply".
var anotherFunc = function(s){
return this.myString + s;
}
anotherFunc.call(myObj, ' And Hello Moon!'); // = 'Hello World! And Hello Moon!'
// 'apply' est presque identique, mais prend un tableau comme liste darguments.
anotherFunc.apply(myObj, [' And Hello Sun!']); // = 'Hello World! And Hello Sun!'
Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN (uh-oh!)
Math.min.apply(Math, [42, 6, 27]); // = 6
// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la
// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser
// "bind" pour garder une référence à la fonction avec ce "this".
var boundFunc = anotherFunc.bind(myObj);
boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!'
// "bind" peut aussi être utilisé pour créer une application partielle de la
// fonction (curry)
var product = function(a, b){ return a * b; }
var doubler = product.bind(this, 2);
doubler(8); // = 16
// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est
// crée et mis à disposition de la fonction via "this". Ces fonctions sont
// communément appelées constructeurs.
var MyConstructor = function(){
this.myNumber = 5;
}
myNewObj = new MyConstructor(); // = {myNumber: 5}
myNewObj.myNumber; // = 5
// Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à
// une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype.
// Quelques implémentations de JS vous laissent accéder au prototype avec la
// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard
// et ne fonctionne pas dans certains des navigateurs actuels.
var myObj = {
myString: 'Hello world!'
};
var myPrototype = {
meaningOfLife: 42,
myFunc: function(){
return this.myString.toLowerCase()
}
};
myObj.__proto__ = myPrototype;
myObj.meaningOfLife; // = 42
myObj.myFunc(); // = 'hello world!'
myPrototype.__proto__ = {
myBoolean: true
};
myObj.myBoolean; // = true
// Pour obtenir le prototype il existe également Object.getPrototypeOf
Object.getPrototypeOf( myObj ) // = {meaningOfLife: 42, myFunc: function}
// Il n'y a pas de copie ici. Chacun des objets stocke une référence à son
// prototype. Cela veut dire que l'on peut le modifier et cela se répercutera
// partout.
myPrototype.meaningOfLife = 43;
myObj.meaningOfLife; // = 43
// L'inverse n'est cependant pas vrai. Changer la propriété d'un objet ne change
// pas la chaine prototypale.
myObj.meaningOfLife = 42;
myPrototype.meaningOfLife; // = 43
// Comme précédemment dit, __proto__ n'est pas standard et ne devrait pas être
// utilisé. Il y a deux autres moyen de créer un nouvel objet avec un prototype
// donné.
// Le premier est Object.create, mais c'est assez récent et risque de ne pas
// fonctionner dans tous les navigateurs.
var myObj = Object.create(myPrototype);
myObj.meaningOfLife; // = 43
// Le deuxième moyen, qui marche partout, fonctionne avec les constructeurs.
// Les constructeurs ont un propriété appelée prototype. Ce n'est *pas* le
// prototype du constructeur de la fonction elle-même, c'est le prototype que
// les nouveaux objets crées grâce à ce constructeur avec "new" auront.
MyConstructor.prototype = {
myNumber: 5,
getMyNumber: function(){
return this.myNumber;
}
};
var myNewObj2 = new MyConstructor();
myNewObj2.getMyNumber(); // = 5
myNewObj2.myNumber = 6
myNewObj2.getMyNumber(); // = 6
// Les types pré-définis tels que les strings ou nombres ont aussi des
// constructeurs
var myNumber = 12;
var myNumberObj = new Number(12);
myNumber == myNumberObj; // = true
// ... mais ils ne sont pas exactement équivalent.
typeof myNumber; // = 'number'
typeof myNumberObj; // = 'object'
myNumber === myNumberObj; // = false
if (0){
// 0 est falsy, le code ne fonctionnera pas.
}
if (Number(0)){
// Parce que Number(0) est truthy, le code fonctionnera
}
// Cependant, vous pouvez ajouter des fonctionnalités aux types de bases grâce à
// cette particularité.
String.prototype.firstCharacter = function(){
return this.charAt(0);
}
'abc'.firstCharacter(); // = 'a'
// C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles
// fonctionnalités de JavaScript dans de plus anciens environnements, tels que
// les vieux navigateurs.
//Par exemple, Object.create est assez récent, mais peut être implémenté grâce à
// ce polyfill
if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe déjà
Object.create = function(proto){
// on crée un constructeur temporaire avec le bon prototype
var Constructor = function(){};
Constructor.prototype = proto;
// puis on utilise "new" pour créer un object avec ce même prototype
return new Constructor();
}
}
```
## Pour aller plus loin (en anglais)
The [Mozilla Developer
Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une
excellente documentation pour le Javascript dans les navigateurs. Et contient
également un wiki pour s'entraider.
MDN's [A re-introduction to
JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
recouvre les principaux sujets vus ici. Le guide est délibérément uniquement
à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous
plutôt ici :
[Document Object
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges.
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
un guide pour vous éviter les faux-amis dans le JavaScript.
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire.
En addition aux contributeurs de cet article, du contenu provient du
"Python tutorial" de Louie Dinh, et de [JS
Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
sur le réseau Mozilla.

View File

@ -14,7 +14,7 @@ lang: fr-fr
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
```cpp ```objective_c
// Les commentaires sur une seule ligne commencent par // // Les commentaires sur une seule ligne commencent par //
/* /*

View File

@ -14,7 +14,7 @@ R は統計計算用の言語です。
データの取得やクリーニング、統計処理やグラフ作成をするために便利な、たくさんのライブラリがあります。また、LaTeX文書からRコマンドを呼び出すこともできます データの取得やクリーニング、統計処理やグラフ作成をするために便利な、たくさんのライブラリがあります。また、LaTeX文書からRコマンドを呼び出すこともできます
```python ```r
# コメント行は、#で開始します # コメント行は、#で開始します
@ -772,4 +772,4 @@ pp + geom_point()
* RとR GUIはこちら [http://www.r-project.org/](http://www.r-project.org/) * RとR GUIはこちら [http://www.r-project.org/](http://www.r-project.org/)
* [RStudio](http://www.rstudio.com/ide/) 別のGUI * [RStudio](http://www.rstudio.com/ide/) 別のGUI

View File

@ -10,7 +10,7 @@ Markdown was created by John Gruber in 2004. It's meant to be an easy to read an
Give me as much feedback as you want! / Feel free to fork and pull request! Give me as much feedback as you want! / Feel free to fork and pull request!
``` ```markdown
<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that <!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that
means we can use HTML elements in Markdown, such as the comment element, and means we can use HTML elements in Markdown, such as the comment element, and
they won't be affected by a markdown parser. However, if you create an HTML they won't be affected by a markdown parser. However, if you create an HTML

View File

@ -12,7 +12,7 @@ filename: LearnObjectiveC.m
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
```cpp ```objective_c
// Single-line comments start with // // Single-line comments start with //
/* /*

View File

@ -14,7 +14,7 @@ escrever sintaxe que converte facilmente em HTML (hoje, suporta outros formatos
Dê-me feedback tanto quanto você quiser! / Sinta-se livre para a garfar (fork) e Dê-me feedback tanto quanto você quiser! / Sinta-se livre para a garfar (fork) e
puxar o projeto (pull request) puxar o projeto (pull request)
``` ```markdown
<!-- Markdown é um superconjunto do HTML, de modo que qualquer arvquivo HTML é <!-- Markdown é um superconjunto do HTML, de modo que qualquer arvquivo HTML é
um arquivo Markdown válido, isso significa que nós podemos usar elementos HTML um arquivo Markdown válido, isso significa que nós podemos usar elementos HTML
em Markdown, como o elemento de comentário, e eles não serão afetados pelo analisador em Markdown, como o elemento de comentário, e eles não serão afetados pelo analisador

View File

@ -8,7 +8,7 @@ filename: learnr.r
R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R` commands within a LaTeX document. R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R` commands within a LaTeX document.
```python ```r
# Comments start with number symbols. # Comments start with number symbols.

View File

@ -13,7 +13,7 @@ Objective-C — компилируемый объектно-ориентиров
построенный на основе языка Си и парадигм Smalltalk. построенный на основе языка Си и парадигм Smalltalk.
В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения. В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения.
```cpp ```objective_c
// Однострочный комментарий // Однострочный комментарий
/* /*

View File

@ -5,25 +5,29 @@ contributors:
- ["Louie Dinh", "http://ldinh.ca"] - ["Louie Dinh", "http://ldinh.ca"]
translators: translators:
- ["Yury Timofeev", "http://twitter.com/gagar1n"] - ["Yury Timofeev", "http://twitter.com/gagar1n"]
- ["Andre Polykanine", "https://github.com/Oire"]
filename: learnpython-ru.py filename: learnpython-ru.py
--- ---
Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из самых популярных Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из
языков. Я люблю его за его понятный и доходчивый синтаксис - это почти что исполняемый псевдокод. самых популярных языков. Я люблю его за понятный и доходчивый синтаксис — это
почти что исполняемый псевдокод.
С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) или louiedinh [at] [google's email service] С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh)
или louiedinh [at] [почтовый сервис Google]
Замечание: Эта статья относится к Python 2.7, но должно работать и в Python 2.x. Скоро будет версия и для Python 3! Замечание: Эта статья относится к Python 2.7, но должно работать и в Python 2.x.
Скоро будет версия и для Python 3!
```python ```python
# Однострочные комментарии начинаются с hash-символа. # Однострочные комментарии начинаются с символа решётки.
""" Многострочный текст может быть """ Многострочный текст может быть
записан, используя 3 знака " и обычно используется записан, используя 3 знака " и обычно используется
в качестве комментария в качестве комментария
""" """
#################################################### ####################################################
## 1. Примитивные типы данных и операторов ## 1. Примитивные типы данных и операторы
#################################################### ####################################################
# У вас есть числа # У вас есть числа
@ -36,17 +40,31 @@ filename: learnpython-ru.py
35 / 5 #=> 7 35 / 5 #=> 7
# А вот деление немного сложнее. В этом случае происходит деление # А вот деление немного сложнее. В этом случае происходит деление
# целых чисел и результат автоматически округляется в меньшую сторону. # целых чисел, и результат автоматически округляется в меньшую сторону.
5 / 2 #=> 2 5 / 2 #=> 2
# Чтобы научиться делить, сначала нужно немного узнать о дробных числах. # Чтобы научиться делить, сначала нужно немного узнать о числах
2.0 # Это дробное число # с плавающей запятой.
2.0 # Это число с плавающей запятой
11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше 11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше
# Результат целочисленного деления округляется в меньшую сторону
# как для положительных, так и для отрицательных чисел.
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# Остаток от деления
7 % 3 # => 1
# Возведение в степень
2 ** 4 # => 16
# Приоритет операций указывается скобками # Приоритет операций указывается скобками
(1 + 3) * 2 #=> 8 (1 + 3) * 2 #=> 8
# Логические значения являются примитивами # Логические (булевы) значения являются примитивами
True True
False False
@ -54,15 +72,15 @@ False
not True #=> False not True #=> False
not False #=> True not False #=> True
# Равенство это == # Равенство это ==
1 == 1 #=> True 1 == 1 #=> True
2 == 1 #=> False 2 == 1 #=> False
# Неравенство это != # Неравенство это !=
1 != 1 #=> False 1 != 1 #=> False
2 != 1 #=> True 2 != 1 #=> True
# Еще немного сравнений # Ещё немного сравнений
1 < 10 #=> True 1 < 10 #=> True
1 > 10 #=> False 1 > 10 #=> False
2 <= 2 #=> True 2 <= 2 #=> True
@ -85,9 +103,10 @@ not False #=> True
# Символ % используется для форматирования строк, например: # Символ % используется для форматирования строк, например:
"%s могут быть %s" % ("строки", "интерполированы") "%s могут быть %s" % ("строки", "интерполированы")
# Новый метод форматирования строк - использование метода format. # Новый способ форматирования строк — использование метода format.
# Это предпочитаемый способ. # Это предпочитаемый способ.
"{0} могут быть {1}".format("строки", "форматированы") "{0} могут быть {1}".format("строки", "форматированы")
# Если вы не хотите считать, можете использовать ключевые слова. # Если вы не хотите считать, можете использовать ключевые слова.
"{name} хочет есть {food}".format(name="Боб", food="лазанью") "{name} хочет есть {food}".format(name="Боб", food="лазанью")
@ -95,7 +114,7 @@ not False #=> True
None #=> None None #=> None
# Не используйте оператор равенства '=='' для сравнения # Не используйте оператор равенства '=='' для сравнения
# объектов с None. Используйте для этого 'is' # объектов с None. Используйте для этого «is»
"etc" is None #=> False "etc" is None #=> False
None is None #=> True None is None #=> True
@ -113,17 +132,18 @@ None is None #=> True
## 2. Переменные и коллекции ## 2. Переменные и коллекции
#################################################### ####################################################
# Печатать довольно просто # У Python есть функция Print, доступная в версиях 2.7 и 3,
print "Я Python. Приятно познакомиться!" print("Я Python. Приятно познакомиться!")
# ...и старый оператор print, доступный в версиях 2.x, но удалённый в версии 3.
print "И я тоже Python!"
# Необязательно объявлять переменные перед их инициализацией. # Необязательно объявлять переменные перед их инициализацией.
some_var = 5 # По соглашению используется нижний_регистр_с_подчеркиваниями some_var = 5 # По соглашению используется нижний_регистр_с_подчёркиваниями
some_var #=> 5 some_var #=> 5
# При попытке доступа к неинициализированной переменной, # При попытке доступа к неинициализированной переменной
# выбрасывается исключение. # выбрасывается исключение.
# См. раздел "Поток управления" для информации об исключениях. # См. раздел «Поток управления» для информации об исключениях.
some_other_var # Выбрасывает ошибку именования some_other_var # Выбрасывает ошибку именования
# if может быть использован как выражение # if может быть использован как выражение
@ -149,24 +169,30 @@ li[0] #=> 1
# Обратимся к последнему элементу # Обратимся к последнему элементу
li[-1] #=> 3 li[-1] #=> 3
# Попытка выйти за границы массива приведет к IndexError # Попытка выйти за границы массива приведёт к ошибке индекса
li[4] # Выдает IndexError li[4] # Выдаёт IndexError
# Можно обращаться к диапазону, используя "кусочный синтаксис" (slice syntax) # Можно обращаться к диапазону, используя "кусочный синтаксис" (slice syntax)
# (Для тех, кто любит математику, это называется замкнуто/открытый интервал.) # (Для тех, кто любит математику, это называется замкнуто-открытый интервал).
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]
# Выбираем каждый второй элемент
li[::2] # =>[1, 4]
# Переворачиваем список
li[::-1] # => [3, 4, 2, 1]
# Используйте сочетания всего вышеназванного для выделения более сложных кусков
# li[начало:конец:шаг]
# Удаляем произвольные элементы из списка оператором del # Удаляем произвольные элементы из списка оператором del
del li[2] # [1, 2, 3] del li[2] # [1, 2, 3]
# Вы можете складывать списки # Вы можете складывать списки
li + other_li #=> [1, 2, 3, 4, 5, 6] - Замечание: li и other_li остаются нетронутыми li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются
# Конкатенировать списки можно методом extend # Объединять списки можно методом extend
li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
# Проверить элемент на вхождение в список можно оператором in # Проверить элемент на вхождение в список можно оператором in
@ -176,12 +202,12 @@ li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
len(li) #=> 6 len(li) #=> 6
# Кортежи - это такие списки, только неизменяемые # Кортежи это такие списки, только неизменяемые
tup = (1, 2, 3) tup = (1, 2, 3)
tup[0] #=> 1 tup[0] #=> 1
tup[0] = 3 # Выдает TypeError tup[0] = 3 # Выдаёт TypeError
# Все то же самое можно делать и с кортежами # Всё то же самое можно делать и с кортежами
len(tup) #=> 3 len(tup) #=> 3
tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
tup[:2] #=> (1, 2) tup[:2] #=> (1, 2)
@ -203,33 +229,33 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# Значения ищутся по ключу с помощью оператора [] # Значения ищутся по ключу с помощью оператора []
filled_dict["one"] #=> 1 filled_dict["one"] #=> 1
# Можно получить все ключи в виде списка # Можно получить все ключи в виде списка с помощью метода keys
filled_dict.keys() #=> ["three", "two", "one"] filled_dict.keys() #=> ["three", "two", "one"]
# Замечание - сохранение порядка ключей в словаре не гарантируется # Замечание: сохранение порядка ключей в словаре не гарантируется
# Ваши результаты могут не совпадать с этими. # Ваши результаты могут не совпадать с этими.
# Можно получить и все значения в виде списка # Можно получить и все значения в виде списка, используйте метод values
filled_dict.values() #=> [3, 2, 1] filled_dict.values() #=> [3, 2, 1]
# То же самое замечание насчет порядка ключей справедливо и здесь # То же самое замечание насчёт порядка ключей справедливо и здесь
# При помощи оператора in можно проверять ключи на вхождение в словарь # При помощи оператора in можно проверять ключи на вхождение в словарь
"one" in filled_dict #=> True "one" in filled_dict #=> True
1 in filled_dict #=> False 1 in filled_dict #=> False
# Попытка получить значение по несуществующему ключу выбросит KeyError # Попытка получить значение по несуществующему ключу выбросит ошибку ключа
filled_dict["four"] # KeyError filled_dict["four"] # KeyError
# Чтобы избежать этого, используйте метод get # Чтобы избежать этого, используйте метод get
filled_dict.get("one") #=> 1 filled_dict.get("one") #=> 1
filled_dict.get("four") #=> None filled_dict.get("four") #=> None
# Метод get также принимает аргумент default, значение которого будет # Метод get также принимает аргумент по умолчанию, значение которого будет
# возвращено при отсутствии указанного ключа # возвращено при отсутствии указанного ключа
filled_dict.get("one", 4) #=> 1 filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4 filled_dict.get("four", 4) #=> 4
# Метод setdefault - это безопасный способ добавить новую пару ключ-значение в словарь # Метод setdefault вставляет пару ключ-значение, только если такого ключа нет
filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
filled_dict.setdefault("five", 6) #filled_dict["five"] по прежнему возвращает 5 filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
# Множества содержат... ну, в общем, множества # Множества содержат... ну, в общем, множества
@ -237,8 +263,8 @@ empty_set = set()
# Инициализация множества набором значений # Инициализация множества набором значений
some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4]) some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4])
# Начиная с Python 2.7, вы можете использовать {} чтобы обьявить множество # Начиная с 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}
@ -262,33 +288,33 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
## 3. Поток управления ## 3. Поток управления
#################################################### ####################################################
# Для начала заведем переменную # Для начала заведём переменную
some_var = 5 some_var = 5
# Так выглядит выражение if. Отступы в python очень важны! # Так выглядит выражение if. Отступы в python очень важны!
# результат: "some_var меньше, чем 10" # результат: «some_var меньше, чем 10»
if some_var > 10: if some_var > 10:
print "some_var намного больше, чем 10." print("some_var намного больше, чем 10.")
elif some_var < 10: # Выражение elif необязательно. elif some_var < 10: # Выражение elif необязательно.
print "some_var меньше, чем 10." print("some_var меньше, чем 10.")
else: # Это тоже необязательно. else: # Это тоже необязательно.
print "some_var равно 10." print("some_var равно 10.")
""" """
Циклы For проходят по спискам Циклы For проходят по спискам
Результат: Результат:
собака это млекопитающее собака это млекопитающее
кошка это млекопитающее кошка это млекопитающее
мышь это млекопитающее мышь это млекопитающее
""" """
for animal in ["собака", "кошка", "мышь"]: for animal in ["собака", "кошка", "мышь"]:
# Можете использовать оператор % для интерполяции форматированных строк # Можете использовать оператор % для интерполяции форматированных строк
print "%s это млекопитающее" % animal print("%s — это млекопитающее" % animal)
""" """
`range(number)` возвращает список чисел «range(число)» возвращает список чисел
от нуля до заданного числа от нуля до заданного числа
Результат: Результат:
0 0
@ -297,7 +323,7 @@ for animal in ["собака", "кошка", "мышь"]:
3 3
""" """
for i in range(4): for i in range(4):
print i print(i)
""" """
Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. Циклы while продолжаются до тех пор, пока указанное условие не станет ложным.
@ -309,19 +335,24 @@ for i in range(4):
""" """
x = 0 x = 0
while x < 4: while x < 4:
print x print(x)
x += 1 # То же самое, что x = x + 1 x += 1 # Краткая запись для x = x + 1
# Обрабывайте исключения блоками try/except # Обрабатывайте исключения блоками try/except
# Работает в Python 2.6 и выше: # Работает в Python 2.6 и выше:
try: try:
# Для выбора ошибки используется raise # Чтобы выбросить ошибку, используется raise
raise IndexError("Это IndexError") raise IndexError("Это ошибка индекса")
except IndexError as e: except IndexError as e:
# pass это просто отсутствие оператора. Обычно здесь происходит # pass это просто отсутствие оператора. Обычно здесь происходит
# восстановление от ошибки. # восстановление после ошибки.
pass pass
except (TypeError, NameError):
pass # Несколько исключений можно обработать вместе, если нужно.
else: # Необязательное выражение. Должно следовать за последним блоком except
print("Всё хорошо!") # Выполнится, только если не было никаких исключений
#################################################### ####################################################
@ -330,23 +361,23 @@ except IndexError as e:
# Используйте def для создания новых функций # Используйте def для создания новых функций
def add(x, y): def add(x, y):
print "x равен %s, а y равен %s" % (x, y) print("x равен %s, а y равен %s" % (x, y))
return x + y # Возвращайте результат выражением return return x + y # Возвращайте результат выражением return
# Вызов функции с аргументами # Вызов функции с аргументами
add(5, 6) #=> prints out "x равен 5, а y равен 6" и возвращает 11 add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11
# Другой способ вызова функции с аргументами # Другой способ вызова функции — вызов с именованными аргументами
add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке.
# Вы можете определить функцию, принимающую неизвестное количество аргументов # Вы можете определить функцию, принимающую изменяемое число аргументов
def varargs(*args): def varargs(*args):
return args return args
varargs(1, 2, 3) #=> (1,2,3) varargs(1, 2, 3) #=> (1,2,3)
# А также можете определить функцию, принимающую изменяющееся количество # А также можете определить функцию, принимающую изменяемое число
# именованных аргументов # именованных аргументов
def keyword_args(**kwargs): def keyword_args(**kwargs):
return kwargs return kwargs
@ -356,8 +387,8 @@ keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
# Если хотите, можете использовать оба способа одновременно # Если хотите, можете использовать оба способа одновременно
def all_the_args(*args, **kwargs): def all_the_args(*args, **kwargs):
print args print(args)
print kwargs print(kwargs)
""" """
all_the_args(1, 2, a=3, b=4) выводит: all_the_args(1, 2, a=3, b=4) выводит:
(1, 2) (1, 2)
@ -368,11 +399,28 @@ all_the_args(1, 2, a=3, b=4) выводит:
# Используйте символ * для передачи кортежей и ** для передачи словарей # Используйте символ * для передачи кортежей и ** для передачи словарей
args = (1, 2, 3, 4) args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4} kwargs = {"a": 3, "b": 4}
all_the_args(*args) # эквивалент foo(1, 2, 3, 4) all_the_args(*args) # эквивалентно foo(1, 2, 3, 4)
all_the_args(**kwargs) # эквивалент foo(a=3, b=4) all_the_args(**kwargs) # эквивалентно foo(a=3, b=4)
all_the_args(*args, **kwargs) # эквивалент foo(1, 2, 3, 4, a=3, b=4) all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4)
# Python имеет функции первого класса # Область определения функций
x = 5
def setX(num):
# Локальная переменная x — это не то же самое, что глобальная переменная x
x = num # => 43
print (x) # => 43
def setGlobalX(num):
global x
print (x) # => 5
x = num # Глобальная переменная x теперь равна 6
print (x) # => 6
setX(43)
setGlobalX(6)
# В Python есть функции первого класса
def create_adder(x): def create_adder(x):
def adder(y): def adder(y):
return x + y return x + y
@ -388,7 +436,7 @@ add_10(3) #=> 13
map(add_10, [1,2,3]) #=> [11, 12, 13] map(add_10, [1,2,3]) #=> [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
# Мы можем использовать списки для удобного отображения и фильтрации # Для удобного отображения и фильтрации можно использовать списочные включения
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
@ -402,7 +450,11 @@ class Human(object):
# Атрибут класса. Он разделяется всеми экземплярами этого класса # Атрибут класса. Он разделяется всеми экземплярами этого класса
species = "H. sapiens" species = "H. sapiens"
# Обычный конструктор # Обычный конструктор, вызывается при инициализации экземпляра класса
# Обратите внимание, что двойное подчёркивание в начале и в конце имени
# означает объекты и атрибуты, которые используются Python, но находятся
# в пространствах имён, управляемых пользователем.
# Не придумывайте им имена самостоятельно.
def __init__(self, name): def __init__(self, name):
# Присваивание значения аргумента атрибуту класса name # Присваивание значения аргумента атрибуту класса name
self.name = name self.name = name
@ -423,17 +475,17 @@ class Human(object):
return "*grunt*" return "*grunt*"
# Инстанцирование класса # Инициализация экземпляра класса
i = Human(name="Иван") i = Human(name="Иван")
print i.say("привет") # "Иван: привет" print(i.say("привет")) # Выводит: «Иван: привет»
j = Human("Петр") j = Human("Пётр")
print j.say("Привет") # "Петр: привет" print(j.say("Привет")) # Выводит: «Пётр: привет»
# Вызов метода класса # Вызов метода класса
i.get_species() #=> "H. sapiens" i.get_species() #=> "H. sapiens"
# Присвоение разделяемому атрибуту # Изменение разделяемого атрибута
Human.species = "H. neanderthalensis" Human.species = "H. neanderthalensis"
i.get_species() #=> "H. neanderthalensis" i.get_species() #=> "H. neanderthalensis"
j.get_species() #=> "H. neanderthalensis" j.get_species() #=> "H. neanderthalensis"
@ -448,12 +500,12 @@ Human.grunt() #=> "*grunt*"
# Вы можете импортировать модули # Вы можете импортировать модули
import math import math
print math.sqrt(16) #=> 4 print(math.sqrt(16)) #=> 4
# Вы можете импортировать отдельные функции модуля # Вы можете импортировать отдельные функции модуля
from math import ceil, floor from math import ceil, floor
print ceil(3.7) #=> 4.0 print(ceil(3.7)) #=> 4.0
print floor(3.7) #=> 3.0 print(floor(3.7)) #=> 3.0
# Можете импортировать все функции модуля. # Можете импортировать все функции модуля.
# (Хотя это и не рекомендуется) # (Хотя это и не рекомендуется)
@ -463,7 +515,7 @@ from math import *
import math as m import math as m
math.sqrt(16) == m.sqrt(16) #=> True math.sqrt(16) == m.sqrt(16) #=> True
# Модули в Python это обычные файлы с кодом python. Вы # Модули в Python — это обычные Python-файлы. Вы
# можете писать свои модули и импортировать их. Название # можете писать свои модули и импортировать их. Название
# модуля совпадает с названием файла. # модуля совпадает с названием файла.
@ -472,18 +524,72 @@ math.sqrt(16) == m.sqrt(16) #=> True
import math import math
dir(math) dir(math)
####################################################
## 7. Дополнительно
####################################################
# Генераторы помогут выполнить ленивые вычисления
def double_numbers(iterable):
for i in iterable:
yield i + i
# Генератор создаёт значения на лету.
# Он не возвращает все значения разом, а создаёт каждое из них при каждой
# итерации. Это значит, что значения больше 15 в double_numbers
# обработаны не будут.
# Обратите внимание: xrange — это генератор, который делает то же, что и range.
# Создание списка чисел от 1 до 900000000 требует много места и времени.
# xrange создаёт объект генератора, а не список сразу, как это делает range.
# Если нам нужно имя переменной, совпадающее с ключевым словом Python,
# мы используем подчёркивание в конце
xrange_ = xrange(1, 900000000)
# Будет удваивать все числа, пока результат не будет >= 30
for i in double_numbers(xrange_):
print(i)
if i >= 30:
break
# Декораторы
# В этом примере beg оборачивает say
# Метод beg вызовет say. Если say_please равно True,
# он изменит возвращаемое сообщение
from functools import wraps
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(")
return msg
return wrapper
@beg
def say(say_please=False):
msg = "Вы не купите мне пива?"
return msg, say_please
print(say()) # Вы не купите мне пива?
print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :(
``` ```
## Хотите еще? ## Хотите ещё?
### Бесплатные онлайн-материалы ### Бесплатные онлайн-материалы
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/) * [Dive Into Python](http://www.diveintopython.net/)
* [The Official Docs](http://docs.python.org/2.6/) * [Официальная документация](http://docs.python.org/2.6/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/) * [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
### Платные ### Платные

View File

@ -9,7 +9,7 @@ filename: learn.scala
Scala - the scalable language Scala - the scalable language
```cpp ```scala
/* /*
Set yourself up: Set yourself up:

View File

@ -12,7 +12,7 @@ The official [Swift Programming Language](https://itunes.apple.com/us/book/swift
See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift.
```js ```swift
// //
// MARK: Basics // MARK: Basics
// //

View File

@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di
Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C
programlama diline Smalltalk stilinde mesajlaşma ekler. programlama diline Smalltalk stilinde mesajlaşma ekler.
```cpp ```objective_c
// Tek satır yorum // işaretleri ile başlar // Tek satır yorum // işaretleri ile başlar
/* /*

View File

@ -13,7 +13,7 @@ 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.
```ts ```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;

View File

@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m
Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch. Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C. Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
```cpp ```objective_c
// Chú thích dòng đơn bắt đầu với // // Chú thích dòng đơn bắt đầu với //
/* /*

View File

@ -17,7 +17,7 @@ ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范
另外还有一本热门的近期出版的 另外还有一本热门的近期出版的
[Land of Lisp](http://landoflisp.com/). [Land of Lisp](http://landoflisp.com/).
```scheme ```common-lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 0. 语法 ;;; 0. 语法
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

View File

@ -9,6 +9,7 @@ contributors:
- ["Amr Tamimi", "https://amrtamimi.com"] - ["Amr Tamimi", "https://amrtamimi.com"]
translators: translators:
- ["Jakukyo Friel", "http://weakish.github.io"] - ["Jakukyo Friel", "http://weakish.github.io"]
filename: lua-cn.lua
--- ---
```lua ```lua

View File

@ -3,7 +3,7 @@ language: Markdown
contributors: contributors:
- ["Dan Turkel", "http://danturkel.com/"] - ["Dan Turkel", "http://danturkel.com/"]
translators: translators:
- ["Fangzhou Chen"] - ["Fangzhou Chen","https://github.com/FZSS"]
filename: learnmarkdown-cn.md filename: learnmarkdown-cn.md
lang: zh-cn lang: zh-cn
--- ---
@ -13,7 +13,7 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的
欢迎您多多反馈以及分支和请求合并。 欢迎您多多反馈以及分支和请求合并。
``` ```markdown
<!-- Markdown 是 HTML 的父集,所以任何 HTML 文件都是有效的 Markdown。 <!-- Markdown 是 HTML 的父集,所以任何 HTML 文件都是有效的 Markdown。
这意味着我们可以在 Markdown 里使用任何 HTML 元素,比如注释元素, 这意味着我们可以在 Markdown 里使用任何 HTML 元素,比如注释元素,
且不会被 Markdown 解析器所影响。不过如果你在 Markdown 文件内创建了 HTML 元素, 且不会被 Markdown 解析器所影响。不过如果你在 Markdown 文件内创建了 HTML 元素,

View File

@ -13,7 +13,7 @@ lang: zh-cn
R 是一门统计语言。它有很多数据分析和挖掘程序包。可以用来统计、分析和制图。 R 是一门统计语言。它有很多数据分析和挖掘程序包。可以用来统计、分析和制图。
你也可以在 LaTeX 文档中运行 `R` 命令。 你也可以在 LaTeX 文档中运行 `R` 命令。
```python ```r
# 评论以 # 开始 # 评论以 # 开始
# R 语言原生不支持 多行注释 # R 语言原生不支持 多行注释

View File

@ -11,7 +11,7 @@ lang: zh-cn
Scala - 一门可拓展性的语言 Scala - 一门可拓展性的语言
```cpp ```scala
/* /*
自行设置: 自行设置:

View File

@ -12,7 +12,7 @@ Swift 是Apple 开发的用于iOS 和OS X 开发的编程语言。Swift 于2014
参阅Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) ——一个完整的Swift 教程 参阅Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) ——一个完整的Swift 教程
```js ```swift
// //
// 基础 // 基础
// //