Merge 'master' of github.com:adambard/learnxinyminutes-docs

This commit is contained in:
evuez 2015-10-16 10:42:41 +02:00
commit 85adff2c39
19 changed files with 605 additions and 233 deletions

View File

@ -90,17 +90,26 @@ else
echo "Your name is your username"
fi
# NOTE: if $Name is empty, bash sees the above condition as:
if [ -ne $USER ]
# which is invalid syntax
# so the "safe" way to use potentially empty variables in bash is:
if [ "$Name" -ne $USER ] ...
# which, when $Name is empty, is seen by bash as:
if [ "" -ne $USER ] ...
# which works as expected
# There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails"
echo "Always executed" && echo "Only executed if first command does NOT fail"
# To use && and || with if statements, you need multiple pairs of square brackets:
if [ $Name == "Steve" ] && [ $Age -eq 15 ]
if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
then
echo "This will run if $Name is Steve AND $Age is 15."
fi
if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "This will run if $Name is Daniya OR Zach."
fi

View File

@ -6,8 +6,8 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
- ["Marco Scannadinari", "https://marcoms.github.io"]
- ["Zachary Ferguson", "https://github.io/zfergus2"]
- ["himanshu", "https://github.com/himanshu81494"]
---
Ah, C. Still **the** language of modern high-performance computing.
@ -54,6 +54,8 @@ int function_2(void);
// Must declare a 'function prototype' before main() when functions occur after
// your main() function.
int add_two_ints(int x1, int x2); // function prototype
// although `int add_two_ints(int, int);` is also valid (no need to name the args),
// it is recommended to name arguments in the prototype as well for easier inspection
// Your program's entry point is a function called
// main with an integer return type.
@ -75,6 +77,9 @@ int main (int argc, char** argv)
// Types
///////////////////////////////////////
// All variables MUST be declared at the top of the current block scope
// we declare them dynamically along the code for the sake of the tutorial
// ints are usually 4 bytes
int x_int = 0;
@ -232,7 +237,7 @@ int main (int argc, char** argv)
0 || 1; // => 1 (Logical or)
0 || 0; // => 0
// Conditional expression ( ? : )
// Conditional ternary expression ( ? : )
int e = 5;
int f = 10;
int z;
@ -302,6 +307,8 @@ int main (int argc, char** argv)
for (i = 0; i <= 5; i++) {
; // use semicolon to act as the body (null statement)
}
// Or
for (i = 0; i <= 5; i++);
// branching with multiple choices: switch()
switch (a) {
@ -678,8 +685,56 @@ typedef void (*my_fnp_type)(char *);
// , | left to right //
//---------------------------------------------------//
```
/******************************* Header Files **********************************
Header files are an important part of c as they allow for the connection of c
source files and can simplify code and definitions by seperating them into
seperate files.
Header files are syntaxtically similar to c source files but reside in ".h"
files. They can be included in your c source file by using the precompiler
command #include "example.h", given that example.h exists in the same directory
as the c file.
*/
/* A safe guard to prevent the header from being defined too many times. This */
/* happens in the case of circle dependency, the contents of the header is */
/* already defined. */
#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */
#define EXAMPLE_H /* Define the macro EXAMPLE_H. */
/* Other headers can be included in headers and therefore transitively */
/* included into files that include this header. */
#include <string.h>
/* Like c source files macros can be defined in headers and used in files */
/* that include this header file. */
#define EXAMPLE_NAME "Dennis Ritchie"
/* Function macros can also be defined. */
#define ADD(a, b) (a + b)
/* Structs and typedefs can be used for consistency between files. */
typedef struct node
{
int val;
struct node *next;
} Node;
/* So can enumerations. */
enum traffic_light_state {GREEN, YELLOW, RED};
/* Function prototypes can also be defined here for use in multiple files, */
/* but it is bad practice to define the function in the header. Definitions */
/* should instead be put in a c file. */
Node createLinkedList(int *vals, int len);
/* Beyond the above elements, other definitions should be left to a c source */
/* file. Excessive includeds or definitions should, also not be contained in */
/* a header file but instead put into separate headers or a c file. */
#endif /* End of the if precompiler directive. */
```
## Further Reading
Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)

View File

@ -48,7 +48,7 @@ Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit sta
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# Pokud použiteje desetinné číslo, výsledek je jím také
# Pokud použijete desetinné číslo, výsledek je jím také
3 * 2.0 # => 6.0
# Modulo
@ -420,7 +420,7 @@ next(iterator) # Vyhodí StopIteration
## 4. Funkce
####################################################
# Pro vytvoření nové funkce použijte def
# Pro vytvoření nové funkce použijte klíčové slovo def
def secist(x, y):
print("x je {} a y je {}".format(x, y))
return x + y # Hodnoty se vrací pomocí return
@ -520,7 +520,7 @@ class Clovek(object):
# podtržítka na začátku a na konci značí, že se jedná o atribut nebo
# objekt využívaný Pythonem ke speciálním účelům, ale můžete sami
# definovat jeho chování. Metody jako __init__, __str__, __repr__
# a další se nazývají "magické metody". Nikdy nepoužívejte toto
# a další se nazývají "magické metody". Nikdy nepoužívejte toto
# speciální pojmenování pro běžné metody.
def __init__(self, jmeno):
# Přiřazení parametru do atributu instance jmeno

View File

@ -160,7 +160,7 @@ on a new line! ""Wow!"", the masses cried";
// List<datatype> <var name> = new List<datatype>();
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
List<int> z = new List<int> { 9000, 1000, 1337 }; // intialize
List<int> z = new List<int> { 9000, 1000, 1337 }; // initialize
// The <> are for generics - Check out the cool stuff section
// Lists don't default to a value;
@ -460,7 +460,7 @@ on a new line! ""Wow!"", the masses cried";
{
// OPTIONAL PARAMETERS
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones
MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones
// BY REF AND OUT PARAMETERS
int maxCount = 0, count; // ref params must have value
@ -481,7 +481,7 @@ on a new line! ""Wow!"", the masses cried";
// in case variable is null
int notNullable = nullable ?? 0; // 0
// ?. is an operator for null-propogation - a shorthand way of checking for null
// ?. is an operator for null-propagation - a shorthand way of checking for null
nullable?.Print(); // Use the Print() extension method if nullable isn't null
// IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is:
@ -650,7 +650,7 @@ on a new line! ""Wow!"", the masses cried";
{
return _cadence;
}
set // set - define a method to set a proprety
set // set - define a method to set a property
{
_cadence = value; // Value is the value passed in to the setter
}

View File

@ -106,6 +106,20 @@ selected:link { }
/* or an element in focus */
selected:focus { }
/* any element that is the first child of its parent */
selector:first-child {}
/* any element that is the last child of its parent */
selector:last-child {}
/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */
/* matches a virtual first child of the selected element */
selector::before {}
/* matches a virtual last child of the selected element */
selector::after {}
/* At appropriate places, an asterisk may be used as a wildcard to select every
element */
* { } /* all elements */

View File

@ -23,8 +23,10 @@ about [D](http://dlang.org/). The D programming language is a modern, general-pu
multi-paradigm language with support for everything from low-level features to
expressive high-level abstractions.
D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool
dudes. With all that out of the way, let's look at some examples!
D is actively developed by a large group of super-smart people and is spearheaded by
[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and
[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu).
With all that out of the way, let's look at some examples!
```c
import std.stdio;
@ -36,9 +38,10 @@ void main() {
writeln(i);
}
auto n = 1; // use auto for type inferred variables
// 'auto' can be used for inferring types.
auto n = 1;
// Numeric literals can use _ as a digit seperator for clarity
// Numeric literals can use '_' as a digit separator for clarity.
while(n < 10_000) {
n += n;
}
@ -47,13 +50,15 @@ void main() {
n -= (n / 2);
} while(n > 0);
// For and while are nice, but in D-land we prefer foreach
// The .. creates a continuous range, excluding the end
// For and while are nice, but in D-land we prefer 'foreach' loops.
// The '..' creates a continuous range, including the first value
// but excluding the last.
foreach(i; 1..1_000_000) {
if(n % 2 == 0)
writeln(i);
}
// There's also 'foreach_reverse' when you want to loop backwards.
foreach_reverse(i; 1..int.max) {
if(n % 2 == 1) {
writeln(i);
@ -69,16 +74,18 @@ are passed to functions by value (i.e. copied) and classes are passed by referen
we can use templates to parameterize all of these on both types and values!
```c
// Here, T is a type parameter. Think <T> from C++/C#/Java
// Here, 'T' is a type parameter. Think '<T>' from C++/C#/Java.
struct LinkedList(T) {
T data = null;
LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think <T>
// Use '!' to instantiate a parameterized type. Again, think '<T>'.
LinkedList!(T)* next;
}
class BinTree(T) {
T data = null;
// If there is only one template parameter, we can omit parens
// If there is only one template parameter, we can omit the parentheses.
BinTree!T left;
BinTree!T right;
}
@ -93,13 +100,11 @@ enum Day {
Saturday,
}
// Use alias to create abbreviations for types
// Use alias to create abbreviations for types.
alias IntList = LinkedList!int;
alias NumTree = BinTree!double;
// We can create function templates as well!
T max(T)(T a, T b) {
if(a < b)
return b;
@ -107,9 +112,8 @@ T max(T)(T a, T b) {
return a;
}
// Use the ref keyword to ensure pass by referece.
// That is, even if a and b are value types, they
// will always be passed by reference to swap
// Use the ref keyword to ensure pass by reference. That is, even if 'a' and 'b'
// are value types, they will always be passed by reference to 'swap()'.
void swap(T)(ref T a, ref T b) {
auto temp = a;
@ -117,13 +121,13 @@ void swap(T)(ref T a, ref T b) {
b = temp;
}
// With templates, we can also parameterize on values, not just types
// With templates, we can also parameterize on values, not just types.
class Matrix(uint m, uint n, T = int) {
T[m] rows;
T[n] columns;
}
auto mat = new Matrix!(3, 3); // We've defaulted type T to int
auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'.
```
@ -133,21 +137,20 @@ have the syntax of POD structures (`structure.x = 7`) with the semantics of
getter and setter methods (`object.setX(7)`)!
```c
// Consider a class parameterized on a types T, U
// Consider a class parameterized on types 'T' & 'U'.
class MyClass(T, U) {
T _data;
U _other;
}
// And "getter" and "setter" methods like so
// And "getter" and "setter" methods like so:
class MyClass(T, U) {
T _data;
U _other;
// Constructors are always named `this`
// Constructors are always named 'this'.
this(T t, U u) {
// This will call the setter methods below.
data = t;
other = u;
}
@ -170,16 +173,24 @@ class MyClass(T, U) {
_other = u;
}
}
// And we use them in this manner
// And we use them in this manner:
void main() {
auto mc = MyClass!(int, string);
auto mc = new MyClass!(int, string)(7, "seven");
mc.data = 7;
mc.other = "seven";
// Import the 'stdio' module from the standard library for writing to
// console (imports can be local to a scope).
import std.stdio;
writeln(mc.data);
writeln(mc.other);
// Call the getters to fetch the values.
writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
// Call the setters to assign new values.
mc.data = 8;
mc.other = "eight";
// Call the getters again to fetch the new values.
writefln("Later: data = %d, str = %s", mc.data, mc.other);
}
```

View File

@ -16,7 +16,7 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con
web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común
para front-end que Java.
JavaScript no sólo se limita a los navegadores web, aunque: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular.
Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular.
¡La retroalimentación es bienvenida! Puedes encontrarme en:
[@adambrenecki](https://twitter.com/adambrenecki), o
@ -124,7 +124,7 @@ undefined; // usado para indicar que un valor no está presente actualmente
// (aunque undefined es un valor en sí mismo)
// false, null, undefined, NaN, 0 y "" es false; todo lo demás es true.
// Note que 0 is false y "0" es true, a pesar de que 0 == "0".
// Note que 0 es false y "0" es true, a pesar de que 0 == "0".
// Aunque 0 === "0" sí es false.
///////////////////////////////////

View File

@ -4,6 +4,7 @@ filename: learnhaml.haml
contributors:
- ["Simon Neveu", "https://github.com/sneveu"]
- ["Thibault", "https://github.com/iTech-"]
lang: fr-fr
---
Haml est un langage de balisage utilisé majoritairement avec Ruby, qui décrit de manière simple et propre le HTML de n'importe quelle page web sans l'utilisation des traditionnelles lignes de code. Le langage est une alternative très populaire au langage de templates Rails (.erb) et permet d'intégrer du code en Ruby dans votre balisage.

View File

@ -5,6 +5,7 @@ contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- ["Leo Rudberg" , "http://github.com/LOZORD"]
- ["Betsy Lorton" , "http://github.com/schbetsy"]
- ["Bruno Volcov", "http://github.com/volcov"]
filename: LearnGit.txt
---
@ -76,6 +77,11 @@ other repositories, or not!
A branch is essentially a pointer to the last commit you made. As you go on
committing, this pointer will automatically update to point the latest commit.
### Tag
A tag is a mark on specific point in history. Typically people use this
functionality to mark release points (v1.0, and so on)
### HEAD and head (component of .git dir)
HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD.
@ -206,6 +212,28 @@ $ git branch -m myBranchName myNewBranchName
$ git branch myBranchName --edit-description
```
### tag
Manage your tags
```bash
# List tags
$ git tag
# Create a annotated tag
# The -m specifies a tagging message,which is stored with the tag.
# If you dont specify a message for an annotated tag,
# Git launches your editor so you can type it in.
$ git tag -a v2.0 -m 'my version 2.0'
# Show info about tag
# That shows the tagger information, the date the commit was tagged,
# and the annotation message before showing the commit information.
$ git show v2.0
# Push a single tag to remote
$ git push origin v2.0
# Push a lot of tags to remote
$ git push origin --tags
```
### checkout
Updates all files in the working tree to match the version in the index, or specified tree.

View File

@ -423,3 +423,5 @@ idioms. Or you can click on a function name in [the
documentation](http://golang.org/pkg/) and the source code comes up!
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information.

View File

@ -58,7 +58,7 @@ Drawbacks of JSON include lack of type definition and some sort of DTD.
"alternative style": {
"comment": "check this out!"
, "comma position": "doesn't matter - as long as it's before the value, then it's valid"
, "comma position": "doesn't matter - as long as it's before the next key, then it's valid"
, "another comment": "how nice"
},

View File

@ -12,7 +12,7 @@ filename: learn-latex.tex
% LaTeX is NOT a "What You See Is What You Get" word processing software like
% MS Word, or OpenOffice Writer
% Every Latex command starts with a backslash (\)
% Every LaTeX command starts with a backslash (\)
% LaTeX documents start with a defining the type of document it's compiling
% Other document types include book, report, presentations, etc.
@ -45,7 +45,7 @@ filename: learn-latex.tex
% but before the main sections of the body.
% This command is available in the document classes article and report.
\begin{abstract}
LaTex documentation written as LaTex! How novel and totally not my idea!
LaTeX documentation written as LaTeX! How novel and totally not my idea!
\end{abstract}
% Section commands are intuitive.
@ -63,8 +63,8 @@ I think we need another one
Much better now.
\label{subsec:pythagoras}
% By using the asterisk we can suppress Latex's inbuilt numbering.
% This works for other Latex commands as well.
% By using the asterisk we can suppress LaTeX's inbuilt numbering.
% This works for other LaTeX commands as well.
\section*{This is an unnumbered section}
However not all sections have to be numbered!
@ -74,7 +74,7 @@ a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to
the source code. \\
\section{Lists}
Lists are one of the easiest things to create in Latex! I need to go shopping
Lists are one of the easiest things to create in LaTeX! I need to go shopping
tomorrow, so let's make a grocery list.
\begin{enumerate} % This creates an "enumerate" environment.
% \item tells the enumerate to increment
@ -106,7 +106,7 @@ Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\
% The opposite also holds true. Variable can also be rendered in math-mode.
My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
I haven't found a Greek letter that yet that Latex doesn't know about!
I haven't found a Greek letter that yet that LaTeX doesn't know about!
Operators are essential parts of a mathematical document:
trigonometric functions ($\sin$, $\cos$, $\tan$),
@ -126,7 +126,7 @@ $^{10}/_{7}$
% \frac{numerator}{denominator}
$\frac{n!}{k!(n - k)!}$ \\
We can also insert equations in an "equation environment."
We can also insert equations in an "equation environment".
% Display math with the equation 'environment'
\begin{equation} % enters math-mode
@ -141,7 +141,7 @@ figures, equations, sections, etc.
Summations and Integrals are written with sum and int commands:
% Some latex compilers will complain if there are blank lines
% Some LaTeX compilers will complain if there are blank lines
% In an equation environment.
\begin{equation}
\sum_{i=0}^{5} f_{i}
@ -181,9 +181,9 @@ We can also insert Tables in the same way as figures.
% \section{Hyperlinks} % Coming soon
\section{Getting Latex to not compile something (i,e, Source Code)}
Let's say we want to include some code into our Latex document,
we would then need Latex to not try and interpret that text and
\section{Getting LaTeX to not compile something (i.e. Source Code)}
Let's say we want to include some code into our LaTeX document,
we would then need LaTeX to not try and interpret that text and
instead just print it to the document. We do this we a verbatim
environment.
@ -198,7 +198,7 @@ environment.
\section{Compiling}
By now you're probably wondering how to compile this fabulous document
and look at the glorious glory that is a Latex pdf.
and look at the glorious glory that is a LaTeX pdf.
(yes, this document actually does compiles). \\
Getting to the final document using LaTeX consists of the following steps:
\begin{enumerate}

View File

@ -6,6 +6,7 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
translators:
- ["João Farias", "https://github.com/JoaoGFarias"]
- ["Elton Viana", "https://github.com/eltonvs"]
lang: pt-br
filename: c-pt.el
---
@ -139,13 +140,13 @@ int main() {
int var_length_array[size]; // declara o VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
//Uma possível saída para esse programa seria:
// > Entre o tamanho do array:: 10
// Uma possível saída para esse programa seria:
// > Entre o tamanho do array: 10
// > sizeof array = 40
// String são apenas arrays de caracteres terminados por um
// byte NUL (0x00), representado em string pelo caracter especial '\0'.
// (Não precisamos incluir o byte NUL em literais de string; o compilador
// byte nulo (0x00), representado em string pelo caracter especial '\0'.
// (Não precisamos incluir o byte nulo em literais de string; o compilador
// o insere ao final do array para nós.)
char uma_string[20] = "Isto é uma string";
// Observe que 'é' não está na tabela ASCII
@ -153,8 +154,8 @@ int main() {
// Porém, comentários podem conter acentos
printf("%s\n", uma_string); // %s formata a string
printf("%d\n", uma_string[16]); // => 0
// i.e., byte #17 é 0 (assim como 18, 19, e 20)
printf("%d\n", uma_string[17]); // => 0
// i.e., byte #18 é 0 (assim como o 19°, 20°, 21°...)
// Se temos caracteres entre aspas simples, temos um caracter literal.
// Seu tipo é `int`, *não* `char` (por razões históricas).
@ -220,7 +221,7 @@ int main() {
0 || 1; // => 1 (Ou lógico)
0 || 0; // => 0
//Expressão condicional ( ? : )
//Expressão condicional ternária ( ? : )
int a = 5;
int b = 10;
int z;
@ -290,6 +291,8 @@ int main() {
for (i = 0; i <= 5; i++) {
; // Use ponto e vírgula para agir como um corpo (declaração nula)
}
// Ou
for (i = 0; i <= 5; i++);
// Criando branchs com escolhas múltiplas: switch()
switch (alguma_expressao_integral) {

View File

@ -2,40 +2,49 @@
language: purescript
contributors:
- ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"]
- ["Thimoteus", "https://github.com/Thimoteus"]
---
PureScript is a small strongly, statically typed language compiling to Javascript.
* Learn more at [http://www.purescript.org/](http://www.purescript.org/)
* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/)
* Documentation: [http://pursuit.purescript.org/](http://pursuit.purescript.org/)
* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/)
All the noncommented lines of code can be run in the PSCI REPL, though some will
require the `--multi-line-mode` flag.
```haskell
--
-- 1. Primitive datatypes that corresponds to their Javascript
-- equivalents at runtime.
import Prelude
-- Numbers
1 + 7*5 :: Number -- 36
1.0 + 7.2*5.5 :: Number -- 40.6
-- Ints
1 + 2*5 :: Int -- 11
-- Types are inferred, so the following works fine
9 / 2.5 + 4.4 -- 8
9.0/2.5 + 4.4 -- 8.0
-- But Ints and Numbers don't mix, so the following won't
5/2 + 2.5 -- Expression 2.5 does not have type Int
-- Hexadecimal literals
0xff + 1 -- 256
-- Unary negation
6 * -3 -- -18
6 * negate 3 -- -18
-- Modulus
3 % 2 -- 1
4 % 2 -- 0
-- Modulus, from purescript-math (Math)
3.0 % 2.0 -- 1.0
4.0 % 2.0 -- 0.0
-- Inspect the type of an expression in psci
:t 9 / 2.5 + 4.4 -- Prim.Number
:t 9.5/2.5 + 4.4 -- Prim.Number
-- Booleans
true :: Boolean -- true
false :: Boolean -- false
-- Negation
not true --false
not true -- false
23 == 23 -- true
1 /= 4 -- true
1 >= 4 -- false
@ -49,19 +58,22 @@ true && (9 >= 19 || 1 < 2) -- true
-- Strings
"Hellow" :: String -- "Hellow"
-- Multiline string
-- Multiline string without newlines, to run in psci use the --multi-line-mode flag
"Hellow\
\orld" -- "Helloworld"
-- Multiline string with newlines
"""Hello
world""" -- "Hello\nworld"
-- Concatenate
"such " ++ "amaze" -- "such amaze"
--
-- 2. Arrays are Javascript arrays, but must be homogeneous
[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8]
[true, true, false] :: [Boolean] -- [true,true,false]
[1,1,2,3,5,8] :: Array Number -- [1,1,2,3,5,8]
[true, true, false] :: Array Boolean -- [true,true,false]
-- [1,2, true, "false"] won't work
-- `Cannot unify Prim.Number with Prim.Boolean`
-- `Cannot unify Prim.Int with Prim.Boolean`
-- Cons (prepend)
1 : [2,4,3] -- [1,2,4,3]
@ -84,91 +96,95 @@ append [1,2,3] [4,5,6] -- [1,2,3,4,5,6]
--
-- 3. Records are Javascript objects, with zero or more fields, which
-- can have different types
-- can have different types.
-- In psci you have to write `let` in front of the function to get a
-- top level binding.
let book = {title: "Foucault's pendulum", author: "Umberto Eco"}
-- Access properties
book.title -- "Foucault's pendulum"
getTitle b = b.title
let getTitle b = b.title
-- Works on all records with a title (but doesn't require any other field)
getTitle book -- "Foucault's pendulum"
getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco"
-- Can use underscores as shorthand
_.title book -- "Foucault's pendulum"
-- Update a record
changeTitle b t = b {title = t}
changeTitle book "Ill nome della rosa" -- {title: "Ill nome della
-- rosa", author: "Umberto Eco"}
let changeTitle b t = b {title = t}
getTitle (changeTitle book "Ill nome della rosa") -- "Ill nome della rosa"
--
-- 4. Functions
sumOfSquares x y = x*x+y*y
-- In psci's multiline mode
let sumOfSquares :: Int -> Int -> Int
sumOfSquares x y = x*x + y*y
sumOfSquares 3 4 -- 25
-- In psci you have to write `let` in front of the function to get a
-- top level binding
mod x y = x % y
mod 3 2 -- 1
let myMod x y = x % y
myMod 3.0 2.0 -- 1.0
-- Infix application of function
3 `mod` 2 -- 1
-- function application have higher precedence than all other
-- function application has higher precedence than all other
-- operators
sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025
-- Conditional
abs' n = if n>=0 then n else -n
let abs' n = if n>=0 then n else -n
abs' (-3) -- 3
-- Guarded equations
abs n | n >= 0 = n
| otherwise = -n
let abs'' n | n >= 0 = n
| otherwise = -n
-- Pattern matching
-- Note the type signature, input is an array of numbers The pattern
-- matching destructures and binds the array into parts
first :: [Number] -> Number
first (x:_) = x
first [3,4,5] -- 3
second :: [Number] -> Number
second (_:y:_) = y
second [3,4,5] -- 4
sumTwo :: [Number] -> [Number]
sumTwo (x:y:rest) = (x+y) : rest
sumTwo [2,3,4,5,6] -- [5,4,5,6]
-- Note the type signature, input is a list of numbers. The pattern matching
-- destructures and binds the list into parts.
-- Requires purescript-lists (Data.List)
let first :: forall a. List a -> a
first (Cons x _) = x
first (toList [3,4,5]) -- 3
let second :: forall a. List a -> a
second (Cons _ (Cons y _)) = y
second (toList [3,4,5]) -- 4
let sumTwo :: List Int -> List Int
sumTwo (Cons x (Cons y rest)) = x + y : rest
fromList (sumTwo (toList [2,3,4,5,6])) :: Array Int -- [5,4,5,6]
-- sumTwo doesn't handle when the array is empty or just have one
-- element in which case you get an error
-- sumTwo doesn't handle when the list is empty or there's only one element in
-- which case you get an error.
sumTwo [1] -- Failed pattern match
-- Complementing patterns to match
-- Good ol' Fibonacci
fib 1 = 1
fib 2 = 2
fib x = fib (x-1) + fib (x-2)
let fib 1 = 1
fib 2 = 2
fib x = fib (x-1) + fib (x-2)
fib 10 -- 89
-- Use underscore to match any, where you don't care about the binding name
isZero 0 = true
isZero _ = false
let isZero 0 = true
isZero _ = false
-- Pattern matching on records
ecoTitle {author = "Umberto Eco", title = t} = Just t
ecoTitle _ = Nothing
let ecoTitle {author = "Umberto Eco", title = t} = Just t
ecoTitle _ = Nothing
ecoTitle book -- Just ("Foucault's pendulum")
ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing
-- ecoTitle requires both field to type check:
ecoTitle {title: "The Quantum Thief"} -- Object does not have property author
ecoTitle {title: "The Quantum Thief"} -- Object lacks required property "author"
-- Lambda expressions
(\x -> x*x) 3 -- 9
(\x y -> x*x + y*y) 4 5 -- 41
sqr = \x -> x*x
let sqr = \x -> x*x
-- Currying
add x y = x + y -- is equivalent with
add = \x -> (\y -> x+y)
add3 = add 3
:t add3 -- Prim.Number -> Prim.Number
let myAdd x y = x + y -- is equivalent with
let myAdd' = \x -> \y -> x + y
let add3 = myAdd 3
:t add3 -- Prim.Int -> Prim.Int
-- Forward and backward function composition
-- drop 3 followed by taking 5
@ -177,9 +193,9 @@ add3 = add 3
(drop 3 <<< take 5) (1..20) -- [4,5]
-- Operations using higher order functions
even x = x % 2 == 0
let even x = x `mod` 2 == 0
filter even (1..10) -- [2,4,6,8,10]
map (\x -> x+11) (1..5) -- [12,13,14,15,16]
map (\x -> x + 11) (1..5) -- [12,13,14,15,16]
-- Requires purescript-foldable-traversabe (Data.Foldable)

View File

@ -15,7 +15,13 @@ 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. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
to Python 2.x. Python 2.7 is reachong end of life and will stop beeign maintained in 2020,
it is though recommended to start learnign Python with Python 3.
For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time,
using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial.
```python
@ -145,6 +151,12 @@ bool("") # => False
# Python has a print statement
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
# Simple way to get input data from console
input_string_var = raw_input("Enter some data: ") # Returns the data as a string
input_var = input("Enter some data: ") # Evaluates the data as python code
# Warning: Caution is recommended for input() method usage
# Note: In python 3, input() is deprecated and raw_input() is renamed to input()
# No need to declare variables before assigning to them.
some_var = 5 # Convention is to use lower_case_with_underscores
some_var # => 5

View File

@ -34,27 +34,27 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
3 # => 3
# Math is what you would expect
1 + 1 # => 2
8 - 1 # => 7
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
# Except division which returns floats, real numbers, by default
35 / 5 # => 7.0
# Result of integer division truncated down both for positive and negative.
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # works on floats too
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # works on floats too
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# When you use a float, results are floats
3 * 2.0 # => 6.0
3 * 2.0 # => 6.0
# Modulo operation
7 % 3 # => 1
7 % 3 # => 1
# Exponentiation (x**y, x to the yth power)
2**4 # => 16
2**4 # => 16
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
@ -64,20 +64,20 @@ True
False
# negate with not
not True # => False
not True # => False
not False # => True
# Boolean Operators
# Note "and" and "or" are case-sensitive
True and False # => False
False or True # => True
True and False # => False
False or True # => True
# Note using Bool operators with ints
0 and 2 # => 0
-5 or 0 # => -5
0 == False # => True
2 == True # => False
1 == True # => True
0 and 2 # => 0
-5 or 0 # => -5
0 == False # => True
2 == True # => False
1 == True # => True
# Equality is ==
1 == 1 # => True
@ -99,13 +99,13 @@ False or True # => True
# (is vs. ==) is checks if two variable refer to the same object, but == checks
# if the objects pointed to have the same values.
a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b = a # Point b at what a is pointing to
b is a # => True, a and b refer to the same object
b == a # => True, a's and b's objects are equal
b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b is a # => False, a and b do not refer to the same object
b == a # => True, a's and b's objects are equal
a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b = a # Point b at what a is pointing to
b is a # => True, a and b refer to the same object
b == a # => True, a's and b's objects are equal
b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b is a # => False, a and b do not refer to the same object
b == a # => True, a's and b's objects are equal
# Strings are created with " or '
"This is a string."
@ -114,24 +114,24 @@ b == a # => True, a's and b's objects are equal
# Strings can be added too! But try not to do this.
"Hello " + "world!" # => "Hello world!"
# Strings can be added without using '+'
"Hello " "world!" # => "Hello world!"
"Hello " "world!" # => "Hello world!"
# A string can be treated like a list of characters
"This is a string"[0] # => 'T'
# .format can be used to format strings, like this:
"{} can be {}".format("strings", "interpolated")
"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated"
# You can repeat the formatting arguments to save some typing.
"{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"
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna"
"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna"
# If your Python 3 code also needs to run on Python 2.5 and below, you can also
# still use the old style of formatting:
"%s can be %s the %s way" % ("strings", "interpolated", "old")
"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way"
# None is an object
@ -140,11 +140,11 @@ None # => None
# Don't use the equality "==" symbol to compare objects to None
# Use "is" instead. This checks for equality of object identity.
"etc" is None # => False
None is None # => True
None is None # => True
# None, 0, and empty strings/lists/dicts all evaluate to False.
# All other values are True
bool(0) # => False
bool(0) # => False
bool("") # => False
bool([]) # => False
bool({}) # => False
@ -155,11 +155,15 @@ bool({}) # => False
####################################################
# Python has a print function
print("I'm Python. Nice to meet you!")
print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
# By default the print function also prints out a newline at the end.
# Use the optional argument end to change the end character.
print("Hello, World", end="!") # => Hello, World!
print("Hello, World", end="!") # => Hello, World!
# Simple way to get input data from console
input_string_var = input("Enter some data: ") # Returns the data as a string
# Note: In earlier versions of Python, input() method was named as raw_input()
# No need to declare variables before assigning to them.
# Convention is to use lower_case_with_underscores
@ -186,7 +190,7 @@ li.pop() # => 3 and li is now [1, 2, 4]
li.append(3) # li is now [1, 2, 4, 3] again.
# Access a list like you would any array
li[0] # => 1
li[0] # => 1
# Look at the last element
li[-1] # => 3
@ -195,23 +199,23 @@ li[4] # Raises an IndexError
# You can look at ranges with slice syntax.
# (It's a closed/open range for you mathy types.)
li[1:3] # => [2, 4]
li[1:3] # => [2, 4]
# Omit the beginning
li[2:] # => [4, 3]
li[2:] # => [4, 3]
# Omit the end
li[:3] # => [1, 2, 4]
li[:3] # => [1, 2, 4]
# Select every second entry
li[::2] # =>[1, 4]
# Return a reversed copy of the list
li[::-1] # => [3, 4, 2, 1]
li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
# Make a one layer deep copy using slices
li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
# Remove arbitrary elements from a list with "del"
del li[2] # li is now [1, 2, 3]
del li[2] # li is now [1, 2, 3]
# Remove first occurrence of a value
li.remove(2) # li is now [1, 3]
@ -226,34 +230,34 @@ li.index(4) # Raises a ValueError as 4 is not in the list
# You can add lists
# Note: values for li and for other_li are not modified.
li + other_li # => [1, 2, 3, 4, 5, 6]
li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
# Check for existence in a list with "in"
1 in li # => True
1 in li # => True
# Examine the length with "len()"
len(li) # => 6
len(li) # => 6
# Tuples are like lists but are immutable.
tup = (1, 2, 3)
tup[0] # => 1
tup[0] # => 1
tup[0] = 3 # Raises a TypeError
# Note that a tuple of length one has to have a comma after the last element but
# tuples of other lengths, even zero, do not.
type((1)) # => <class 'int'>
type((1,)) # => <class 'tuple'>
type(()) # => <class 'tuple'>
type((1)) # => <class 'int'>
type((1,)) # => <class 'tuple'>
type(()) # => <class 'tuple'>
# You can do most of the list operations on tuples too
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
@ -273,45 +277,45 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# Note keys for dictionaries have to be immutable types. This is to ensure that
# the key can be converted to a constant hash value for quick look-ups.
# Immutable types include ints, floats, strings, tuples.
invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
# Look up values with []
filled_dict["one"] # => 1
filled_dict["one"] # => 1
# Get all keys as an iterable with "keys()". We need to wrap the call in list()
# to turn it into a list. We'll talk about those later. Note - Dictionary key
# ordering is not guaranteed. Your results might not match this exactly.
list(filled_dict.keys()) # => ["three", "two", "one"]
list(filled_dict.keys()) # => ["three", "two", "one"]
# Get all values as an iterable with "values()". Once again we need to wrap it
# in list() to get it out of the iterable. Note - Same as above regarding key
# ordering.
list(filled_dict.values()) # => [3, 2, 1]
list(filled_dict.values()) # => [3, 2, 1]
# Check for existence of keys in a dictionary with "in"
"one" in filled_dict # => True
1 in filled_dict # => False
"one" in filled_dict # => True
1 in filled_dict # => False
# Looking up a non-existing key is a KeyError
filled_dict["four"] # KeyError
filled_dict["four"] # KeyError
# Use "get()" method to avoid the KeyError
filled_dict.get("one") # => 1
filled_dict.get("four") # => None
filled_dict.get("one") # => 1
filled_dict.get("four") # => None
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4) # => 1
filled_dict.get("four", 4) # => 4
filled_dict.get("four", 4) # => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
# Adding to a dictionary
filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
#filled_dict["four"] = 4 #another way to add to dict
filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
#filled_dict["four"] = 4 #another way to add to dict
# Remove keys from a dictionary with del
del filled_dict["one"] # Removes the key "one" from filled dict
@ -325,24 +329,24 @@ del filled_dict["one"] # Removes the key "one" from filled dict
# Sets store ... well sets
empty_set = set()
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
# Similar to keys of a dictionary, elements of a set have to be immutable.
invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}
# Can set new variables to a set
filled_set = some_set
# Add one more item to the set
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# Do set intersection with &
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
filled_set & other_set # => {3, 4, 5}
# Do set union with |
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
@ -358,7 +362,7 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Check for existence in a set with in
2 in filled_set # => True
10 in filled_set # => False
10 in filled_set # => False
@ -444,12 +448,12 @@ try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
finally: # Execute under all circumstances
print("We can clean up resources here")
# Instead of try/finally to cleanup resources you can use a with statement
@ -463,11 +467,11 @@ with open("myfile.txt") as f:
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.
print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.
# We can loop over it.
for i in our_iterable:
print(i) # Prints one, two, three
print(i) # Prints one, two, three
# However we cannot address elements by index.
our_iterable[1] # Raises a TypeError
@ -484,7 +488,7 @@ next(our_iterator) # => "two"
next(our_iterator) # => "three"
# After the iterator has returned all of its data, it gives you a StopIterator Exception
next(our_iterator) # Raises StopIteration
next(our_iterator) # Raises StopIteration
# You can grab all the elements of an iterator by calling list() on it.
list(filled_dict.keys()) # => Returns ["one", "two", "three"]
@ -497,20 +501,20 @@ list(filled_dict.keys()) # => Returns ["one", "two", "three"]
# Use "def" to create new functions
def add(x, y):
print("x is {} and y is {}".format(x, y))
return x + y # Return values with a return statement
return x + y # Return values with a return statement
# Calling functions with parameters
add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
# Another way to call functions is with keyword arguments
add(y=6, x=5) # Keyword arguments can arrive in any order.
add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
# positional arguments
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
# keyword arguments, as well
@ -518,7 +522,7 @@ def keyword_args(**kwargs):
return kwargs
# Let's call it to see what happens
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# You can do both at once, if you like
@ -535,33 +539,33 @@ all_the_args(1, 2, a=3, b=4) prints:
# Use * to expand tuples and use ** to expand kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
# Returning multiple values (with tuple assignments)
def swap(x, y):
return y, x # Return multiple values as a tuple without the parenthesis.
# (Note: parenthesis have been excluded but can be included)
return y, x # Return multiple values as a tuple without the parenthesis.
# (Note: parenthesis have been excluded but can be included)
x = 1
y = 2
x, y = swap(x, y) # => x = 2, y = 1
# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
x, y = swap(x, y) # => x = 2, y = 1
# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
# Function Scope
x = 5
def set_x(num):
# Local var x not the same as global variable x
x = num # => 43
print (x) # => 43
x = num # => 43
print (x) # => 43
def set_global_x(num):
global x
print (x) # => 5
x = num # global var x is now set to 6
print (x) # => 6
print (x) # => 5
x = num # global var x is now set to 6
print (x) # => 6
set_x(43)
set_global_x(6)
@ -577,20 +581,20 @@ add_10 = create_adder(10)
add_10(3) # => 13
# There are also anonymous functions
(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# TODO - Fix for iterables
# There are built-in higher order functions
map(add_10, [1, 2, 3]) # => [11, 12, 13]
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
map(add_10, [1, 2, 3]) # => [11, 12, 13]
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# We can use list comprehensions for nice maps and filters
# List comprehension stores the output as a list which can itself be a nested list
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Classes
@ -657,15 +661,15 @@ j = Human("Joel")
print(j.say("hello")) # prints out "Joel: hello"
# Call our class method
i.get_species() # => "H. sapiens"
i.get_species() # => "H. sapiens"
# Change the shared attribute
Human.species = "H. neanderthalensis"
i.get_species() # => "H. neanderthalensis"
j.get_species() # => "H. neanderthalensis"
i.get_species() # => "H. neanderthalensis"
j.get_species() # => "H. neanderthalensis"
# Call the static method
Human.grunt() # => "*grunt*"
Human.grunt() # => "*grunt*"
# Update the property
i.age = 42
@ -689,8 +693,8 @@ print(math.sqrt(16)) # => 4
# You can get specific functions from a module
from math import ceil, floor
print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
# You can import all functions from a module.
# Warning: this is not recommended
@ -698,7 +702,7 @@ from math import *
# You can shorten module names
import math as m
math.sqrt(16) == m.sqrt(16) # => True
math.sqrt(16) == m.sqrt(16) # => True
# Python modules are just ordinary python files. You
# can write your own, and import them. The name of the
@ -757,7 +761,7 @@ def say(say_please=False):
return msg, say_please
print(say()) # Can you buy me a beer?
print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
@ -774,6 +778,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [Python Course](http://www.python-course.eu/index.php)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
### Dead Tree

View File

@ -12,8 +12,7 @@ contributors:
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Rahil Momin", "https://github.com/iamrahil"]
- ["Gabriel Halley", https://github.com/ghalley]
- ["Gabriel Halley", https://github.com/ghalley"]
---
```ruby

View File

@ -3,6 +3,7 @@ language: sass
filename: learnsass.scss
contributors:
- ["Laura Kyle", "https://github.com/LauraNK"]
- ["Sean Corrales", "https://github.com/droidenator"]
---
Sass is a CSS extension language that adds features such as variables, nesting, mixins and more.
@ -11,6 +12,7 @@ Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help develop
Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons.
This tutorial is written using SCSS.
If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling options but rather the tools to write your CSS more efficiently and make maintenance much easier.
```scss
@ -121,6 +123,69 @@ div {
/*Functions
==============================*/
/* Sass provides functions that can be used to accomplish a variety of
tasks. Consider the following */
/* Functions can be invoked by using their name and passing in the
required arguments */
body {
width: round(10.25px);
}
.footer {
background-color: fade_out(#000000, 0.25)
}
/* Compiles to: */
body {
width: 10px;
}
.footer {
background-color: rgba(0, 0, 0, 0.75);
}
/* You may also define your own functions. Functions are very similar to
mixins. When trying to choose between a function or a mixin, remember
that mixins are best for generating CSS while functions are better for
logic that might be used throughout your Sass code. The examples in
the Math Operators' section are ideal candidates for becoming a reusable
function. */
/* This function will take a target size and the parent size and calculate
and return the percentage */
@function calculate-percentage($target-size, $parent-size) {
@return $target-size / $parent-size * 100%;
}
$main-content: calculate-percentage(600px, 960px);
.main-content {
width: $main-content;
}
.sidebar {
width: calculate-percentage(300px, 960px);
}
/* Compiles to: */
.main-content {
width: 62.5%;
}
.sidebar {
width: 31.25%;
}
/*Extend (Inheritance)
==============================*/
@ -150,6 +215,12 @@ div {
border-color: #22df56;
}
/* Extending a CSS statement is preferable to creating a mixin
because of the way it groups together the classes that all share
the same base styling. If this was done with a mixin, the width,
height, and border would be duplicated for each statement that
called the mixin. While it won't affect your workflow, it will
add unnecessary bloat to the files created by the Sass compiler. */
@ -172,6 +243,7 @@ ul {
/* '&' will be replaced by the parent selector. */
/* You can also nest pseudo-classes. */
/* Keep in mind that over-nesting will make your code less maintainable.
Best practices recommend going no more than 3 levels deep when nesting.
For example: */
ul {
@ -212,6 +284,140 @@ ul li a {
/*Partials and Imports
==============================*/
/* Sass allows you to create partial files. This can help keep your Sass
code modularized. Partial files should begin with an '_', e.g. _reset.css.
Partials are not generated into CSS. */
/* Consider the following CSS which we'll put in a file called _reset.css */
html,
body,
ul,
ol {
margin: 0;
padding: 0;
}
/* Sass offers @import which can be used to import partials into a file.
This differs from the traditional CSS @import statement which makes
another HTTP request to fetch the imported file. Sass takes the
imported file and combines it with the compiled code. */
@import 'reset';
body {
font-size: 16px;
font-family: Helvetica, Arial, Sans-serif;
}
/* Compiles to: */
html, body, ul, ol {
margin: 0;
padding: 0;
}
body {
font-size: 16px;
font-family: Helvetica, Arial, Sans-serif;
}
/*Placeholder Selectors
==============================*/
/* Placeholders are useful when creating a CSS statement to extend. If you
wanted to create a CSS statement that was exclusively used with @extend,
you can do so using a placeholder. Placeholders begin with a '%' instead
of '.' or '#'. Placeholders will not appear in the compiled CSS. */
%content-window {
font-size: 14px;
padding: 10px;
color: #000;
border-radius: 4px;
}
.message-window {
@extend %content-window;
background-color: #0000ff;
}
/* Compiles to: */
.message-window {
font-size: 14px;
padding: 10px;
color: #000;
border-radius: 4px;
}
.message-window {
background-color: #0000ff;
}
/*Math Operations
==============================*/
/* Sass provides the following operators: +, -, *, /, and %. These can
be useful for calculating values directly in your Sass files instead
of using values that you've already calculated by hand. Below is an example
of a setting up a simple two column design. */
$content-area: 960px;
$main-content: 600px;
$sidebar-content: 300px;
$main-size: $main-content / $content-area * 100%;
$sidebar-size: $sidebar-content / $content-area * 100%;
$gutter: 100% - ($main-size + $sidebar-size);
body {
width: 100%;
}
.main-content {
width: $main-size;
}
.sidebar {
width: $sidebar-size;
}
.gutter {
width: $gutter;
}
/* Compiles to: */
body {
width: 100%;
}
.main-content {
width: 62.5%;
}
.sidebar {
width: 31.25%;
}
.gutter {
width: 6.25%;
}
```
@ -227,6 +433,15 @@ If you want to play with Sass in your browser, check out [SassMeister](http://sa
You can use either syntax, just go into the settings and select either Sass or SCSS.
## Compatibility
Sass can be used in any project as long as you have a program to compile it
into CSS. You'll want to verify that the CSS you're using is compatible
with your target browsers.
[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
## Further reading
* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
* [The Sass Way](http://thesassway.com/) provides tutorials (beginner-advanced) and articles.

View File

@ -7,7 +7,7 @@ contributors:
XML is a markup language designed to store and transport data.
Unlike HTML, XML does not specify how to display or to format data, just carry it.
Unlike HTML, XML does not specify how to display or to format data, it just carries it.
* XML Syntax
@ -83,7 +83,7 @@ With this tool, you can check the XML data outside the application logic.
<!DOCTYPE note SYSTEM "Bookstore.dtd">
<bookstore>
<book category="COOKING">
<title >Everyday Italian</title>
<title>Everyday Italian</title>
<price>30.00</price>
</book>
</bookstore>
@ -121,7 +121,7 @@ With this tool, you can check the XML data outside the application logic.
<bookstore>
<book category="COOKING">
<title >Everyday Italian</title>
<title>Everyday Italian</title>
<price>30.00</price>
</book>
</bookstore>