summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--README.markdown22
-rw-r--r--bash.html.markdown45
-rw-r--r--c.html.markdown2
-rw-r--r--java.html.markdown12
-rw-r--r--perl6.html.markdown2
-rw-r--r--python.html.markdown8
-rw-r--r--python3.html.markdown6
-rw-r--r--r.html.markdown11
-rw-r--r--ru-ru/java-ru.html.markdown506
-rw-r--r--ruby.html.markdown14
-rw-r--r--scala.html.markdown390
-rw-r--r--tmux.html.markdown3
-rw-r--r--zh-cn/python3-cn.html.markdown629
13 files changed, 1443 insertions, 207 deletions
diff --git a/README.markdown b/README.markdown
index dc379a9b..4e24bbe6 100644
--- a/README.markdown
+++ b/README.markdown
@@ -14,12 +14,12 @@ properly!
## Contributing
-All contributions welcome, from the tiniest typo to a brand new article. Translations
+All contributions are welcome, from the tiniest typo to a brand new article. Translations
in all languages are welcome (or, for that matter, original articles in any language).
Send a pull request or open an issue any time of day or night.
**Please tag your issues pull requests with [language/lang-code] at the beginning**
-**(e.g. [python/en] for english python).** This will help everyone pick out things they
+**(e.g. [python/en] for English Python).** This will help everyone pick out things they
care about.
### Style Guidelines
@@ -27,7 +27,7 @@ care about.
* **Keep lines under 80 chars**
* **Prefer example to exposition**
* **Eschew surplusage**
-* **Use utf-8**
+* **Use UTF-8**
Long version:
@@ -38,28 +38,28 @@ Long version:
* We welcome newcomers, but the target audience for this site is programmers with some experience.
So, try to avoid explaining basic concepts except for those specific to the language in question,
- to keep articles succinct and scannable. We all know how to use google here.
+ to keep articles succinct and scannable. We all know how to use Google here.
-* For translations (or english articles with non-ASCII characters), please make sure your file is
- utf-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in vim)
+* For translations (or English articles with non-ASCII characters), please make sure your file is
+ UTF-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in Vim)
### Header configuration
-The actual site uses Middleman to generate HTML files from these markdown ones. Middleman, or at least
+The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least
the custom scripts underpinning the site, required that some key information be defined in the header.
-The following fields are necessary for english articles about programming languages:
+The following fields are necessary for English articles about programming languages:
* **language** The *programming language* in question
-* **contributors** A list of [author, url] lists to credit
+* **contributors** A list of [author, URL] lists to credit
Other fields:
* **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable.
- For non-english articles, *filename* should have a language-specific suffix.
+ For non-English articles, *filename* should have a language-specific suffix.
* **lang**: For translations, the human language this article is in. For categorization, mostly.
-Here's an example header for an esperanto translation of Ruby:
+Here's an example header for an Esperanto translation of Ruby:
```yaml
---
diff --git a/bash.html.markdown b/bash.html.markdown
index 81d586c4..3b163638 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -111,12 +111,45 @@ ls -l # Lists every file and directory on a separate line
# .txt files in the current directory:
ls -l | grep "\.txt"
-# You can also redirect a command, input and error output.
-python2 hello.py < "input.in"
-python2 hello.py > "output.out"
-python2 hello.py 2> "error.err"
-# The output error will overwrite the file if it exists, if you want to
-# concatenate them, use ">>" instead.
+# You can redirect command input and output (stdin, stdout, and stderr).
+# Read from stdin until ^EOF$ and overwrite hello.py with the lines
+# between "EOF":
+cat > hello.py << EOF
+#!/usr/bin/env python
+from __future__ import print_function
+import sys
+print("#stdout", file=sys.stdout)
+print("#stderr", file=sys.stderr)
+for line in sys.stdin:
+ print(line, file=sys.stdout)
+EOF
+
+# Run hello.py with various stdin, stdout, and stderr redirections:
+python hello.py < "input.in"
+python hello.py > "output.out"
+python hello.py 2> "error.err"
+python hello.py > "output-and-error.log" 2>&1
+python hello.py > /dev/null 2>&1
+# The output error will overwrite the file if it exists,
+# if you want to append instead, use ">>":
+python hello.py >> "output.out" 2>> "error.err"
+
+# Overwrite output.txt, append to error.err, and count lines:
+info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
+wc -l output.out error.err
+
+# Run a command and print its file descriptor (e.g. /dev/fd/123)
+# see: man fd
+echo <(echo "#helloworld")
+
+# Overwrite output.txt with "#helloworld":
+cat > output.out <(echo "#helloworld")
+echo "#helloworld" > output.out
+echo "#helloworld" | cat > output.out
+echo "#helloworld" | tee output.out >/dev/null
+
+# Cleanup temporary files verbosely (add '-i' for interactive)
+rm -v output.out error.err output-and-error.log
# Commands can be substituted within other commands using $( ):
# The following command displays the number of files and directories in the
diff --git a/c.html.markdown b/c.html.markdown
index 6daabe94..874197d3 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -84,7 +84,7 @@ int main() {
// doubles are usually 64-bit floating-point numbers
double x_double = 0.0; // real numbers without any suffix are doubles
- // Integral types may be unsigned.
+ // integer types may be unsigned (only positive)
unsigned short ux_short;
unsigned int ux_int;
unsigned long long ux_long_long;
diff --git a/java.html.markdown b/java.html.markdown
index dffc3828..f08c4679 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -123,9 +123,15 @@ public class LearnJava {
// Others to check out
// ArrayLists - Like arrays except more functionality is offered,
// and the size is mutable
- // LinkedLists
- // Maps
- // HashMaps
+ // LinkedLists - Implementation of doubly-linked list. All of the
+ // operations perform as could be expected for
+ // a doubly-linked list.
+ // Maps - A set of objects that maps keys to values. A map cannot contain
+ // duplicate keys; each key can map to at most one value.
+ // HashMaps - This class uses a hashtable to implement the Map interface.
+ // This allows the execution time of basic operations,
+ // such as get and insert element, to remain constant even
+ // for large sets.
///////////////////////////////////////
// Operators
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 52625bc2..9f3a03ba 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1149,7 +1149,7 @@ my @list = 1, 3, 9 ... * > 30; # you can use a predicate
# (with the Whatever Star, here).
my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above)
-my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers,
+my @fib = 1, 1, *+* ... *; # lazy infinite list of fibonacci series,
# computed using a closure!
my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above)
my @fib = 1, 1, { $^a + $^b } ... *; #(... also equivalent to the above)
diff --git a/python.html.markdown b/python.html.markdown
index ba236fb3..f7b0082c 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -7,21 +7,21 @@ contributors:
filename: learnpython.py
---
-Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular
+Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular
languages in existence. I fell in love with Python for its syntactic clarity. It's basically
executable pseudocode.
Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. Look for another tour of Python 3 soon!
+to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial.
```python
# Single line comments start with a number symbol.
""" Multiline strings can be written
- using three "'s, and are often used
+ using three "s, and are often used
as comments
"""
@@ -55,7 +55,7 @@ to Python 2.x. Look for another tour of Python 3 soon!
# Modulo operation
7 % 3 # => 1
-# Exponentiation (x to the y'th power)
+# Exponentiation (x to the yth power)
2**4 # => 16
# Enforce precedence with parentheses
diff --git a/python3.html.markdown b/python3.html.markdown
index e478e57f..0b4feccc 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -7,7 +7,7 @@ contributors:
filename: learnpython3.py
---
-Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular
+Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular
languages in existence. I fell in love with Python for its syntactic clarity. It's basically
executable pseudocode.
@@ -20,7 +20,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria
# Single line comments start with a number symbol.
""" Multiline strings can be written
- using three "'s, and are often used
+ using three "s, and are often used
as comments
"""
@@ -51,7 +51,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria
# Modulo operation
7 % 3 # => 1
-# Exponentiation (x to the y'th power)
+# Exponentiation (x to the yth power)
2**4 # => 16
# Enforce precedence with parentheses
diff --git a/r.html.markdown b/r.html.markdown
index 7cb56fd7..c555d748 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -179,7 +179,7 @@ c(3,3,3,2,2,1) # 3 3 3 2 2 1
# You can also have infinitely large or small numbers
class(Inf) # "numeric"
class(-Inf) # "numeric"
-# You might use "Inf", for example, in integrate( dnorm(x), 3, Inf);
+# You might use "Inf", for example, in integrate(dnorm, 3, Inf);
# this obviates Z-score tables.
# BASIC ARITHMETIC
@@ -236,11 +236,12 @@ c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
# FACTORS
# The factor class is for categorical data
# Factors can be ordered (like childrens' grade levels) or unordered (like gender)
-factor(c("female", "female", "male", "NA", "female"))
-# female female male NA female
-# Levels: female male NA
+factor(c("female", "female", "male", NA, "female"))
+# female female male <NA> female
+# Levels: female male
# The "levels" are the values the categorical data can take
-levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA"
+# Note that missing data does not enter the levels
+levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male"
# If a factor vector has length 1, its levels will have length 1, too
length(factor("male")) # 1
length(levels(factor("male"))) # 1
diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown
new file mode 100644
index 00000000..460086e3
--- /dev/null
+++ b/ru-ru/java-ru.html.markdown
@@ -0,0 +1,506 @@
+---
+language: java
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Madison Dickson", "http://github.com/mix3d"]
+translators:
+ - ["Sergey Gaykov", "https://github.com/gaykov"]
+filename: LearnJavaRu.java
+lang: ru-ru
+---
+
+Java - это объектно ориентированный язык программирования общего назначения,
+основанный на классах и поддерживающий параллельное программирование.
+[Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html)
+
+```java
+// Однострочные комментарии начинаются с //.
+/*
+Многострочные комментарии
+выглядят так.
+*/
+/**
+JavaDoc-комментарии выглядят так. Они используются для описания класса
+и его членов.
+*/
+
+// Импорт класса ArrayList из пакета java.util.
+import java.util.ArrayList;
+// Импорт всех классов из пакета java.security.
+import java.security.*;
+
+// Каждый .java файл содержит один публичный класс, имя которого совпадает с
+// именем файла.
+public class LearnJavaRu {
+
+ // Программа должна содержать метод main, который является точкой входа.
+ public static void main (String[] args) {
+
+ // System.out.println используется для печати строк.
+ System.out.println("Hello World!");
+ System.out.println(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
+
+ // Чтобы напечатать что-либо не заканчивая переводом строки
+ // используется System.out.print.
+ System.out.print("Hello ");
+ System.out.print("World");
+
+
+ ///////////////////////////////////////
+ // Типы и Переменные
+ ///////////////////////////////////////
+
+ // Переменные объявляются с использованием <тип> <имя>
+ // Byte - 8-битное целое число.
+ // (-128 <= byte <= 127)
+ byte fooByte = 100;
+
+ // Short - 16-битное целое число.
+ // (-32,768 <= short <= 32,767)
+ short fooShort = 10000;
+
+ // Integer - 32-битное целое число.
+ // (-2,147,483,648 <= int <= 2,147,483,647)
+ int fooInt = 1;
+
+ // Long - 64-битное целое число.
+ // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
+ long fooLong = 100000L;
+ // L используется для указания на то, что переменная имеет тип long;
+ // По умолчанию, числа без L являются integer.
+
+ // Замечание: в Java нет беззнаковых типов.
+
+ // Float - 32-битное IEEE 754 число с плавающей запятой с одинарной степенью точности.
+ float fooFloat = 234.5f;
+ // f используется для указания на то, что переменная имеет тип float;
+ // иначе, число являлось бы double.
+
+ // Double - 64-битное IEEE 754 число с плавающей запятой с двойной степенью точности.
+ double fooDouble = 123.4;
+
+ // Boolean - true или false
+ boolean fooBoolean = true;
+ boolean barBoolean = false;
+
+ // Char - Простой 16-битный символ Unicode.
+ char fooChar = 'A';
+
+ // Переменным final не может быть присвоен другой объект.
+ final int HOURS_I_WORK_PER_WEEK = 9001;
+
+ // Строки.
+ String fooString = "My String Is Here!";
+
+ // \n - это экранированный символ, который означает начало новой строки.
+ String barString = "Printing on a new line?\nNo Problem!";
+ // \t - это экранированный символ, который добавляет символ табуляции.
+ String bazString = "Do you want to add a tab?\tNo Problem!";
+ System.out.println(fooString);
+ System.out.println(barString);
+ System.out.println(bazString);
+
+ // Массивы
+ // Размер массива должен быть указан при объявлении.
+ // Объявлять массив можно в следующих форматах:
+ //<тип данных> [] <имя> = new <тип данных>[<размер массива>];
+ //<тип данных> <имя>[] = new <тип данных>[<размер массива>];
+ int [] intArray = new int[10];
+ String [] stringArray = new String[1];
+ boolean boolArray [] = new boolean[100];
+
+ // Другой способ объявления и инициализации массива:
+ int [] y = {9000, 1000, 1337};
+ String names [] = {"Bob", "John", "Fred", "Juan Pedro"};
+ boolean bools[] = new boolean[] {true, false, false};
+
+ // Индексация массива - доступ к элементу.
+ System.out.println("intArray @ 0: " + intArray[0]);
+
+ // Массивы изменяемы и индекс в них начинается с 0.
+ intArray[1] = 1;
+ System.out.println("intArray @ 1: " + intArray[1]); // => 1
+
+ // Дополнительно.
+ // ArrayLists - похож на массив, но предлагает больше возможностей,
+ // его размер изменяемый.
+ // LinkedLists - реализация двусвязного списка. Все операции
+ // выполняются так, как ожидается от двусвязного
+ // списка.
+ // Maps - набор объектов, в которых присутствует связь
+ // ключ-значение. В Map ключ не может дублироваться.
+ // Каждый ключ связан только с одним значением.
+ // HashMaps - этот класс использует хэш-таблицу для реализации
+ // интерфейса Map. Это позволяет сохранить постоянной
+ // скорость выполнения базовых операций, таких как
+ // добавление и удаление элементов, вне зависимости
+ // от размера множества.
+
+ ///////////////////////////////////////
+ // Операторы
+ ///////////////////////////////////////
+ System.out.println("\n->Операторы");
+
+ int i1 = 1, i2 = 2; // Сокращение для множественного объявления.
+
+ // Арифметика в Java проста.
+ System.out.println("1+2 = " + (i1 + i2)); // => 3
+ System.out.println("2-1 = " + (i2 - i1)); // => 1
+ System.out.println("2*1 = " + (i2 * i1)); // => 2
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 округлено)
+
+ // Остаток от деления
+ System.out.println("11%3 = "+(11 % 3)); // => 2
+
+ // Операторы сравнения.
+ System.out.println("3 == 2? " + (3 == 2)); // => false
+ System.out.println("3 != 2? " + (3 != 2)); // => true
+ System.out.println("3 > 2? " + (3 > 2)); // => true
+ System.out.println("3 < 2? " + (3 < 2)); // => false
+ System.out.println("2 <= 2? " + (2 <= 2)); // => true
+ System.out.println("2 >= 2? " + (2 >= 2)); // => true
+
+ // Побитовые операторы!
+ /*
+ ~ Унарное побитовое дополнение.
+ << Знаковый сдвиг влево.
+ >> Знаковый сдвиг вправо.
+ >>> Беззнаковый сдвиг вправо.
+ & Побитовое И.
+ ^ Побитовое исключающее ИЛИ.
+ | Побитовое ИЛИ.
+ */
+
+ // Операторы инкремента.
+ int i = 0;
+ System.out.println("\n->Inc/Dec-rementation");
+ // Операторы ++ и -- увеличивают и уменьшают значение на 1 соответственно.
+ // Если они находятся перед переменной, сначала происходит
+ // увеличение/уменьшение, затем операция, если после,
+ // то сначала выполняется операция, затем увеличение/уменьшение.
+ System.out.println(i++); //i = 1, напечатает 0 (пре-инкремент)
+ System.out.println(++i); //i = 2, напечатает 2 (пре-инкремент)
+ System.out.println(i--); //i = 1, напечатает 2 (пост-декремент)
+ System.out.println(--i); //i = 0, напечатает 0 (пре-декремент)
+
+ ///////////////////////////////////////
+ // Контролирующие операторы.
+ ///////////////////////////////////////
+ System.out.println("\n->Контролирующие операторы");
+
+ // Оператор if такой же, как и в С.
+ int j = 10;
+ if (j == 10){
+ System.out.println("Я напечатаюсь!");
+ } else if (j > 10) {
+ System.out.println("Я нет.");
+ } else {
+ System.out.println("И я тоже нет.");
+ }
+
+ // Цикл while.
+ int fooWhile = 0;
+ while(fooWhile < 100)
+ {
+ // System.out.println(fooWhile);
+ // Увеличить счетчик.
+ // Будет пройдено 100 итераций, fooWhile 0,1,2...99
+ fooWhile++;
+ }
+ System.out.println("Значение fooWhile: " + fooWhile);
+
+ // Цикл Do While.
+ int fooDoWhile = 0;
+ do
+ {
+ // System.out.println(fooDoWhile);
+ // Увеличить счетчик.
+ // Будет пройдено 100 итераций, fooDoWhile 0->99
+ fooDoWhile++;
+ } while(fooDoWhile < 100);
+ System.out.println("Значение fooDoWhile: " + fooDoWhile);
+
+ // Цикл for.
+ int fooFor;
+ // Структура цикла for => for(<начальное_состояние>; <условие>; <шаг>)
+ for(fooFor=0; fooFor<10; fooFor++){
+ // System.out.println(fooFor);
+ // Пройдет 10 итераций., fooFor 0->9
+ }
+ System.out.println("Значение fooFor: " + fooFor);
+
+ // Цикл For Each
+ // Автоматический проход через массив или список объектов.
+ int[] fooList = {1,2,3,4,5,6,7,8,9};
+ // Структура цикла for each => for(<объект> : <объект_массив>)
+ // читается как: для каждого объекта в массиве
+ // заметка: тип объекта должен совпадать с типом массива.
+
+ for( int bar : fooList ){
+ System.out.println(bar);
+ //Пройдет 9 итераций и напечатает 1-9 на новых строках.
+ }
+
+ // Switch Case
+ // switch работает с типами byte, short, char и int.
+ // Также он работает с перечислениями,
+ // классом String и с некоторыми классами-обертками над
+ // примитивными типами: Character, Byte, Short и Integer.
+ int month = 3;
+ String monthString;
+ switch (month){
+ case 1:
+ monthString = "Январь";
+ break;
+ case 2:
+ monthString = "Февраль";
+ break;
+ case 3:
+ monthString = "Март";
+ break;
+ default:
+ monthString = "Другой месяц";
+ break;
+ }
+ System.out.println("Результат Switch Case: " + monthString);
+
+ // Сокращенный синтаксис условного оператора.
+ // Вы можете использовать этот синтаксис для быстрого присвоения
+ // или логических переходов.
+ // Читается так: "Если (условие) истинно, использовать <значение 1>,
+ // в ином случае, использовать <значение 2>"
+ int foo = 5;
+ String bar = (foo < 10) ? "A" : "B";
+ System.out.println(bar); // Напечатает А, потому что условие истинно
+
+
+ ///////////////////////////////////////
+ // Преобразование и приведение типов данных.
+ ///////////////////////////////////////
+
+ // Преобразование данных.
+
+ // Преобразование строки в число.
+ Integer.parseInt("123"); // Вернет числовое представление "123".
+
+ // Преобразование числа в строку
+ Integer.toString(123); // Вернет строковое представление 123.
+
+ // Для других преобразований смотрите следующие классы:
+ // Double
+ // Long
+ // String
+
+ // Приведение типов
+ // Вы так же можете приводить типы в Java.
+ // Подробнее об этом можно узнать по ссылке:
+ // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
+
+
+ ///////////////////////////////////////
+ // Классы и Функции
+ ///////////////////////////////////////
+
+ System.out.println("\n->Классы и Функции");
+
+ // (Класс Bicycle определен ниже)
+
+ // Для создания экземпляра класса используется new.
+ Bicycle trek = new Bicycle();
+
+ // Вызов методов объекта.
+ trek.speedUp(3); // Вы должны всегда использовать сеттеры и геттеры.
+ trek.setCadence(100);
+
+ // toString возвращает строковое представление объекта.
+ System.out.println("trek info: " + trek.toString());
+
+ } // Конец метода main.
+} // Конец класса LearnJava.
+
+
+// Вы можете включать другие, не публичные классы в .java файл.
+
+
+// Синтаксис объявления класса:
+// <public/private/protected> class <имя класса>{
+// // Поля с данными, конструкторы, функции, все внутри.
+// // Функции называют методами в Java.
+// }
+
+class Bicycle {
+
+ // Поля/Переменные класса Bicycle.
+ public int cadence;// Публичные(public): Доступны из любого места.
+ private int speed; // Приватные(private): Доступны только внутри класса.
+ protected int gear;// Защищенные(protected): Доступ из класса и наследников.
+ String name; // по умолчанию: Доступны только внутри пакета.
+
+ // Конструкторы - способ создания класса.
+ // Это конструктор:
+ public Bicycle() {
+ gear = 1;
+ cadence = 50;
+ speed = 5;
+ name = "Bontrager";
+ }
+
+ // Это конструктор, который принимает аргументы:
+ public Bicycle(int startCadence, int startSpeed, int startGear, String name) {
+ this.gear = startGear;
+ this.cadence = startCadence;
+ this.speed = startSpeed;
+ this.name = name;
+ }
+
+ // Синтаксис функций:
+ // <public/private/protected> <тип возвращаемого значения> <имя>(<аргументы>)
+
+ // Классы в Java часто реализуют сеттеры и геттеры для своих полей.
+
+ // Синтаксис определения метода:
+ // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>)
+ public int getCadence() {
+ return cadence;
+ }
+
+ // void-методы не возвращают значений.
+ public void setCadence(int newValue) {
+ cadence = newValue;
+ }
+
+ public void setGear(int newValue) {
+ gear = newValue;
+ }
+
+ public void speedUp(int increment) {
+ speed += increment;
+ }
+
+ public void slowDown(int decrement) {
+ speed -= decrement;
+ }
+
+ public void setName(String newName) {
+ name = newName;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ //Метод для отображения значений атрибутов объекта.
+ @Override
+ public String toString() {
+ return "gear: " + gear +
+ " cadence: " + cadence +
+ " speed: " + speed +
+ " name: " + name;
+ }
+} // конец класса Bicycle.
+
+// PennyFarthing - это класс, наследованный от Bicycle
+class PennyFarthing extends Bicycle {
+ // (Penny Farthings - это такие велосипеды с большим передним колесом,
+ // у них нет передач.)
+
+ public PennyFarthing(int startCadence, int startSpeed){
+ // Вызов конструктора родительского класса.
+ super(startCadence, startSpeed, 0, "PennyFarthing");
+ }
+
+ // Вы должны пометить метод, который переопределяете, при помощи @аннотации
+ // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте:
+ // http://docs.oracle.com/javase/tutorial/java/annotations/
+ @Override
+ public void setGear(int gear) {
+ gear = 0;
+ }
+
+}
+
+// Интерфейсы
+// Синтаксис определения интерфейса:
+// <модификатор доступа> interface <имя> extends <базовый интерфейс> {
+// // Константы
+// // Определение методов.
+//}
+
+// Пример - Еда:
+public interface Edible {
+ // Любой класс, реализующий этот интерфейс, должен реализовать этот метод.
+ public void eat();
+}
+
+public interface Digestible {
+ public void digest();
+}
+
+
+// Сейчас мы можем создать класс, реализующий оба эти интерфейса.
+public class Fruit implements Edible, Digestible {
+ public void eat() {
+ //...
+ }
+
+ public void digest() {
+ //...
+ }
+}
+
+// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать
+// несколько интерфейсов. Например:
+public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo {
+ public void InterfaceOneMethod() {
+
+ }
+
+ public void InterfaceTwoMethod() {
+
+ }
+}
+
+```
+
+## Почитать еще
+
+Здесь приведены ссылки только для того, чтобы получить общее представление о Java. Гуглите, чтобы найти какие-либо конкретные примеры.
+
+**Официальные руководства Oracle**:
+
+* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
+
+* [Модификаторы доступа в Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
+
+* [Концепции объектно-ориентированного программирования](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+ * [Наследование](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
+ * [Полиморфизм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
+ * [Абстракция](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
+
+* [Исключения](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
+
+* [Интерфейсы](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
+
+* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
+
+* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)
+
+**Уроки онлайн**
+
+* [Learneroo.com - Изучение Java](http://www.learneroo.com)
+
+* [Codingbat.com](http://codingbat.com/java)
+
+
+**Книги**:
+
+* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
+
+* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
+
+* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300)
+
+
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 3c67de2e..e58c513d 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -10,6 +10,7 @@ contributors:
- ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
- ["Ariel Krakowski", "http://www.learneroo.com"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
---
@@ -271,6 +272,19 @@ else
end
#=> "OK job"
+# exception handling:
+begin
+ # code here that might raise an exception
+ raise NoMemoryError, 'You ran out of memory.'
+rescue NoMemoryError => exception_variable
+ puts 'NoMemoryError was raised', exception_variable
+rescue RuntimeError => other_exception_variable
+ puts 'RuntimeError was raised now'
+else
+ puts 'This runs if no exceptions were thrown at all'
+ensure
+ puts 'This code always runs no matter what'
+end
# Functions
diff --git a/scala.html.markdown b/scala.html.markdown
index 5a0cc0ff..dc039f0c 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -4,6 +4,7 @@ filename: learnscala.scala
contributors:
- ["George Petrov", "http://github.com/petrovg"]
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
+ - ["Geoff Liu", "http://geoffliu.me"]
filename: learn.scala
---
@@ -20,34 +21,47 @@ Scala - the scalable language
scala>
- This is the so called REPL. You can run commands in the REPL. Let's do just
- that:
+ This is the so called REPL (Read-Eval-Print Loop). You may type any valid
+ Scala expression into it, and the result will be printed. We will explain what
+ Scala files look like further into this tutorial, but for now, let's start
+ with some basics.
*/
-println(10) // prints the integer 10
-println("Boo!") // printlns the string Boo!
+/////////////////////////////////////////////////
+// 1. Basics
+/////////////////////////////////////////////////
+// Single line comments start with two forward slashes
-// Some basics
+/*
+ Multi line comments, as you can already see from above, look like this.
+*/
// Printing, and forcing a new line on the next print
println("Hello world!")
+println(10)
+
// Printing, without forcing a new line on next print
print("Hello world")
-// Declaring values is done using either var or val
-// val declarations are immutable, whereas var's are mutable. Immutability is
+// Declaring values is done using either var or val.
+// val declarations are immutable, whereas var's are mutable. Immutability is
// a good thing.
val x = 10 // x is now 10
x = 20 // error: reassignment to val
-var x = 10
-x = 20 // x is now 20
+var y = 10
+y = 20 // y is now 20
-// Single line comments start with two forward slashes
-/*
-Multi line comments look like this.
+/*
+ Scala is a statically typed language, yet note that in the above declarations, we did not specify
+ a type. This is due to a language feature called type inference. In most cases, Scala compiler can
+ guess what the type of a variable is, so you don't have to type it every time. We can explicitly
+ declare the type of a variable like so:
*/
+val z: Int = 10
+val a: Double = 1.0
+val b: Double = 10 // Notice automatic conversion from Int to Double, result is 10.0, not 10
// Boolean values
true
@@ -64,9 +78,11 @@ true == false // false
2 - 1 // 1
5 * 3 // 15
6 / 2 // 3
+6 / 4 // 1
+6.0 / 4 // 1.5
-// Evaluating a command in the REPL gives you the type and value of the result
+// Evaluating an expression in the REPL gives you the type and value of the result
1 + 7
@@ -78,23 +94,63 @@ true == false // false
This means the result of evaluating 1 + 7 is an object of type Int with a
value of 8
- 1+7 will give you the same result
+ Note that "res29" is a sequentially generated variable name to store the results of the
+ expressions you typed, your output may differ.
*/
+"Scala strings are surrounded by double quotes"
+'a' // A Scala Char
+// 'Single quote strings don't exist' <= This causes an error
+
+// Strings have the usual Java methods defined on them
+"hello world".length
+"hello world".substring(2, 6)
+"hello world".replace("C", "3")
-// Everything is an object, including a function. Type these in the REPL:
+// They also have some extra Scala methods. See also: scala.collection.immutable.StringOps
+"hello world".take(5)
+"hello world".drop(5)
-7 // results in res30: Int = 7 (res30 is just a generated var name for the result)
+// String interpolation: notice the prefix "s"
+val n = 45
+s"We have $n apples" // => "We have 45 apples"
+
+// Expressions inside interpolated strings are also possible
+val a = Array(11, 9, 6)
+s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old."
+s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples."
+s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4"
+
+// Formatting with interpolated strings with the prefix "f"
+f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25"
+f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454"
+
+// Raw strings, ignoring special characters.
+raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r."
+
+// Some characters need to be "escaped", e.g. a double quote inside a string:
+"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown""
+
+// Triple double-quotes let strings span multiple rows and contain quotes
+val html = """<form id="daform">
+ <p>Press belo', Joe</p>
+ <input type="submit">
+ </form>"""
+
+
+/////////////////////////////////////////////////
+// 2. Functions
+/////////////////////////////////////////////////
// The next line gives you a function that takes an Int and returns it squared
-(x:Int) => x * x
+(x:Int) => x * x
// You can assign this function to an identifier, like this:
val sq = (x:Int) => x * x
/* The above says this
-
- sq: Int => Int = <function1>
+
+ sq: Int => Int = <function1>
Which means that this time we gave an explicit name to the value - sq is a
function that take an Int and returns Int.
@@ -105,28 +161,68 @@ val sq = (x:Int) => x * x
sq(10) // Gives you this: res33: Int = 100.
// The colon explicitly defines the type of a value, in this case a function
-// taking an Int and returning an Int.
-val add10: Int => Int = _ + 10
+// taking an Int and returning an Int.
+val add10: Int => Int = _ + 10
-// Scala allows methods and functions to return, or take as parameters, other
-// functions or methods.
-List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element
+/////////////////////////////////////////////////
+// 3. Flow Control
+/////////////////////////////////////////////////
-// Anonymous functions can be used instead of named functions:
-List(1, 2, 3) map (x => x + 10)
+1 to 5
+val r = 1 to 5
+r.foreach( println )
-// And the underscore symbol, can be used if there is just one argument to the
-// anonymous function. It gets bound as the variable
-List(1, 2, 3) map (_ + 10)
+r foreach println
+// NB: Scala is quite lenient when it comes to dots and brackets - study the
+// rules separately. This helps write DSLs and APIs that read like English
+
+(5 to 1 by -1) foreach ( println )
+
+// A while loops
+var i = 0
+while (i < 10) { println("i " + i); i+=1 }
+
+while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why?
+
+i // Show the value of i. Note that while is a loop in the classical sense -
+ // it executes sequentially while changing the loop variable. while is very
+ // fast, faster that Java // loops, but using the combinators and
+ // comprehensions above is easier to understand and parallelize
+
+// A do while loop
+do {
+ println("x is still less than 10");
+ x += 1
+} while (x < 10)
+
+// Tail recursion is an idiomatic way of doing recurring things in Scala.
+// Recursive functions need an explicit return type, the compiler can't infer it.
+// Here it's Unit.
+def showNumbersInRange(a:Int, b:Int):Unit = {
+ print(a)
+ if (a < b)
+ showNumbersInRange(a + 1, b)
+}
+showNumbersInRange(1,14)
-// If the anonymous block AND the function you are applying both take one
-// argument, you can even omit the underscore
-List("Dom", "Bob", "Natalia") foreach println
+// Conditionals
+val x = 10
-// Data structures
+if (x == 1) println("yeah")
+if (x == 10) println("yeah")
+if (x == 11) println("yeah")
+if (x == 11) println ("yeah") else println("nay")
+
+println(if (x == 10) "yeah" else "nope")
+val text = if (x == 10) "yeah" else "nope"
+
+
+/////////////////////////////////////////////////
+// 4. Data Structures
+/////////////////////////////////////////////////
val a = Array(1, 2, 3, 5, 8, 13)
a(0)
@@ -145,8 +241,8 @@ val s = Set(1, 3, 7)
s(0)
s(1)
-/* Look up the documentation of map here -
- * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
+/* Look up the documentation of map here -
+ * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
* and make sure you can read it
*/
@@ -175,110 +271,27 @@ d._1
d._2
+/////////////////////////////////////////////////
+// 5. Object Oriented Programming
+/////////////////////////////////////////////////
-// Combinators
-
-s.map(sq)
-
-val sSquared = s. map(sq)
-
-sSquared.filter(_ < 10)
-
-sSquared.reduce (_+_)
-
-// The filter function takes a predicate (a function from A -> Boolean) and
-// selects all elements which satisfy the predicate
-List(1, 2, 3) filter (_ > 2) // List(3)
-List(
- Person(name = "Dom", age = 23),
- Person(name = "Bob", age = 30)
-).filter(_.age > 25) // List(Person("Bob", 30))
-
-
-// Scala a foreach method defined on certain collections that takes a type
-// returning Unit (a void method)
-aListOfNumbers foreach (x => println(x))
-aListOfNumbers foreach println
-
-
-
-
-// For comprehensions
-
-for { n <- s } yield sq(n)
-
-val nSquared2 = for { n <- s } yield sq(n)
-
-for { n <- nSquared2 if n < 10 } yield n
-
-for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
-
-/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas
- a for-comprehension defines a relationship between two sets of data. */
-
-
-
-// Loops and iteration
-
-1 to 5
-val r = 1 to 5
-r.foreach( println )
-
-r foreach println
-// NB: Scala is quite lenient when it comes to dots and brackets - study the
-// rules separately. This helps write DSLs and APIs that read like English
-
-(5 to 1 by -1) foreach ( println )
-
-// A while loops
-var i = 0
-while (i < 10) { println("i " + i); i+=1 }
-
-while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why?
-
-i // Show the value of i. Note that while is a loop in the classical sense -
- // it executes sequentially while changing the loop variable. while is very
- // fast, faster that Java // loops, but using the combinators and
- // comprehensions above is easier to understand and parallelize
-
-// A do while loop
-do {
- println("x is still less than 10");
- x += 1
-} while (x < 10)
-
-// Tail recursion is an idiomatic way of doing recurring things in Scala.
-// Recursive functions need an explicit return type, the compiler can't infer it.
-// Here it's Unit.
-def showNumbersInRange(a:Int, b:Int):Unit = {
- print(a)
- if (a < b)
- showNumbersInRange(a + 1, b)
-}
-
-
-
-// Conditionals
-
-val x = 10
-
-if (x == 1) println("yeah")
-if (x == 10) println("yeah")
-if (x == 11) println("yeah")
-if (x == 11) println ("yeah") else println("nay")
-
-println(if (x == 10) "yeah" else "nope")
-val text = if (x == 10) "yeah" else "nope"
-
-var i = 0
-while (i < 10) { println("i " + i); i+=1 }
-
-
-
-// Object oriented features
+/*
+ Aside: Everything we've done so far in this tutorial has been simple
+ expressions (values, functions, etc). These expressions are fine to type into
+ the command-line interpreter for quick tests, but they cannot exist by
+ themselves in a Scala file. For example, you cannot have just "val x = 5" in
+ a Scala file. Instead, the only top-level constructs allowed in Scala are:
+
+ - objects
+ - classes
+ - case classes
+ - traits
+
+ And now we will explain what these are.
+*/
-// Classname is Dog
-class Dog {
+class Dog(br: String) {
+ var breed: String = br
//A method called bark, returning a String
def bark: String = {
// the body of the method
@@ -286,10 +299,13 @@ class Dog {
}
}
-// Classes can contain nearly any other construct, including other classes,
-// functions, methods, objects, case classes, traits etc.
+val mydog = new Dog("greyhound")
+println(mydog.breed) // => "greyhound"
+println(mydog.bark) // => "Woof, woof!"
+// Classes can contain nearly any other construct, including other classes,
+// functions, methods, objects, case classes, traits etc.
// Case classes
@@ -298,8 +314,12 @@ case class Person(name:String, phoneNumber:String)
Person("George", "1234") == Person("Kate", "1236")
+// Objects and traits coming soon!
+
-// Pattern matching
+/////////////////////////////////////////////////
+// 6. Pattern Matching
+/////////////////////////////////////////////////
val me = Person("George", "1234")
@@ -338,49 +358,77 @@ matcher("52917") // => "No match on '52917'"
matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917"
-// Strings
+/////////////////////////////////////////////////
+// 7. Functional Programming
+/////////////////////////////////////////////////
-"Scala strings are surrounded by double quotes" //
-'a' // A Scala Char
-'Single quote strings don't exist' // Error
-"Strings have the usual Java methods defined on them".length
-"They also have some extra Scala methods.".reverse
+// Scala allows methods and functions to return, or take as parameters, other
+// functions or methods.
-// Seealso: scala.collection.immutable.StringOps
+List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element
-println("ABCDEF".length)
-println("ABCDEF".substring(2, 6))
-println("ABCDEF".replace("C", "3"))
+// Anonymous functions can be used instead of named functions:
+List(1, 2, 3) map (x => x + 10)
-// String interpolation
-val n = 45
-println(s"We have $n apples") // => "We have 45 apples"
+// And the underscore symbol, can be used if there is just one argument to the
+// anonymous function. It gets bound as the variable
+List(1, 2, 3) map (_ + 10)
-// Expressions inside interpolated strings are also possible
-val a = Array(11, 9, 6)
-println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old."
-println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples."
-println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4"
+// If the anonymous block AND the function you are applying both take one
+// argument, you can even omit the underscore
+List("Dom", "Bob", "Natalia") foreach println
-// Formatting with interpolated strings (note the prefixed f)
-println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25"
-println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122"
-// Ignoring special characters.
-println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r."
+// Combinators
-// Some characters need to be 'escaped', e.g. a double quote inside a string:
-val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown""
+s.map(sq)
-// Triple double-quotes let strings span multiple rows and contain quotes
-val html = """<form id="daform">
- <p>Press belo', Joe</p>
- | <input type="submit">
- </form>"""
+val sSquared = s. map(sq)
+
+sSquared.filter(_ < 10)
+
+sSquared.reduce (_+_)
+
+// The filter function takes a predicate (a function from A -> Boolean) and
+// selects all elements which satisfy the predicate
+List(1, 2, 3) filter (_ > 2) // List(3)
+case class Person(name:String, phoneNumber:String)
+List(
+ Person(name = "Dom", age = 23),
+ Person(name = "Bob", age = 30)
+).filter(_.age > 25) // List(Person("Bob", 30))
+
+
+// Scala a foreach method defined on certain collections that takes a type
+// returning Unit (a void method)
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
+aListOfNumbers foreach (x => println(x))
+aListOfNumbers foreach println
+
+// For comprehensions
+
+for { n <- s } yield sq(n)
+
+val nSquared2 = for { n <- s } yield sq(n)
+
+for { n <- nSquared2 if n < 10 } yield n
+
+for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
+
+/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas
+ a for-comprehension defines a relationship between two sets of data. */
+
+
+/////////////////////////////////////////////////
+// 8. Implicits
+/////////////////////////////////////////////////
+Coming soon!
-// Application structure and organization
+/////////////////////////////////////////////////
+// 9. Misc
+/////////////////////////////////////////////////
// Importing things
import scala.collection.immutable.List
diff --git a/tmux.html.markdown b/tmux.html.markdown
index de3a8341..9eb96303 100644
--- a/tmux.html.markdown
+++ b/tmux.html.markdown
@@ -2,8 +2,7 @@
category: tool
tool: tmux
contributors:
- - ["kaernyk", "https://github.com/kaernyk"]
- - ["jmaud", "https://github.com/jmaud"]
+ - ["wzsk", "https://github.com/wzsk"]
filename: LearnTmux.txt
---
diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown
new file mode 100644
index 00000000..c223297c
--- /dev/null
+++ b/zh-cn/python3-cn.html.markdown
@@ -0,0 +1,629 @@
+---
+language: python3
+contributors:
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+translators:
+ - ["Geoff Liu", "http://geoffliu.me"]
+filename: learnpython3-cn.py
+lang: zh-cn
+---
+
+Python是由吉多·范罗苏姆(Guido Van Rossum)在90年代早期设计。它是如今最常用的编程
+语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。
+
+欢迎大家斧正。英文版原作Louie Dinh [@louiedinh](http://twitter.com/louiedinh)
+或着Email louiedinh [at] [谷歌的信箱服务]。中文翻译Geoff Liu。
+
+注意:这篇教程是特别为Python3写的。如果你想学旧版Python2,我们特别有另一篇教程。
+
+```python
+
+# 用井字符开头的是单行注释
+
+""" 多行字符串用三个引号
+ 包裹,也常被用来做多
+ 行注释
+"""
+
+####################################################
+## 1. 原始数据类型和运算符
+####################################################
+
+# 整数
+3 # => 3
+
+# 算术没有什么出乎意料的
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+
+# 但是除法例外,会自动转换成浮点数
+35 / 5 # => 7.0
+5 / 3 # => 1.6666666666666667
+
+# 整数除法的结果都是向下取整
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # 浮点数也可以
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# 浮点数的运算结果也是浮点数
+3 * 2.0 # => 6.0
+
+# 模除
+7 % 3 # => 1
+
+# x的y次方
+2**4 # => 16
+
+# 用括号决定优先级
+(1 + 3) * 2 # => 8
+
+# 布尔值
+True
+False
+
+# 用not取非
+not True # => False
+not False # => True
+
+# 逻辑运算符,注意and和or都是小写
+True and False #=> False
+False or True #=> True
+
+# 整数也可以当作布尔值
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
+# 用==判断相等
+1 == 1 # => True
+2 == 1 # => False
+
+# 用!=判断不等
+1 != 1 # => False
+2 != 1 # => True
+
+# 比较大小
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# 大小比较可以连起来!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# 字符串用单引双引都可以
+"这是个字符串"
+'这也是个字符串'
+
+# 用加号连接字符串
+"Hello " + "world!" # => "Hello world!"
+
+# 字符串可以被当作字符列表
+"This is a string"[0] # => 'T'
+
+# 用.format来格式化字符串
+"{} can be {}".format("strings", "interpolated")
+
+# 可以重复参数以节省时间
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+
+# 如果不想数参数,可以用关键字
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+
+# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法
+"%s can be %s the %s way" % ("strings", "interpolated", "old")
+
+# None是一个对象
+None # => None
+
+# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。
+"etc" is None # => False
+None is None # => True
+
+# None,0,空字符串,空列表,空字典都算是False
+# 所有其他值都是True
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
+
+
+####################################################
+## 2. 变量和集合
+####################################################
+
+# print是内置的打印函数
+print("I'm Python. Nice to meet you!")
+
+# 在给变量赋值前不用提前声明
+# 传统的变量命名是小写,用下划线分隔单词
+some_var = 5
+some_var # => 5
+
+# 访问未赋值的变量会抛出异常
+# 参考流程控制一段来学习异常处理
+some_unknown_var # 抛出NameError
+
+# 用列表(list)储存序列
+li = []
+# 创建列表时也可以同时赋给元素
+other_li = [4, 5, 6]
+
+# 用append在列表最后追加元素
+li.append(1) # li现在是[1]
+li.append(2) # li现在是[1, 2]
+li.append(4) # li现在是[1, 2, 4]
+li.append(3) # li现在是[1, 2, 4, 3]
+# 用pop从列表尾部删除
+li.pop() # => 3 且li现在是[1, 2, 4]
+# 把3再放回去
+li.append(3) # li变回[1, 2, 4, 3]
+
+# 列表存取跟数组一样
+li[0] # => 1
+# 取出最后一个元素
+li[-1] # => 3
+
+# 越界存取会造成IndexError
+li[4] # 抛出IndexError
+
+# 列表有切割语法
+li[1:3] # => [2, 4]
+# 取尾
+li[2:] # => [4, 3]
+# 取头
+li[:3] # => [1, 2, 4]
+# 隔一个取一个
+li[::2] # =>[1, 4]
+# 倒排列表
+li[::-1] # => [3, 4, 2, 1]
+# 可以用三个参数的任何组合来构建切割
+# li[始:终:步伐]
+
+# 用del删除任何一个元素
+del li[2] # li is now [1, 2, 3]
+
+# 列表可以相加
+# 注意:li和other_li的值都不变
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# 用extend拼接列表
+li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6]
+
+# 用in测试列表是否包含值
+1 in li # => True
+
+# 用len取列表长度
+len(li) # => 6
+
+
+# 元组是不可改变的序列
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # 抛出TypeError
+
+# 列表允许的操作元组大都可以
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# 可以把元组合列表解包,赋值给变量
+a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3
+# 元组周围的括号是可以省略的
+d, e, f = 4, 5, 6
+# 交换两个变量的值就这么简单
+e, d = d, e # 现在d是5,e是4
+
+
+# 用字典表达映射关系
+empty_dict = {}
+# 初始化的字典
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# 用[]取值
+filled_dict["one"] # => 1
+
+
+# 用keys获得所有的键。因为keys返回一个可迭代对象,所以在这里把结果包在list里。我们下面会详细介绍可迭代。
+# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。
+list(filled_dict.keys()) # => ["three", "two", "one"]
+
+
+# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。
+list(filled_dict.values()) # => [3, 2, 1]
+
+
+# 用in测试一个字典是否包含一个键
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# 访问不存在的键会导致KeyError
+filled_dict["four"] # KeyError
+
+# 用get来避免KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# 当键不存在的时候get方法可以返回默认值
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+
+# setdefault方法只有当键不存在的时候插入新值
+filled_dict.setdefault("five", 5) # filled_dict["five"]设为5
+filled_dict.setdefault("five", 6) # filled_dict["five"]还是5
+
+# 字典赋值
+filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
+filled_dict["four"] = 4 # 另一种赋值方法
+
+# 用del删除
+del filled_dict["one"] # 从filled_dict中把one删除
+
+
+# 用set表达集合
+empty_set = set()
+# 初始化一个集合,语法跟字典相似。
+some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4}
+
+# 可以把集合赋值于变量
+filled_set = some_set
+
+# 为集合添加元素
+filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5}
+
+# & 取交集
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# | 取并集
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# - 取补集
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# in 测试集合是否包含元素
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+## 3. 流程控制和迭代器
+####################################################
+
+# 先随便定义一个变量
+some_var = 5
+
+# 这是个if语句。注意缩进在Python里是有意义的
+# 印出"some_var比10小"
+if some_var > 10:
+ print("some_var比10大")
+elif some_var < 10: # elif句是可选的
+ print("some_var比10小")
+else: # else也是可选的
+ print("some_var就是10")
+
+
+"""
+用for循环语句遍历列表
+打印:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ print("{} is a mammal".format(animal))
+
+"""
+"range(number)"返回数字列表从0到给的数字
+打印:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print(i)
+
+"""
+while循环直到条件不满足
+打印:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print(x)
+ x += 1 # x = x + 1 的简写
+
+# 用try/except块处理异常状况
+try:
+ # 用raise抛出异常
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # pass是无操作,但是应该在这里处理错误
+except (TypeError, NameError):
+ pass # 可以同时处理不同类的错误
+else: # else语句是可选的,必须在所有的except之后
+ print("All good!") # 只有当try运行完没有错误的时候这句才会运行
+
+
+# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列
+# 的对象。比如说上面range返回的对象就是可迭代的。
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) # => range(1,10) 是一个实现可迭代接口的对象
+
+# 可迭代对象可以遍历
+for i in our_iterable:
+ print(i) # 打印 one, two, three
+
+# 但是不可以随机访问
+our_iterable[1] # 抛出TypeError
+
+# 可迭代对象知道怎么生成迭代器
+our_iterator = iter(our_iterable)
+
+# 迭代器是一个可以记住遍历的位置的对象
+# 用__next__可以取得下一个元素
+our_iterator.__next__() #=> "one"
+
+# 再一次调取__next__时会记得位置
+our_iterator.__next__() #=> "two"
+our_iterator.__next__() #=> "three"
+
+# 当迭代器所有元素都取出后,会抛出StopIteration
+our_iterator.__next__() # 抛出StopIteration
+
+# 可以用list一次取出迭代器所有的元素
+list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
+
+
+
+####################################################
+## 4. 函数
+####################################################
+
+# 用def定义新函数
+def add(x, y):
+ print("x is {} and y is {}".format(x, y))
+ return x + y # 用return语句返回
+
+# 调用函数
+add(5, 6) # => 印出"x is 5 and y is 6"并且返回11
+
+# 也可以用关键字参数来调用函数
+add(y=6, x=5) # 关键字参数可以用任何顺序
+
+
+# 我们可以定义一个可变参数函数
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+
+# 我们也可以定义一个关键字可变参数函数
+def keyword_args(**kwargs):
+ return kwargs
+
+# 我们来看看结果是什么:
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# 这两种可变参数可以混着用
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # 相当于 foo(1, 2, 3, 4)
+all_the_args(**kwargs) # 相当于 foo(a=3, b=4)
+all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4)
+
+
+# 函数作用域
+x = 5
+
+def setX(num):
+ # 局部作用域的x和全局域的x是不同的
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # 现在全局域的x被赋值
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
+# 函数在Python是一等公民
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# 也有匿名函数
+(lambda x: x > 2)(3) # => True
+
+# 内置的高阶函数
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+####################################################
+## 5. 类
+####################################################
+
+
+# 定义一个继承object的类
+class Human(object):
+
+ # 类属性,被所有此类的实例共用。
+ species = "H. sapiens"
+
+ # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属
+ # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这
+ # 种格式。
+ def __init__(self, name):
+ # Assign the argument to the instance's name attribute
+ self.name = name
+
+ # 实例方法,第一个参数总是self,就是这个实例对象
+ def say(self, msg):
+ return "{name}: {message}".format(name=self.name, message=msg)
+
+ # 类方法,被所有此类的实例共用。第一个参数是这个类对象。
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # 静态方法。调用时没有实例或类的绑定。
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# 构造一个实例
+i = Human(name="Ian")
+print(i.say("hi")) # 印出 "Ian: hi"
+
+j = Human("Joel")
+print(j.say("hello")) # 印出 "Joel: hello"
+
+# 调用一个类方法
+i.get_species() # => "H. sapiens"
+
+# 改一个共用的类属性
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# 调用静态方法
+Human.grunt() # => "*grunt*"
+
+
+####################################################
+## 6. 模块
+####################################################
+
+# 用import导入模块
+import math
+print(math.sqrt(16)) # => 4
+
+# 也可以从模块中导入个别值
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# 可以导入一个模块中所有值
+# 警告:不建议这么做
+from math import *
+
+# 如此缩写模块名字
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Python模块其实就是普通的Python文件。你可以自己写,然后导入,
+# 模块的名字就是文件的名字。
+
+# 你可以这样列出一个模块里所有的值
+import math
+dir(math)
+
+
+####################################################
+## 7. 高级用法
+####################################################
+
+# 用生成器(generators)方便地写惰性运算
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的
+# 值全部算好。这意味着double_numbers不会生成大于15的数字。
+#
+# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。
+#
+# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。
+range_ = range(1, 900000000)
+# 当找到一个 >=30 的结果就会停
+for i in double_numbers(range_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# 装饰器(decorators)
+# 这个例子中,beg装饰say
+# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print(say()) # Can you buy me a beer?
+print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
+```
+
+## 想继续学吗?
+
+### 线上免费材料(英文)
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+
+* [The Official Docs](http://docs.python.org/3/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/3/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+
+### 书籍(也是英文)
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+