diff options
author | Philip Withnall <philip@tecnocode.co.uk> | 2013-08-22 21:47:59 (GMT) |
---|---|---|
committer | Philip Withnall <philip@tecnocode.co.uk> | 2013-08-22 21:47:59 (GMT) |
commit | 3d711c002e79c5b2e4839a0f982b4fc4d1b80539 (patch) | |
tree | 95f23641689acc8d4e20dffa1ab3bc50e2997c13 | |
parent | 06dda82769d0167a8c11e7f5c95c331326234818 (diff) |
Split slides.tex out into a separate TeX file per part
This makes things a little easier to manage.
-rw-r--r-- | Makefile | 11 | ||||
-rw-r--r-- | introduction-to-python.tex | 525 | ||||
-rw-r--r-- | python-functions-and-classes.tex | 273 | ||||
-rw-r--r-- | slides.tex | 800 | ||||
-rw-r--r-- | writing-sugar-activities.tex | 1 |
5 files changed, 812 insertions, 798 deletions
@@ -26,13 +26,20 @@ ES_EXERCISES = \ 9_dicts \ $(NULL) +TEX_FILES = \ + slides.tex \ + introduction-to-python.tex \ + python-functions-and-classes.tex \ + writing-sugar-activities.tex \ + $(NULL) + all: $(PDFS) -presentation.pdf: presentation.tex slides.tex +presentation.pdf: presentation.tex $(TEX_FILES) pdflatex "\providecommand\locale{$(LANG)}\input{$<}" pdflatex "\providecommand\locale{$(LANG)}\input{$<}" -handout.pdf: handout.tex slides.tex +handout.pdf: handout.tex $(TEX_FILES) pdflatex "\providecommand\locale{$(LANG)}\input{$<}" pdflatex "\providecommand\locale{$(LANG)}\input{$<}" diff --git a/introduction-to-python.tex b/introduction-to-python.tex new file mode 100644 index 0000000..03b9dbd --- /dev/null +++ b/introduction-to-python.tex @@ -0,0 +1,525 @@ +\section{\en{Interpreter}\es{Intérprete}} + +\en{You can run Python interactively, and enter programs which will be executed +line-by-line. This is not the best way to write a program, but is good for +experiments. Each instruction is also called a statement.} +\es{Es posible que ejecutar Python interactivamente y escribir programas que se +ejecutan línea a línea. Esta no es la mejor manera de escribir un programa, pero +es bueno para la experimentación.} + +\en{As with all programming languages, you write a program as a sequence of +instructions. The computer will execute them exactly as you write them, in +order, so if you write incorrect instructions your program will not function +correctly.} +\es{Al igual que con todos los lenguajes de programación, se escribe una +programa como una secuencia de instrucciones. El ordenador ejecutará +exactamente como usted los escribe, en orden, así que si usted escribe +instrucciones incorrectas su programa no funcionará correctamente.} + +\en{When it starts, the Python interpreter displays a \texttt{>{}>{}>} prompt, +indicating that it's waiting for an instruction to be inputted. Input to the +interpreter is always on lines prefixed by \texttt{>{}>{}>} or \texttt{...}, +whereas output from the interpreter isn't prefixed.} +\es{Cuando se inicia, el intérprete de Python muestra un aviso \texttt{>{}>{}>}, +lo que indica que está esperando una instrucción para ser introducida. De +entrada a la intérprete está siempre en líneas prefijadas por \texttt{>{}>{}>} o +\texttt{...}, mientras que la salida del intérprete no se prefija.} + +\begin{frame}[fragile] +\frametitle{\en{Interpreter}\es{Intérprete}} +\begin{lstlisting}[numbers=none] +$ python +Python 2.7.5 (default, Jul 8 2013, 09:48:44) +[GCC 4.8.1 20130603 (Red Hat 4.8.1)] on linux2 +Type "help", "copyright" "credits" or "license" +for more information. +\end{lstlisting} +\begin{lstlisting}[language=Python,numbers=none] +>>> print(4 + 5) +9 +\end{lstlisting} +\end{frame} + +\en{As well as arithmetic, you can manipulate strings. Strings are sequences of +characters, and the main operations on them are concatenation (joining two +strings together) and formatting (replacing placeholders in a string with other +values, such as numbers or other strings).} +\es{Así como la aritmética, se puede manipular cadenas. Cadenas son secuencias +de caracteres y las principales operaciones en ellos son concatenación (la unión +de dos cadenas) y formato (reemplazar los marcadores de posición en una cadena +con otros valores, tales como números u otras cadenas).} + +\en{In the following example, a pair of brackets surround the sum. Just as in +arithmetic, brackets in programming are used to order operations.} +\es{En el ejemplo siguiente, un par de soportes rodean la suma. Tal como en +la aritmética, los paréntesis se utilizan en la programación de operaciones para +ponen en orden.} + +\begin{frame}[fragile] +\frametitle{\en{String manipulation}\es{Manipulación de cadenas}} +\begin{lstlisting}[language=Python,numbers=none] +>>> print('manipulacion' + ' de ' + 'cadenas') +manipulacion de cadenas +>>> print('cadenas con %i numeros' % (4 + 6)) +cadenas con 10 numeros +\end{lstlisting} +\end{frame} + + +\section{Variables} + +\en{Python has \emph{variables} which allow results to be stored in memory so they +don't have to be recomputed all the time. They may also be updated later in the +program, which is useful when looping through code. You can think of a variable +as a named box which holds the value you put in it; you can replace the value +and it won't change or be forgotten until you replace it again.} +\es{Python tiene \emph{variables} que permiten resultados que se guarden en +la memoria para que no tiene que ser calculado de nuevo todo el tiempo. Ellos +también pueden ser actualizadas más tarde en el programa, lo cual es útil cuando +se encuentra en un bucle en el código. Ustedes pueden pensar en una variable +como una caja con nombre que contiene el valor que ustedes ponen en élla. Se +puede reemplazar el valor y no va a cambiar o será olvidado hasta que cambien de +nuevo.} + +\en{Here, we have substituted the variable \texttt{answer} for the long sum +\texttt{3 * 4 + 7 * 11 - 3}.} +\es{Aquí, hemos sustituido la variable \texttt{respuesta} a la suma largo +\texttt{3 * 4 + 7 * 11 - 3}.} + +\begin{frame}[fragile] +\frametitle{Variables} +\begin{onlyenv}<1| handout:1>\begin{lstlisting}[language=Python,numbers=none] +>>> print(3 * 4 + 7 * 11 - 3) +86 +>>> print('la respuesta es %i' % (3 * 4 + 7 * 11 - 3)) +la respuesta es 86 +\end{lstlisting}\end{onlyenv} +\begin{onlyenv}<2| handout:2>\begin{lstlisting}[language=Python,numbers=none] +>>> respuesta = 3 * 4 + 7 * 11 - 3 +>>> print(respuesta) +86 +>>> print('la respuesta es %i' % answer) +la respuesta es 86 +\end{lstlisting}\end{onlyenv} +\end{frame} + +\en{Variables are required when handling unknown values, such as data inputted by +the user using the \texttt{raw\_input()} function.} +\es{Variables son necesarios cuando se manipulan valores desconocidos, tales +como los datos del usario introducida por la función \texttt{raw\_input()}.} + +\begin{frame}[fragile] +\frametitle{Variables} +\begin{lstlisting}[language=Python,numbers=none] +>>> x = int(raw_input('Escriba un numero: ')) +Escriba un numero: 5 +>>> print('El doble del numero: %i' % (x * 2)) +El doble del numero: 10 +\end{lstlisting} +\end{frame} + + +\section{\en{Function calls}\es{Llamadas de funciones}} + +\en{Just as values can be stored in variables and used multiple times, code may +be used multiple times using \emph{functions}. A function in Python is like a +(partial) function in maths: it takes 0 or more arguments, and returns a value. +Some functions in Python do not return a value.} +\es{Al igual que los valores pueden guardar en las variables y utilizar varias +veces, el código puede ser utilizado varias veces utilizando \emph{funciones}. +Una función en Python es como una función (parcial) en matemáticas: se necesita +0 o más argumentos, y devuelve un valor. Algunas funciones en Python no +devuelven un valor.} + +\en{You can think of a function call as substituting the values passed as its +parameters into the function's code, and substituting all that for the function +call. To call a function, write the function name, followed by its parameters +in brackets, separated by commas.} +\es{Más o menos, una llamada de función sustitutos de los valores pasados como +su parámetros en el código de la función, entonces sustitutos todo lo que para +la llamada de función. Para llamar a una función, escriba el nombre de la +función, seguido de sus parámetros entre paréntesis, separados por comas.} + +\en{We will see how to define your own functions later. For now, observe that +\texttt{print()} is a function which takes 1 argument (a string to output) and +returns nothing. The examples below use the \texttt{range()} function which +takes 1 argument and returns a list of integers. An example of a function taking +multiple arguments is \texttt{max()}, which returns the maximum of the integers +it is passed.} +\es{Veremos cómo definir sus propias funciones después. Por ahora, tenga una +cuenta que \texttt{print()} es una función que toma 1 argumento (una cadena que +es la salida) y devuelve nada. Los ejemplos siguientes utilizan la función +\texttt{range()} que toma 1 argumento y devuelve una lista de enteros. Un +ejemplo de una función de tomar múltiples argumentos es \texttt{max()}, que +devuelve el máximo de los números enteros que se transmite.} + +\begin{frame}[fragile] +\frametitle{\en{Function calls}\es{Llamadas de funciones}} +\begin{lstlisting}[language=Python,numbers=none] +# Llame a la funcion range() con el parametro 5 +valor = range(5) + +# Llame a la funcion max() con 4 parametros +maximo = max(7, 3, 5, 1) + +# Llame a la funcion int() en el valor devuelto +# por la funcion raw_input() +numero = int(raw_input('Escribir un numero: ')) +\end{lstlisting} +\end{frame} + + +\section{\en{Control flow}\es{Flujo de control}} + +\en{Just as data flows around a program, between calculations and variables, control +also flows around a program, from statement to statement. There are two main +types of control flow: looping and branching. Below is an example of looping: +the statements in the \texttt{for} block are repeated 4 times. A statement is +`in' a block if it is indented by 4 spaces relative to the block statement.} +\es{Así como los flujos de datos a través de un programa, entre los cálculos y +variables, el control también fluye a través de un programa, de instrucción a +instrucción. Hay dos principales tipos de flujo de control: bucles y +condicionales. A continuación se muestra un ejemplo de un bucle: los +instrucciones en el bloque \texttt{for} se repiten 4 veces. Una instrucción es +`en' un bloque si se sangra por 4 espacios relativos a la declaración del +bloque.} + +\en{A \texttt{for} loop repeats for every element in a list in its condition. +Each element is assigned to a loop variable. In the example below, the list is +produced by \texttt{range(4)} (which we will learn more about later), and the +loop variable is \texttt{i}. So the first time the code block is executed, +\texttt{i} is equal to 0; the second time it is equal to 1, etc.} +\es{Un bucle \texttt{for} se repite para cada elemento en la lista en su +condición. Cada elemento se le asigna a una variable de bucle. En el siguiente +ejemplo, la lista es producido por \texttt{range(4)} (que vamos a aprender más +adelante), y el variable de bucle es \texttt{i}. Por lo tanto la primera vez que +el bloque de código se ejecuta, \texttt{i} es igual a 0; el segundo vez es +igual a 1, etc.} + +\begin{frame}[fragile] +\frametitle{\en{Control flow: \texttt{for} loop} + \es{Flujo de control: bucle \texttt{for}}} +\begin{lstlisting}[language=Python,numbers=none] +>>> for i in range(4): +... print(i) +... +0 +1 +2 +3 +>>> print(range(4)) +[0, 1, 2, 3] +\end{lstlisting} +\end{frame} + +\en{As well as the \texttt{for} loop, there is a \texttt{while} loop. \texttt{for} +executes its code block for each of the items in a list it's passed, assigning +the current item to the named variable for each iteration. \texttt{while} +executes its code block as many times as the loop condition is \texttt{True}.} +\es{Así como el bucle \texttt{for}, hay un bucle \texttt{while}. \texttt{for} +ejecuta su bloque de código para cada uno de los elementos de una lista que se +pasa, la asignación de el elemento actual a la variable llamada para cada +iteración. \texttt{while} ejectua su bloque de código tantas veces como la +condición del bucle es \texttt{True}.} + +\begin{frame}[fragile] +\frametitle{\en{Control flow: \texttt{while} loop} + \es{Flujo de control: bucle \texttt{while}}} +\begin{lstlisting}[language=Python,numbers=none] +>>> target = int(raw_input('Escribe un numero: ')) +Escribe un numero: 15 +>>> while target > 0: +... print(target) +... target = target / 2 +... +15 +7 +3 +1 +\end{lstlisting} +\end{frame} + +\en{One thing to consider is whether a loop will ever terminate (i.e.\ execution +will continue to the code after the loop). With \texttt{while} loops it's +possible for the loop to never terminate, as in the example below. Try to avoid +this.} +\es{Algo a considerar es si un bucle nunca terminará (es decir, la ejecución +seguirá el código después del bucle). Con bucles \texttt{while} es posible que +el bucle nunca a terminar, como en ejemplo a continuación. Trate de evitar +esto.} + +\en{\textbf{Question}: What does the code below do?} +\es{\textbf{Pregunta}: ¿Qué hace el código siguiente?} + +\begin{frame}[fragile] +\frametitle{\en{Control flow: \texttt{while} loop} + \es{Flujo de control: bucle \texttt{while}}} +\begin{lstlisting}[language=Python,numbers=none] +>>> while True: +... print('Educatrachos ') +... +\end{lstlisting} +\end{frame} + +\en{Branching executes a block of instructions only if a given condition is +\texttt{True}. If the condition is \texttt{False}, those instructions are not +executed.} +\es{La ramificación ejecutar un bloque de instrucciónes sólo si una condición +dada es \texttt{True}. Si la condición es \texttt{False}, esas instrucciones +no son ejecutado.} + +\en{This uses a new type of data, called a Boolean variable. Booleans can either be +\texttt{True} or \texttt{False}, nothing else. The other types of variable we've +encountered so far are integers and strings.} +\es{Esto utiliza un nuevo tipo de datos, llamado una variable booleana. +Booleanos pueden ser tanto \texttt{True} o \texttt{False}, nada más. Los otros +tipos de variables que hemos encontrado hasta ahora son enteros y cadenas.} + +\begin{frame}[fragile] +\frametitle{\en{Control flow: \texttt{if} statement} + \es{Flujo de control: instrucción \texttt{if}}} +\begin{lstlisting}[language=Python,numbers=none] +>>> if 1 + 2 == 3: +... print('correcto') +... +correcto +\end{lstlisting} +\end{frame} + +\en{\texttt{if} statements can have \texttt{elif} and \texttt{else} statements +appended. \texttt{elif} code blocks are executed if the conditions above them +are all \texttt{False} but the \texttt{elif} condition is \texttt{True}. +\texttt{else} code blocks are executed if all the conditions above them are +\texttt{False}.} +\es{\texttt{if} instrucciones pueden tener instrucciones \texttt{elif} y +\texttt{else} anexa. Bloques de código \texttt{elif} se ejecutan si las +condiciones anteriores a son todos \texttt{False}, pero la condición +\texttt{elif} es \texttt{True}. Bloques de código \texttt{else} se ejecutan si +todas las condiciones anteriores a son \texttt{False}.} + +\begin{frame}[fragile] +\frametitle{\en{Control flow: \texttt{if} statement} + \es{Flujo de control: instrucción \texttt{if}}} +\begin{lstlisting}[language=Python,numbers=none] +>>> if 1 == 0: +... print('incorrecto') +... elif 1 + 1 == 4: +... print('tambien incorrecto') +... else: +... print('correcto') +... +correcto +\end{lstlisting} +\end{frame} + +\en{The following example illustrates the power of variables: updating a +variable from a loop to calculate the 4th triangular number.} +\es{Esto ejemplo ilustra el poder de variables: la actualización de una variable +dentro de un bucle para calcular el número cuarto triangular.} + +\begin{frame}[fragile] +\frametitle{\en{Control flow}\es{Flujo de control}} +\begin{lstlisting}[language=Python,numbers=none] +>>> respuesta = 0 +>>> for i in range(5): +... respuesta = respuesta + i +... +>>> print(respuesta) +10 # == 0 + 0 + 1 + 2 + 3 + 4 +\end{lstlisting} +\end{frame} + +\en{Code blocks and control flow statements may be nested to form more complex +control flows.} +\es{Los bloques de código y las instrucciones de control de flujo se pueden +anidar para formir flujos de control más complejos.} + +\begin{frame}[fragile] +\frametitle{\en{Control flow}\es{Flujo de control}} +\begin{lstlisting}[language=Python,numbers=none] +>>> for i in range(6): +... if i % 2 == 0: +... print(i) +... +0 +2 +4 +\end{lstlisting} +\end{frame} + + +\section{\en{Comments}\es{Comentarios}} + +\en{When developing a program, you write the code once, and then it's read hundreds +of times by other people. Therefore, you should aim to make your code as easy +to understand as possible. Give variables descriptive names, use adequate +whitespace to separate distinct blocks of code, and add comments everywhere to +describe the purpose of each block of code.} +\es{En el desarrollo de un programa, escribir el código una vez, y luego de leer +cientos de veces por otras personas. Por lo tanto, ustedes deben tratar de hacer +que el código lo más fácil de entender como sea posible. Dar nombres +descriptivos de las variables, usar adecuado espacio en blanco para separar +distintos bloques de código, y añadir comentarios en todas partes que describe +el propósito de cada bloque de código.} + +\en{A comment is a statement in Python which is not executed by the interpreter. +It's a note from you to the people reading the code.} +\es{Un comentario es una instrucción en Python que no es ejecutando por el +intérprete. Es una nota de usted para las personas que leen el código.} + +\begin{frame}[fragile] +\frametitle{\en{Comments}\es{Comentarios}} +\begin{lstlisting}[language=Python,numbers=none] +"""Hay dos tipos de comentario. + +Comentarios de varios lineas, como este, se +utilizan para describir la gran bloques de +codigo, como las funciones y clases +(introducidas mas adelante). +Comentarios de una sola linea se utilizan +para describir bloques mas pequenos de codigo, +pero ambos tipos de comentario son +intercambiables. +""" + +# Este es un comentario de una sola linea. +\end{lstlisting} +\end{frame} + + +\section{\en{Lists and dictionaries}\es{Listas y diccionarios}} + +\en{As well as integers, strings and booleans, Python has two more data types: lists +and dictionaries. A list is just like in real life: an ordered sequence of +items. A dictionary is also similar to real life: an unordered mapping of keys +to values.} +\es{Adémas de números enteros, cadenas y booleanos, Python tiene dos más tipos +de datos: listas y diccionarios. Una lista es igual que en la vida real: una +secuencia ordenada de elementos. Un diccionario también es similar a la vida +real: un mapeo no ordenada de llaves a valores.} + +\en{The example below demonstrates constructing a list of three items and accessing +the 1st and 2nd items in the list. Note that, like other programming languages, +ordinal numbering starts from 0.} +\es{El siguiente ejemplo demuestra la construcción de una lista de tres +elementos y el acceso a los primero y segundo elementos de la lista. Tenga un +cuenta que, al igual que otros lenguajes de programación, numeración ordinal +comienza desde 0.} + +\begin{frame}[fragile] +\frametitle{\en{Lists}\es{Listas}} +\begin{lstlisting}[language=Python,numbers=none] +>>> lista = [10, 20, 30] +>>> print(lista[0]) +10 +>>> print(lista[1]) +20 +\end{lstlisting} +\end{frame} + +\en{Lists can be appended to, tested to see if an item is in them, and have items +removed from them. Many operations on lists are achieved using \emph{method +calls} on the list, signified by a dot and then the method name +(e.g.\ \texttt{.append}). We'll see more about methods later.} +\es{Las listas pueden ser anexados, prueban para ver si un elemento está en +ellos, y tienen elementos retirado de ellos. Muchas de las operaciones en las +listas utilizan métodos en la lista, representada por un punto y luego el nombre +del método (por ejemplo, \texttt{.append}). Veremos más sobre los métodos más +adelanta.} + +\en{Note that the \texttt{range()} function produces a list.} +\es{Tenga en cuenta que la función \texttt{range()} produce una lista.} + +\begin{frame}[fragile] +\frametitle{\en{Lists}\es{Listas}} +\begin{lstlisting}[language=Python,numbers=none] +>>> lista = range(5) +>>> print(lista) +[0, 1, 2, 3, 4] +>>> lista.append(5) +>>> print(lista) +[0, 1, 2, 3, 4, 5] +>>> lista.remove(3) +>>> print(lista) +[0, 1, 2, 4, 5] +>>> if 2 in lista: +... print('La lista contiene 2') +... +La lista contiene 2 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{\en{Dictionaries}\es{Diccionarios}} +\begin{lstlisting}[language=Python,numbers=none] +>>> dict = {'llave': 'valor', 'otra-llave': 4} +>>> print(dict['llave']) +value +>>> dict['nueva-llave'] = 'otro-valor' +>>> print(dict['nueva-llave']) +otro-valor +>>> del dict['llave'] +>>> print('llave' in dict) +False +\end{lstlisting} +\end{frame} + + +\en{When programming, an API reference (documentation of all the available +pre-written functions) is vital. The functions in Python are +well documented and the documentation is easy to read. There are two references: +one for the functions in Python, and one for the language syntax itself.} +\es{En la programación, una referencia de la API (documentación de todas las +funciones de pre-escritos disponibles) es vital. Las funciones en +Python son bien documentados y la documentación es fácil de leer. Hay dos +referencias: uno para las funciones en Python, y uno para la sintaxis del +lenguaje en sí mismo.} + +\begin{frame}{\en{API references}\es{Referencias de la API}} +\begin{itemize} + \item{\url{http://docs.python.org/2.7/library/index.html}} + \item{\url{http://docs.python.org/2.7/reference/index.html}} +\end{itemize} +\end{frame} + + +\en{At this point it's suggested that you experiment with what you have learnt so +far by completing some exercises. Each exercise is in a separate \texttt{.py} +(Python) file, and its solution is in a second file. Edit the first file using +a text editor and test your code by running it non-interactively as explained +below. Ask me any questions you have!} +\es{En este punto se sugiere que ustedes experimentan con lo que han aprendido +ahora por completar algunos ejercicios. Cada ejercicio está en una única +archivo \texttt{.py}, y su solución se encuentra en un segundo archivo. Edite el +primer archivo utilizando un editor de texto (como `gedit') y probar su código +ejecutándolo de forma no interactiva, como se explica a continuación. ¡Pídeme +cualquier pregunta que tenga!} + +\begin{frame}[fragile] +\frametitle{\en{Running Python files}\es{Ejecutando archivos de Python}} +\begin{itemize} + \item{\en{Write your code in a \texttt{.py} file.} + \es{Escribir el código en un archivo \texttt{.py}.}} + \item{\en{Put the following on the first two lines:} + \es{Poner lo siguiente en las dos primeras líneas del archivo:} + \begin{lstlisting}[language=Python,numbers=none] +#!/usr/bin/python +# coding=utf-8 + \end{lstlisting}} + \item{\en{From a terminal, run \texttt{python my-file.py}.} + \es{Desde un terminal, ejecute \texttt{python my-file.py}.}} +\end{itemize} +\end{frame} + + +\begin{frame}<presentation>{\en{Questions?}\es{¿Preguntas?}} +\en{Any questions so far?} +\es{¿Hay preguntas hasta ahora?} + +\begin{itemize} + \item{\url{http://docs.python.org.ar/tutorial/2/}} + \item{\url{http://pythonmonk.com/}} + \item{\url{http://docs.python.org/2.7/library/index.html}} + \item{\url{http://docs.python.org/2.7/reference/index.html}} +\end{itemize} +\end{frame} diff --git a/python-functions-and-classes.tex b/python-functions-and-classes.tex new file mode 100644 index 0000000..062ce97 --- /dev/null +++ b/python-functions-and-classes.tex @@ -0,0 +1,273 @@ +\section{\en{Functions}\es{Funciones}} + +\en{We've already seen how to call existing functions; now we'll see how to +define new ones. As with loops and conditionals, a function is a block of code +which is indented by 4 spaces relative to the name of the function, which is +itself preceded by \texttt{def} and followed by a list of parameter names. These +parameter names become variables in your function's code, with values provided +by the caller of the function.} +\es{TODO} + +\begin{frame}[fragile] +\frametitle{\en{Functions}\es{Funciones}} +\begin{lstlisting}[language=Python] +def funcion_sin_parametros(): + print('Este funcion no tiene parametros') + +def funcion_con_parametros(para1, para2): + print('Este funcion tiene parametros: %s y %s' % (para1, para2)) + +# Llame a los funciones. +funcion_sin_parametros() +funcion_con_parametros('hola', 'mundo') +\end{lstlisting} +\end{frame} + +\en{In the previous example, neither function returned a value. To do this, use +the \texttt{return} statement. As soon as this statement is executed, control +will return to the code which called the function --- so code after the +\texttt{return} statement will not be executed. The following example +demonstrates a function which returns the minimum of its two parameters.} +\es{TODO} + +\begin{frame}[fragile] +\frametitle{\en{Functions}\es{Funciones}} +\begin{lstlisting}[language=Python] +def min(numero_a, numero_b): + if numero_a > numero_b: + return numero_b + else: + return numero_a + +minimo = min(5, 7) +print('El numero mas pequeno es %i' % minimo) +\end{lstlisting} +\end{frame} + +\en{You can think of this as substituting the parameters from the function call +into the function's code, and then substituting that for the return value of the +function call.} +\es{TODO} + +\begin{frame}[fragile] +\frametitle{\en{Functions}\es{Funciones}} +\begin{lstlisting}[language=Python] +minimo = ( + if 5 > 7: + return 7 + else: + return 5 +) +print('El numero mas pequeno es %i' % minimo) +\end{lstlisting} +\end{frame} + + +\section{\en{Imports}\es{Importaciónes}} + +\en{Python provides a large number of existing functions, with related functions +grouped together in \emph{modules}. To speed up loading of programs, only the +functions from modules which your program explicitly \emph{imports} are +available to call.} +\es{TODO} + +\en{To import a module, use the \texttt{import} statement at the top of your +Python file. Common modules which you might want to import are:} +\es{TODO} +\begin{description} + \item[\texttt{os}] + {\en{Functions for interfacing with the operating system.} + \es{TODO}} + \item[\texttt{sys}] + {\en{Functions for interfacing with the Python interpreter.} + \es{TODO}} + \item[\texttt{math}] + {\en{Mathematical functions more advanced than simple arithmetic.} + \es{TODO}} + \item[\texttt{gi.repository.Gtk}] + {\en{Graphical user interface classes and functions from GTK+.} + \es{TODO}} +\end{description} + +\begin{frame}[fragile] +\frametitle{\en{Imports}\es{Importaciónes}} +\begin{lstlisting}[language=Python]] +#!/usr/bin/python +# coding=utf-8 + +import os +import math +from gi.repository import Gtk +from sys import argv +\end{lstlisting} +\end{frame} + +\en{Python modules can be arranged in hierarchies, with the modules named after +the files and directories which contain the code. For example, +\texttt{repository} is a sub-module of \texttt{gi}. When referencing a class +or method in code, you can include the name of the sub-module containing it if +that sub-module hasn't been imported already (but its parent module has).} +\es{TODO} + + +\section{\en{Classes}\es{Clases}} + +\en{A \emph{class} is a collection of functions and variables which can be +instantiated multiple times. Each instance of a class is an \emph{object} and +its variables are separate from those of other instances of the same class.} +\es{TODO} + +\en{Why collect functions and variables together? It makes maintaining a large +program a lot easier by separating code and data out into different components +which don't interfere with each other.} +\es{TODO} + +\en{To define a class in Python, use the \texttt{class} statement, followed by +the class name, then the name of its parent class in brackets. All code inside +the class must be indented by 4 spaces. Parent classes allow for inheritance, +which is covered shortly.} +\es{TODO} + +\en{In this example, the \texttt{Vehiculo} class has two instance variables +(\texttt{matricula} and \texttt{numero\_de\_ruedas}) and three methods +(\texttt{\_\_init\_\_}, \texttt{calcular\_impuesto} and +\texttt{dar\_matricula}). All of the methods can access the values of the +instance variables, which can be unique for each instance of the class.} +\es{TODO} + +\en{The \texttt{\_\_init\_\_} method is special: it's the \emph{constructor} +for the class. It is called when an instance of the class is created, as shown +next.} +\es{TODO} + +\begin{frame}[fragile] +\frametitle{\en{Defining classes}\es{Definición de clases}} +\begin{lstlisting}[language=Python] +class Vehiculo(object): + def __init__(self, matricula, numero_de_ruedas): + self._matricula = matricula + self._numero_de_ruedas = numero_de_ruedas + + # Asumir vehiculos estan gravados por el numero de ruedas + def calcular_impuesto(self): + return 100 * self._numero_de_ruedas + + def dar_matricula(self): + return self._matricula +\end{lstlisting} + % TODO: syntax; constructors as special methods; inheritance; properties (definition) + % TODO: class as bundle of functions and variables; instantiating a class; getting/setting a property; calling a method from outside and inside a class instance +\end{frame} + +\en{Instantiating a class is similar to calling a function; you're effectively +calling the \texttt{\_\_init\_\_} function, and can pass it parameters as +normal. Once you've instantiated a class, you can call its methods using a +dot --- just like calling \texttt{append()} on a list. All lists are actually +instances of a \texttt{list} class.} +\es{TODO} + +\begin{frame}[fragile] +\frametitle{\en{Using classes}\es{Utilización de clases}} +\begin{lstlisting}[language=Python] +mi_coche = Vehiculo('AB99BA', 4) +mi_moto = Vehiculo('CB21TA', 2) + +print(mi_coche.calcular_impuesto()) # da 400 +print(mi_coche.dar_matricula()) # da 'AB99BA' +print(mi_moto.calcular_impuesto()) # da 200 +\end{lstlisting} +\end{frame} + +\en{Inheritance is a major feature of classes. A class can specify a parent +class which it \emph{inherits} methods from. This means that, in the example +here, instances of the \texttt{Coche} class (which inherits from +\texttt{Vehiculo}) have \texttt{calcular\_impuesto()} and +\texttt{dar\_matricula()} methods. At the bottom of the inheritance tree is +\texttt{object}.} +\es{TODO} + +\en{A child class can override one of its parent class' methods by defining +its own method of the same name. This is commonly done with the +\texttt{\_\_init\_\_} method, as here. The new code in the child class' method +can call the old code in the parent class by using \texttt{super()}.} +\es{TODO} + +\begin{frame}[fragile] +\frametitle{\en{Defining classes}\es{Definición de clases}} +\begin{lstlisting}[language=Python] +class Coche(Vehiculo): + def __init__(self, matricula, peso): + # Todos los coches tienen 4 ruedas + super(Coche, self).__init__(matricula, 4) + self._peso = peso + + def calcular_presion(self): + return self._peso / 4 + +class Moto(Vehiculo): + def __init__(self, matricula): + # Todos los motos tienen 2 ruedas + super(Moto, self).__init__(matricula, 2) + +mi_coche = Coche('AB99BA', 1500) +mi_moto = Moto('CB21TA') + +print(mi_coche.calcular_impuesto()) # da 400 +print(mi_coche.dar_matricula()) # da 'AB99BA' +print(mi_moto.calcular_impuesto()) # da 200 +\end{lstlisting} +\end{frame} + + +\subsection{\en{Private methods}\es{TODO}} + +\en{What if you want to define a method in your class but don't want it to be +callable from outside the class? For example, a method which performs part of a +larger calculation. The convention in Python is to prefix the method name with +a double-underscore, which hides it from code outside the class. The method is +then called a \emph{private method}. The same is true for variables, although +a single-underscore is commonly used for them.} +\es{TODO} + +\begin{frame}[fragile] +\frametitle{\en{Private methods}\es{TODO}} +\begin{lstlisting}[language=Python] +class Coche(Vehiculo): + TODO +\end{lstlisting} +\end{frame} + + +\section{\en{Documentation}\es{Documentación}} + +\en{As mentioned before, commenting a program is vital. Python encourages this +by making class and method documentation available when running a program, if +the documentation is written in ``docstring'' format. Documentation in this +format must be written as a single string as the first line of the class or +method being documented.} +\es{TODO} + +\begin{frame}[fragile] +\frametitle{\en{Documentation}\es{Documentación}} +\begin{lstlisting}[language=Python] +class Vehiculo(object): + """TODO""" + def my_method(self, foo): + """TODO""" + return 15 +\end{lstlisting} +\end{frame} + +\en{You can access documentation from the Python interpreter by accessing the +\texttt{\_\_doc\_\_} member variable of the class or method. + +\begin{frame}[fragile] +\frametitle{\en{Documentation}\es{Documentación}} +\begin{lstlisting}[language=Python] +print(Vehiculo.__doc__) +print(range.__doc__) +\end{lstlisting} +\end{frame} + + +% TODO: git, licensing, basic GTK+ usage, code formatting/peps @@ -191,807 +191,15 @@ Windows.} \part{\en{Introduction to Python}\es{Introducción a Python}} -\section{\en{Interpreter}\es{Intérprete}} - -\en{You can run Python interactively, and enter programs which will be executed -line-by-line. This is not the best way to write a program, but is good for -experiments. Each instruction is also called a statement.} -\es{Es posible que ejecutar Python interactivamente y escribir programas que se -ejecutan línea a línea. Esta no es la mejor manera de escribir un programa, pero -es bueno para la experimentación.} - -\en{As with all programming languages, you write a program as a sequence of -instructions. The computer will execute them exactly as you write them, in -order, so if you write incorrect instructions your program will not function -correctly.} -\es{Al igual que con todos los lenguajes de programación, se escribe una -programa como una secuencia de instrucciones. El ordenador ejecutará -exactamente como usted los escribe, en orden, así que si usted escribe -instrucciones incorrectas su programa no funcionará correctamente.} - -\en{When it starts, the Python interpreter displays a \texttt{>{}>{}>} prompt, -indicating that it's waiting for an instruction to be inputted. Input to the -interpreter is always on lines prefixed by \texttt{>{}>{}>} or \texttt{...}, -whereas output from the interpreter isn't prefixed.} -\es{Cuando se inicia, el intérprete de Python muestra un aviso \texttt{>{}>{}>}, -lo que indica que está esperando una instrucción para ser introducida. De -entrada a la intérprete está siempre en líneas prefijadas por \texttt{>{}>{}>} o -\texttt{...}, mientras que la salida del intérprete no se prefija.} - -\begin{frame}[fragile] -\frametitle{\en{Interpreter}\es{Intérprete}} -\begin{lstlisting}[numbers=none] -$ python -Python 2.7.5 (default, Jul 8 2013, 09:48:44) -[GCC 4.8.1 20130603 (Red Hat 4.8.1)] on linux2 -Type "help", "copyright" "credits" or "license" -for more information. -\end{lstlisting} -\begin{lstlisting}[language=Python,numbers=none] ->>> print(4 + 5) -9 -\end{lstlisting} -\end{frame} - -\en{As well as arithmetic, you can manipulate strings. Strings are sequences of -characters, and the main operations on them are concatenation (joining two -strings together) and formatting (replacing placeholders in a string with other -values, such as numbers or other strings).} -\es{Así como la aritmética, se puede manipular cadenas. Cadenas son secuencias -de caracteres y las principales operaciones en ellos son concatenación (la unión -de dos cadenas) y formato (reemplazar los marcadores de posición en una cadena -con otros valores, tales como números u otras cadenas).} - -\en{In the following example, a pair of brackets surround the sum. Just as in -arithmetic, brackets in programming are used to order operations.} -\es{En el ejemplo siguiente, un par de soportes rodean la suma. Tal como en -la aritmética, los paréntesis se utilizan en la programación de operaciones para -ponen en orden.} - -\begin{frame}[fragile] -\frametitle{\en{String manipulation}\es{Manipulación de cadenas}} -\begin{lstlisting}[language=Python,numbers=none] ->>> print('manipulacion' + ' de ' + 'cadenas') -manipulacion de cadenas ->>> print('cadenas con %i numeros' % (4 + 6)) -cadenas con 10 numeros -\end{lstlisting} -\end{frame} - - -\section{Variables} - -\en{Python has \emph{variables} which allow results to be stored in memory so they -don't have to be recomputed all the time. They may also be updated later in the -program, which is useful when looping through code. You can think of a variable -as a named box which holds the value you put in it; you can replace the value -and it won't change or be forgotten until you replace it again.} -\es{Python tiene \emph{variables} que permiten resultados que se guarden en -la memoria para que no tiene que ser calculado de nuevo todo el tiempo. Ellos -también pueden ser actualizadas más tarde en el programa, lo cual es útil cuando -se encuentra en un bucle en el código. Ustedes pueden pensar en una variable -como una caja con nombre que contiene el valor que ustedes ponen en élla. Se -puede reemplazar el valor y no va a cambiar o será olvidado hasta que cambien de -nuevo.} - -\en{Here, we have substituted the variable \texttt{answer} for the long sum -\texttt{3 * 4 + 7 * 11 - 3}.} -\es{Aquí, hemos sustituido la variable \texttt{respuesta} a la suma largo -\texttt{3 * 4 + 7 * 11 - 3}.} - -\begin{frame}[fragile] -\frametitle{Variables} -\begin{onlyenv}<1| handout:1>\begin{lstlisting}[language=Python,numbers=none] ->>> print(3 * 4 + 7 * 11 - 3) -86 ->>> print('la respuesta es %i' % (3 * 4 + 7 * 11 - 3)) -la respuesta es 86 -\end{lstlisting}\end{onlyenv} -\begin{onlyenv}<2| handout:2>\begin{lstlisting}[language=Python,numbers=none] ->>> respuesta = 3 * 4 + 7 * 11 - 3 ->>> print(respuesta) -86 ->>> print('la respuesta es %i' % answer) -la respuesta es 86 -\end{lstlisting}\end{onlyenv} -\end{frame} - -\en{Variables are required when handling unknown values, such as data inputted by -the user using the \texttt{raw\_input()} function.} -\es{Variables son necesarios cuando se manipulan valores desconocidos, tales -como los datos del usario introducida por la función \texttt{raw\_input()}.} - -\begin{frame}[fragile] -\frametitle{Variables} -\begin{lstlisting}[language=Python,numbers=none] ->>> x = int(raw_input('Escriba un numero: ')) -Escriba un numero: 5 ->>> print('El doble del numero: %i' % (x * 2)) -El doble del numero: 10 -\end{lstlisting} -\end{frame} - - -\section{\en{Function calls}\es{Llamadas de funciones}} - -\en{Just as values can be stored in variables and used multiple times, code may -be used multiple times using \emph{functions}. A function in Python is like a -(partial) function in maths: it takes 0 or more arguments, and returns a value. -Some functions in Python do not return a value.} -\es{Al igual que los valores pueden guardar en las variables y utilizar varias -veces, el código puede ser utilizado varias veces utilizando \emph{funciones}. -Una función en Python es como una función (parcial) en matemáticas: se necesita -0 o más argumentos, y devuelve un valor. Algunas funciones en Python no -devuelven un valor.} - -\en{You can think of a function call as substituting the values passed as its -parameters into the function's code, and substituting all that for the function -call. To call a function, write the function name, followed by its parameters -in brackets, separated by commas.} -\es{Más o menos, una llamada de función sustitutos de los valores pasados como -su parámetros en el código de la función, entonces sustitutos todo lo que para -la llamada de función. Para llamar a una función, escriba el nombre de la -función, seguido de sus parámetros entre paréntesis, separados por comas.} - -\en{We will see how to define your own functions later. For now, observe that -\texttt{print()} is a function which takes 1 argument (a string to output) and -returns nothing. The examples below use the \texttt{range()} function which -takes 1 argument and returns a list of integers. An example of a function taking -multiple arguments is \texttt{max()}, which returns the maximum of the integers -it is passed.} -\es{Veremos cómo definir sus propias funciones después. Por ahora, tenga una -cuenta que \texttt{print()} es una función que toma 1 argumento (una cadena que -es la salida) y devuelve nada. Los ejemplos siguientes utilizan la función -\texttt{range()} que toma 1 argumento y devuelve una lista de enteros. Un -ejemplo de una función de tomar múltiples argumentos es \texttt{max()}, que -devuelve el máximo de los números enteros que se transmite.} - -\begin{frame}[fragile] -\frametitle{\en{Function calls}\es{Llamadas de funciones}} -\begin{lstlisting}[language=Python,numbers=none] -# Llame a la funcion range() con el parametro 5 -valor = range(5) - -# Llame a la funcion max() con 4 parametros -maximo = max(7, 3, 5, 1) - -# Llame a la funcion int() en el valor devuelto -# por la funcion raw_input() -numero = int(raw_input('Escribir un numero: ')) -\end{lstlisting} -\end{frame} - - -\section{\en{Control flow}\es{Flujo de control}} - -\en{Just as data flows around a program, between calculations and variables, control -also flows around a program, from statement to statement. There are two main -types of control flow: looping and branching. Below is an example of looping: -the statements in the \texttt{for} block are repeated 4 times. A statement is -`in' a block if it is indented by 4 spaces relative to the block statement.} -\es{Así como los flujos de datos a través de un programa, entre los cálculos y -variables, el control también fluye a través de un programa, de instrucción a -instrucción. Hay dos principales tipos de flujo de control: bucles y -condicionales. A continuación se muestra un ejemplo de un bucle: los -instrucciones en el bloque \texttt{for} se repiten 4 veces. Una instrucción es -`en' un bloque si se sangra por 4 espacios relativos a la declaración del -bloque.} - -\en{A \texttt{for} loop repeats for every element in a list in its condition. -Each element is assigned to a loop variable. In the example below, the list is -produced by \texttt{range(4)} (which we will learn more about later), and the -loop variable is \texttt{i}. So the first time the code block is executed, -\texttt{i} is equal to 0; the second time it is equal to 1, etc.} -\es{Un bucle \texttt{for} se repite para cada elemento en la lista en su -condición. Cada elemento se le asigna a una variable de bucle. En el siguiente -ejemplo, la lista es producido por \texttt{range(4)} (que vamos a aprender más -adelante), y el variable de bucle es \texttt{i}. Por lo tanto la primera vez que -el bloque de código se ejecuta, \texttt{i} es igual a 0; el segundo vez es -igual a 1, etc.} - -\begin{frame}[fragile] -\frametitle{\en{Control flow: \texttt{for} loop} - \es{Flujo de control: bucle \texttt{for}}} -\begin{lstlisting}[language=Python,numbers=none] ->>> for i in range(4): -... print(i) -... -0 -1 -2 -3 ->>> print(range(4)) -[0, 1, 2, 3] -\end{lstlisting} -\end{frame} - -\en{As well as the \texttt{for} loop, there is a \texttt{while} loop. \texttt{for} -executes its code block for each of the items in a list it's passed, assigning -the current item to the named variable for each iteration. \texttt{while} -executes its code block as many times as the loop condition is \texttt{True}.} -\es{Así como el bucle \texttt{for}, hay un bucle \texttt{while}. \texttt{for} -ejecuta su bloque de código para cada uno de los elementos de una lista que se -pasa, la asignación de el elemento actual a la variable llamada para cada -iteración. \texttt{while} ejectua su bloque de código tantas veces como la -condición del bucle es \texttt{True}.} - -\begin{frame}[fragile] -\frametitle{\en{Control flow: \texttt{while} loop} - \es{Flujo de control: bucle \texttt{while}}} -\begin{lstlisting}[language=Python,numbers=none] ->>> target = int(raw_input('Escribe un numero: ')) -Escribe un numero: 15 ->>> while target > 0: -... print(target) -... target = target / 2 -... -15 -7 -3 -1 -\end{lstlisting} -\end{frame} - -\en{One thing to consider is whether a loop will ever terminate (i.e.\ execution -will continue to the code after the loop). With \texttt{while} loops it's -possible for the loop to never terminate, as in the example below. Try to avoid -this.} -\es{Algo a considerar es si un bucle nunca terminará (es decir, la ejecución -seguirá el código después del bucle). Con bucles \texttt{while} es posible que -el bucle nunca a terminar, como en ejemplo a continuación. Trate de evitar -esto.} - -\en{\textbf{Question}: What does the code below do?} -\es{\textbf{Pregunta}: ¿Qué hace el código siguiente?} - -\begin{frame}[fragile] -\frametitle{\en{Control flow: \texttt{while} loop} - \es{Flujo de control: bucle \texttt{while}}} -\begin{lstlisting}[language=Python,numbers=none] ->>> while True: -... print('Educatrachos ') -... -\end{lstlisting} -\end{frame} - -\en{Branching executes a block of instructions only if a given condition is -\texttt{True}. If the condition is \texttt{False}, those instructions are not -executed.} -\es{La ramificación ejecutar un bloque de instrucciónes sólo si una condición -dada es \texttt{True}. Si la condición es \texttt{False}, esas instrucciones -no son ejecutado.} - -\en{This uses a new type of data, called a Boolean variable. Booleans can either be -\texttt{True} or \texttt{False}, nothing else. The other types of variable we've -encountered so far are integers and strings.} -\es{Esto utiliza un nuevo tipo de datos, llamado una variable booleana. -Booleanos pueden ser tanto \texttt{True} o \texttt{False}, nada más. Los otros -tipos de variables que hemos encontrado hasta ahora son enteros y cadenas.} - -\begin{frame}[fragile] -\frametitle{\en{Control flow: \texttt{if} statement} - \es{Flujo de control: instrucción \texttt{if}}} -\begin{lstlisting}[language=Python,numbers=none] ->>> if 1 + 2 == 3: -... print('correcto') -... -correcto -\end{lstlisting} -\end{frame} - -\en{\texttt{if} statements can have \texttt{elif} and \texttt{else} statements -appended. \texttt{elif} code blocks are executed if the conditions above them -are all \texttt{False} but the \texttt{elif} condition is \texttt{True}. -\texttt{else} code blocks are executed if all the conditions above them are -\texttt{False}.} -\es{\texttt{if} instrucciones pueden tener instrucciones \texttt{elif} y -\texttt{else} anexa. Bloques de código \texttt{elif} se ejecutan si las -condiciones anteriores a son todos \texttt{False}, pero la condición -\texttt{elif} es \texttt{True}. Bloques de código \texttt{else} se ejecutan si -todas las condiciones anteriores a son \texttt{False}.} - -\begin{frame}[fragile] -\frametitle{\en{Control flow: \texttt{if} statement} - \es{Flujo de control: instrucción \texttt{if}}} -\begin{lstlisting}[language=Python,numbers=none] ->>> if 1 == 0: -... print('incorrecto') -... elif 1 + 1 == 4: -... print('tambien incorrecto') -... else: -... print('correcto') -... -correcto -\end{lstlisting} -\end{frame} - -\en{The following example illustrates the power of variables: updating a -variable from a loop to calculate the 4th triangular number.} -\es{Esto ejemplo ilustra el poder de variables: la actualización de una variable -dentro de un bucle para calcular el número cuarto triangular.} - -\begin{frame}[fragile] -\frametitle{\en{Control flow}\es{Flujo de control}} -\begin{lstlisting}[language=Python,numbers=none] ->>> respuesta = 0 ->>> for i in range(5): -... respuesta = respuesta + i -... ->>> print(respuesta) -10 # == 0 + 0 + 1 + 2 + 3 + 4 -\end{lstlisting} -\end{frame} - -\en{Code blocks and control flow statements may be nested to form more complex -control flows.} -\es{Los bloques de código y las instrucciones de control de flujo se pueden -anidar para formir flujos de control más complejos.} - -\begin{frame}[fragile] -\frametitle{\en{Control flow}\es{Flujo de control}} -\begin{lstlisting}[language=Python,numbers=none] ->>> for i in range(6): -... if i % 2 == 0: -... print(i) -... -0 -2 -4 -\end{lstlisting} -\end{frame} - - -\section{\en{Comments}\es{Comentarios}} - -\en{When developing a program, you write the code once, and then it's read hundreds -of times by other people. Therefore, you should aim to make your code as easy -to understand as possible. Give variables descriptive names, use adequate -whitespace to separate distinct blocks of code, and add comments everywhere to -describe the purpose of each block of code.} -\es{En el desarrollo de un programa, escribir el código una vez, y luego de leer -cientos de veces por otras personas. Por lo tanto, ustedes deben tratar de hacer -que el código lo más fácil de entender como sea posible. Dar nombres -descriptivos de las variables, usar adecuado espacio en blanco para separar -distintos bloques de código, y añadir comentarios en todas partes que describe -el propósito de cada bloque de código.} - -\en{A comment is a statement in Python which is not executed by the interpreter. -It's a note from you to the people reading the code.} -\es{Un comentario es una instrucción en Python que no es ejecutando por el -intérprete. Es una nota de usted para las personas que leen el código.} - -\begin{frame}[fragile] -\frametitle{\en{Comments}\es{Comentarios}} -\begin{lstlisting}[language=Python,numbers=none] -"""Hay dos tipos de comentario. - -Comentarios de varios lineas, como este, se -utilizan para describir la gran bloques de -codigo, como las funciones y clases -(introducidas mas adelante). -Comentarios de una sola linea se utilizan -para describir bloques mas pequenos de codigo, -pero ambos tipos de comentario son -intercambiables. -""" - -# Este es un comentario de una sola linea. -\end{lstlisting} -\end{frame} - - -\section{\en{Lists and dictionaries}\es{Listas y diccionarios}} - -\en{As well as integers, strings and booleans, Python has two more data types: lists -and dictionaries. A list is just like in real life: an ordered sequence of -items. A dictionary is also similar to real life: an unordered mapping of keys -to values.} -\es{Adémas de números enteros, cadenas y booleanos, Python tiene dos más tipos -de datos: listas y diccionarios. Una lista es igual que en la vida real: una -secuencia ordenada de elementos. Un diccionario también es similar a la vida -real: un mapeo no ordenada de llaves a valores.} - -\en{The example below demonstrates constructing a list of three items and accessing -the 1st and 2nd items in the list. Note that, like other programming languages, -ordinal numbering starts from 0.} -\es{El siguiente ejemplo demuestra la construcción de una lista de tres -elementos y el acceso a los primero y segundo elementos de la lista. Tenga un -cuenta que, al igual que otros lenguajes de programación, numeración ordinal -comienza desde 0.} - -\begin{frame}[fragile] -\frametitle{\en{Lists}\es{Listas}} -\begin{lstlisting}[language=Python,numbers=none] ->>> lista = [10, 20, 30] ->>> print(lista[0]) -10 ->>> print(lista[1]) -20 -\end{lstlisting} -\end{frame} - -\en{Lists can be appended to, tested to see if an item is in them, and have items -removed from them. Many operations on lists are achieved using \emph{method -calls} on the list, signified by a dot and then the method name -(e.g.\ \texttt{.append}). We'll see more about methods later.} -\es{Las listas pueden ser anexados, prueban para ver si un elemento está en -ellos, y tienen elementos retirado de ellos. Muchas de las operaciones en las -listas utilizan métodos en la lista, representada por un punto y luego el nombre -del método (por ejemplo, \texttt{.append}). Veremos más sobre los métodos más -adelanta.} - -\en{Note that the \texttt{range()} function produces a list.} -\es{Tenga en cuenta que la función \texttt{range()} produce una lista.} - -\begin{frame}[fragile] -\frametitle{\en{Lists}\es{Listas}} -\begin{lstlisting}[language=Python,numbers=none] ->>> lista = range(5) ->>> print(lista) -[0, 1, 2, 3, 4] ->>> lista.append(5) ->>> print(lista) -[0, 1, 2, 3, 4, 5] ->>> lista.remove(3) ->>> print(lista) -[0, 1, 2, 4, 5] ->>> if 2 in lista: -... print('La lista contiene 2') -... -La lista contiene 2 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] -\frametitle{\en{Dictionaries}\es{Diccionarios}} -\begin{lstlisting}[language=Python,numbers=none] ->>> dict = {'llave': 'valor', 'otra-llave': 4} ->>> print(dict['llave']) -value ->>> dict['nueva-llave'] = 'otro-valor' ->>> print(dict['nueva-llave']) -otro-valor ->>> del dict['llave'] ->>> print('llave' in dict) -False -\end{lstlisting} -\end{frame} - - -\en{When programming, an API reference (documentation of all the available -pre-written functions) is vital. The functions in Python are -well documented and the documentation is easy to read. There are two references: -one for the functions in Python, and one for the language syntax itself.} -\es{En la programación, una referencia de la API (documentación de todas las -funciones de pre-escritos disponibles) es vital. Las funciones en -Python son bien documentados y la documentación es fácil de leer. Hay dos -referencias: uno para las funciones en Python, y uno para la sintaxis del -lenguaje en sí mismo.} - -\begin{frame}{\en{API references}\es{Referencias de la API}} -\begin{itemize} - \item{\url{http://docs.python.org/2.7/library/index.html}} - \item{\url{http://docs.python.org/2.7/reference/index.html}} -\end{itemize} -\end{frame} - - -\en{At this point it's suggested that you experiment with what you have learnt so -far by completing some exercises. Each exercise is in a separate \texttt{.py} -(Python) file, and its solution is in a second file. Edit the first file using -a text editor and test your code by running it non-interactively as explained -below. Ask me any questions you have!} -\es{En este punto se sugiere que ustedes experimentan con lo que han aprendido -ahora por completar algunos ejercicios. Cada ejercicio está en una única -archivo \texttt{.py}, y su solución se encuentra en un segundo archivo. Edite el -primer archivo utilizando un editor de texto (como `gedit') y probar su código -ejecutándolo de forma no interactiva, como se explica a continuación. ¡Pídeme -cualquier pregunta que tenga!} - -\begin{frame}[fragile] -\frametitle{\en{Running Python files}\es{Ejecutando archivos de Python}} -\begin{itemize} - \item{\en{Write your code in a \texttt{.py} file.} - \es{Escribir el código en un archivo \texttt{.py}.}} - \item{\en{Put the following on the first two lines:} - \es{Poner lo siguiente en las dos primeras líneas del archivo:} - \begin{lstlisting}[language=Python,numbers=none] -#!/usr/bin/python -# coding=utf-8 - \end{lstlisting}} - \item{\en{From a terminal, run \texttt{python my-file.py}.} - \es{Desde un terminal, ejecute \texttt{python my-file.py}.}} -\end{itemize} -\end{frame} - - -\begin{frame}<presentation>{\en{Questions?}\es{¿Preguntas?}} -\en{Any questions so far?} -\es{¿Hay preguntas hasta ahora?} - -\begin{itemize} - \item{\url{http://docs.python.org.ar/tutorial/2/}} - \item{\url{http://pythonmonk.com/}} - \item{\url{http://docs.python.org/2.7/library/index.html}} - \item{\url{http://docs.python.org/2.7/reference/index.html}} -\end{itemize} -\end{frame} +\input{introduction-to-python} \part{\en{Python functions and classes}\es{Funciones y clases en Python}} -\section{\en{Functions}\es{Funciones}} - -\en{We've already seen how to call existing functions; now we'll see how to -define new ones. As with loops and conditionals, a function is a block of code -which is indented by 4 spaces relative to the name of the function, which is -itself preceded by \texttt{def} and followed by a list of parameter names. These -parameter names become variables in your function's code, with values provided -by the caller of the function.} -\es{TODO} - -\begin{frame}[fragile] -\frametitle{\en{Functions}\es{Funciones}} -\begin{lstlisting}[language=Python] -def funcion_sin_parametros(): - print('Este funcion no tiene parametros') - -def funcion_con_parametros(para1, para2): - print('Este funcion tiene parametros: %s y %s' % (para1, para2)) - -# Llame a los funciones. -funcion_sin_parametros() -funcion_con_parametros('hola', 'mundo') -\end{lstlisting} -\end{frame} - -\en{In the previous example, neither function returned a value. To do this, use -the \texttt{return} statement. As soon as this statement is executed, control -will return to the code which called the function --- so code after the -\texttt{return} statement will not be executed. The following example -demonstrates a function which returns the minimum of its two parameters.} -\es{TODO} - -\begin{frame}[fragile] -\frametitle{\en{Functions}\es{Funciones}} -\begin{lstlisting}[language=Python] -def min(numero_a, numero_b): - if numero_a > numero_b: - return numero_b - else: - return numero_a - -minimo = min(5, 7) -print('El numero mas pequeno es %i' % minimo) -\end{lstlisting} -\end{frame} - -\en{You can think of this as substituting the parameters from the function call -into the function's code, and then substituting that for the return value of the -function call.} -\es{TODO} - -\begin{frame}[fragile] -\frametitle{\en{Functions}\es{Funciones}} -\begin{lstlisting}[language=Python] -minimo = ( - if 5 > 7: - return 7 - else: - return 5 -) -print('El numero mas pequeno es %i' % minimo) -\end{lstlisting} -\end{frame} - - -\section{\en{Imports}\es{Importaciónes}} - -\en{Python provides a large number of existing functions, with related functions -grouped together in \emph{modules}. To speed up loading of programs, only the -functions from modules which your program explicitly \emph{imports} are -available to call.} -\es{TODO} - -\en{To import a module, use the \texttt{import} statement at the top of your -Python file. Common modules which you might want to import are:} -\es{TODO} -\begin{description} - \item[\texttt{os}] - {\en{Functions for interfacing with the operating system.} - \es{TODO}} - \item[\texttt{sys}] - {\en{Functions for interfacing with the Python interpreter.} - \es{TODO}} - \item[\texttt{math}] - {\en{Mathematical functions more advanced than simple arithmetic.} - \es{TODO}} - \item[\texttt{gi.repository.Gtk}] - {\en{Graphical user interface classes and functions from GTK+.} - \es{TODO}} -\end{description} - -\begin{frame}[fragile] -\frametitle{\en{Imports}\es{Importaciónes}} -\begin{lstlisting}[language=Python]] -#!/usr/bin/python -# coding=utf-8 - -import os -import math -from gi.repository import Gtk -from sys import argv -\end{lstlisting} -\end{frame} - -\en{Python modules can be arranged in hierarchies, with the modules named after -the files and directories which contain the code. For example, -\texttt{repository} is a sub-module of \texttt{gi}. When referencing a class -or method in code, you can include the name of the sub-module containing it if -that sub-module hasn't been imported already (but its parent module has).} -\es{TODO} - - -\section{\en{Classes}\es{Clases}} - -\en{A \emph{class} is a collection of functions and variables which can be -instantiated multiple times. Each instance of a class is an \emph{object} and -its variables are separate from those of other instances of the same class.} -\es{TODO} - -\en{Why collect functions and variables together? It makes maintaining a large -program a lot easier by separating code and data out into different components -which don't interfere with each other.} -\es{TODO} - -\en{To define a class in Python, use the \texttt{class} statement, followed by -the class name, then the name of its parent class in brackets. All code inside -the class must be indented by 4 spaces. Parent classes allow for inheritance, -which is covered shortly.} -\es{TODO} - -\en{In this example, the \texttt{Vehiculo} class has two instance variables -(\texttt{matricula} and \texttt{numero\_de\_ruedas}) and three methods -(\texttt{\_\_init\_\_}, \texttt{calcular\_impuesto} and -\texttt{dar\_matricula}). All of the methods can access the values of the -instance variables, which can be unique for each instance of the class.} -\es{TODO} - -\en{The \texttt{\_\_init\_\_} method is special: it's the \emph{constructor} -for the class. It is called when an instance of the class is created, as shown -next.} -\es{TODO} - -\begin{frame}[fragile] -\frametitle{\en{Defining classes}\es{Definición de clases}} -\begin{lstlisting}[language=Python] -class Vehiculo(object): - def __init__(self, matricula, numero_de_ruedas): - self._matricula = matricula - self._numero_de_ruedas = numero_de_ruedas - - # Asumir vehiculos estan gravados por el numero de ruedas - def calcular_impuesto(self): - return 100 * self._numero_de_ruedas - - def dar_matricula(self): - return self._matricula -\end{lstlisting} - % TODO: syntax; constructors as special methods; inheritance; properties (definition) - % TODO: class as bundle of functions and variables; instantiating a class; getting/setting a property; calling a method from outside and inside a class instance -\end{frame} - -\en{Instantiating a class is similar to calling a function; you're effectively -calling the \texttt{\_\_init\_\_} function, and can pass it parameters as -normal. Once you've instantiated a class, you can call its methods using a -dot --- just like calling \texttt{append()} on a list. All lists are actually -instances of a \texttt{list} class.} -\es{TODO} - -\begin{frame}[fragile] -\frametitle{\en{Using classes}\es{Utilización de clases}} -\begin{lstlisting}[language=Python] -mi_coche = Vehiculo('AB99BA', 4) -mi_moto = Vehiculo('CB21TA', 2) - -print(mi_coche.calcular_impuesto()) # da 400 -print(mi_coche.dar_matricula()) # da 'AB99BA' -print(mi_moto.calcular_impuesto()) # da 200 -\end{lstlisting} -\end{frame} - -\en{Inheritance is a major feature of classes. A class can specify a parent -class which it \emph{inherits} methods from. This means that, in the example -here, instances of the \texttt{Coche} class (which inherits from -\texttt{Vehiculo}) have \texttt{calcular\_impuesto()} and -\texttt{dar\_matricula()} methods. At the bottom of the inheritance tree is -\texttt{object}.} -\es{TODO} - -\en{A child class can override one of its parent class' methods by defining -its own method of the same name. This is commonly done with the -\texttt{\_\_init\_\_} method, as here. The new code in the child class' method -can call the old code in the parent class by using \texttt{super()}.} -\es{TODO} - -\begin{frame}[fragile] -\frametitle{\en{Defining classes}\es{Definición de clases}} -\begin{lstlisting}[language=Python] -class Coche(Vehiculo): - def __init__(self, matricula, peso): - # Todos los coches tienen 4 ruedas - super(Coche, self).__init__(matricula, 4) - self._peso = peso - - def calcular_presion(self): - return self._peso / 4 - -class Moto(Vehiculo): - def __init__(self, matricula): - # Todos los motos tienen 2 ruedas - super(Moto, self).__init__(matricula, 2) - -mi_coche = Coche('AB99BA', 1500) -mi_moto = Moto('CB21TA') - -print(mi_coche.calcular_impuesto()) # da 400 -print(mi_coche.dar_matricula()) # da 'AB99BA' -print(mi_moto.calcular_impuesto()) # da 200 -\end{lstlisting} -\end{frame} - - -\subsection{\en{Private methods}\es{TODO}} - -\en{What if you want to define a method in your class but don't want it to be -callable from outside the class? For example, a method which performs part of a -larger calculation. The convention in Python is to prefix the method name with -a double-underscore, which hides it from code outside the class. The method is -then called a \emph{private method}. The same is true for variables, although -a single-underscore is commonly used for them.} -\es{TODO} - -\begin{frame}[fragile] -\frametitle{\en{Private methods}\es{TODO}} -\begin{lstlisting}[language=Python] -class Coche(Vehiculo): - TODO -\end{lstlisting} -\end{frame} - - -\section{\en{Documentation}\es{Documentación}} - -\en{As mentioned before, commenting a program is vital. Python encourages this -by making class and method documentation available when running a program, if -the documentation is written in ``docstring'' format. Documentation in this -format must be written as a single string as the first line of the class or -method being documented.} -\es{TODO} - -\begin{frame}[fragile] -\frametitle{\en{Documentation}\es{Documentación}} -\begin{lstlisting}[language=Python] -class Vehiculo(object): - """TODO""" - def my_method(self, foo): - """TODO""" - return 15 -\end{lstlisting} -\end{frame} - -\en{You can access documentation from the Python interpreter by accessing the -\texttt{\_\_doc\_\_} member variable of the class or method. - -\begin{frame}[fragile] -\frametitle{\en{Documentation}\es{Documentación}} -\begin{lstlisting}[language=Python] -print(Vehiculo.__doc__) -print(range.__doc__) -\end{lstlisting} -\end{frame} +\input{python-functions-and-classes} -% TODO: git, licensing, basic GTK+ usage, code formatting/peps +\part{\en{Writing Sugar activities}\es{Escribir actividades por Sugar}} +\input{writing-sugar-activities} \section{\en{Miscellany}\es{Miscelánea}} diff --git a/writing-sugar-activities.tex b/writing-sugar-activities.tex new file mode 100644 index 0000000..f06f2b6 --- /dev/null +++ b/writing-sugar-activities.tex @@ -0,0 +1 @@ +% TODO: This part is yet to be written. |