\mode* % Reset \mode from slides.tex \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 paréntesis rodean la suma. Tal como en la aritmética, los paréntesis se utilizan en la programación de operaciones para ponen en orden.} \en{\texttt{\%i} is the placeholder for an integer. \texttt{\%s} is the placeholder for a string. Other placeholders exist, but are used less frequently.} \es{\texttt{\%i} es el marcador de posición para un entero. \texttt{\%s} es el marcador de posición para una cadena. Hay otros marcadores de posición, pero se utilizan con menos frequencia.} \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{\en{Operators}\es{Operadores}} \en{So far, we've used several mathematical and string \emph{operators}. Operators in Python are very similar to those in mathematics: symbols which take one or two \emph{operands} (parameters or inputs) and evaluate to a single result. (Formally, they are unary or binary infix functions.)} \es{Hasta el momento, hemos utilizado varios \emph{operadores} matemáticos y de cadena. Los operadores en Python son muy similares a las de las matemáticas: símbolos que tienen uno o dos \emph{operandos} (parámetros o entradas) y evaluar a un solo resultado. (Formalmente, son funciones infijos unario o binario).} \en{As in mathematics, operators must be used with the correct number and type of operands. It wouldn't make sense to write $6 +$ as a sum, for example; or to write $15 8$ and expect to calculate the answer $15 + 8 = 23$.} \es{Al igual que en las matemáticas, los operadores deben ser utilizados con el número y el tipo correcto de operandos. No tendría sentido escribir $6 +$ como una suma, por ejemplo, o para escribir $15 8$ y esperar para calcular la respuesta $15 + 8 = 23$.} \en{When Python runs a program, operators are evaluated in order of precedence. For example, multiplication always takes precedence over addition, as in mathematics. Brackets can be used to enforce an ordering. During evaluation, Python effectively repeatedly replaces each operator and its operands with the result of the operation.} \es{Cuando Python se ejecuta un programa, los operadores se evalúan en el orden de precedencia. Por ejemplo, la multiplicación siempre tiene prioridad sobre la suma, como en matemáticas. Paréntesis pueden hacer cumplir una orden. Durante la evaluación, Python efectivamente reemplaza repetidamente cada operador y sus operandos con el resultado de la operación.} \begin{frame}[fragile] \frametitle{\en{Operator evaluation}\es{Evalución de operadors}} \begin{block}{\en{Integers}\es{Enteros}} \begin{lstlisting}[language=Python] 15 * 7 + (6 / 2) == 105 + (6 / 2) == 105 + 3 == 108 \end{lstlisting} \end{block} \begin{block}{\en{Strings}\es{Cadenas}} \begin{lstlisting}[language=Python] 'Soy %s' % ('Sr' + ' Gustavo' + ' Hernandez') == 'Soy %s' % ('Sr Gustavo' + ' Hernandez') == 'Soy %s' % 'Sr Gustavo Hernandez' == 'Soy Sr Gustavo Hernandez' \end{lstlisting} \end{block} \end{frame} \en{Here are the type signatures of a number of Python operators. These show how the operators should be used, with which types of variables, and what type of output they evaluate to. Note: Almost all integer types (\texttt{int}) below can be replaced with float. $\alpha$ represents any type. Assignment operators do not have a return value (so, for example, \texttt{5 == (a += 2)} is not valid Python.} \es{Aquí están las firmas de tipo de una serie de operadores de Python. Estos muestran cómo se deben utilizar los operadores, con el que los tipos de variables, y qué tipo de salida que evalúan. Nota: Casi todos los tipos de enteros (\texttt{int}) aquí pueden ser reemplazados con \texttt{float}. $\alpha$ representa cualquier tipo. Los operadores de asignación no tienen un valor de retorno (así, por ejemplo, \texttt{5 == (a + = 2)} no es válido Python.} \begin{frame}[fragile] \frametitle{\en{Operators}\es{Operadores}} \begin{block}{\en{Numerical}\es{Númerico}} \begin{align*} \mathtt{int}\; \mathtt{+} \;\mathtt{int} &\to \mathtt{int} \\ \mathtt{int}\; \mathtt{-} \;\mathtt{int} &\to \mathtt{int} \\ \mathtt{int}\; \mathtt{*} \;\mathtt{int} &\to \mathtt{int} \\ \mathtt{int}\; \mathtt{/} \;\mathtt{int} &\to \mathtt{int} \\ \mathtt{int}\; \mathtt{\%} \;\mathtt{int} &\to \mathtt{int} \\ \mathtt{int}\; \mathtt{**} \;\mathtt{int} &\to \mathtt{int} \\ \mathtt{int}\; \mathtt{//} \;\mathtt{int} &\to \mathtt{int} \end{align*} \end{block} \end{frame} \begin{frame}[fragile] \frametitle{\en{Operators}\es{Operadores}} \begin{block}{\en{String}\es{Cadena}} \begin{align*} \mathtt{str}\; \mathtt{+} \;\mathtt{str} &\to \mathtt{str} \\ \mathtt{str}\; \mathtt{\%} \;\mathtt{tuple} &\to \mathtt{str} \end{align*} \end{block} \begin{block}{\en{Comparison}\es{Comparación}} \begin{align*} \mathtt{int}\; \mathtt{>} \;\mathtt{int} &\to \mathtt{bool} \\ \mathtt{int}\; \mathtt{<} \;\mathtt{int} &\to \mathtt{bool} \\ \mathtt{int}\; \mathtt{>=} \;\mathtt{int} &\to \mathtt{bool} \\ \mathtt{int}\; \mathtt{<=} \;\mathtt{int} &\to \mathtt{bool} \\ \alpha\; \mathtt{==} \;\alpha &\to \mathtt{bool} \\ \alpha\; \mathtt{!=} \;\alpha &\to \mathtt{bool} \end{align*} \end{block} \end{frame} \begin{frame}[fragile] \frametitle{\en{Operators}\es{Operadores}} \begin{block}{\en{Assignment}\es{Asignación}} \begin{align*} \alpha\; &= \;\alpha \\ \mathtt{int}\; &\mathtt{+=} \;\mathtt{int} \\ \mathtt{int}\; &\mathtt{-=} \;\mathtt{int} \\ \mathtt{int}\; &\mathtt{*=} \;\mathtt{int} \\ \mathtt{int}\; &\mathtt{/=} \;\mathtt{int} \\ \mathtt{int}\; &\mathtt{\%=} \;\mathtt{int} \\ \mathtt{int}\; &\mathtt{**=} \;\mathtt{int} \\ \mathtt{int}\; &\mathtt{//=} \;\mathtt{int} \end{align*} \end{block} \end{frame} \begin{frame}[fragile] \frametitle{\en{Operators}\es{Operadores}} \begin{block}{\en{Logical}\es{Lógico}} \begin{align*} \mathtt{bool}\; \mathtt{and} \;\mathtt{bool} &\to \mathtt{bool} \\ \mathtt{bool}\; \mathtt{or} \;\mathtt{bool} &\to \mathtt{bool} \\ \mathtt{not} \;\mathtt{bool} &\to \mathtt{bool} \end{align*} \end{block} \begin{block}{\en{Membership}\es{Afiliación}} \begin{align*} \alpha\; \mathtt{in} \;\alpha~\mathtt{seq} &\to \mathtt{bool} \\ \alpha\; \mathtt{not~in} \;\alpha~\mathtt{seq} &\to \mathtt{bool} \end{align*} \end{block} \end{frame} \begin{frame}[fragile] \frametitle{\en{Operators}\es{Operadores}} \begin{block}{\en{Identity}\es{Identidad}} \begin{align*} \alpha\; \mathtt{is} \;\alpha &\to \mathtt{bool} \\ \alpha\; \mathtt{is~not} \;\alpha &\to \mathtt{bool} \end{align*} \end{block} \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()}.} \en{A single equals sign, \texttt{=}, is used to assign a value to a variable. It is called the \emph{assignment operator}.} \es{Un solo signo igual, \texttt{=}, se utiliza para asignar un valor a una variable. Se llama el \emph{operador de asignación}.} \begin{frame}[fragile] \frametitle{Variables} \begin{lstlisting}[language=Python,numbers=none] >>> x = int(raw_input('Escriba un numero: ')) Escriba un numero: 5 >>> print('Doble del numero: %i' % (x * 2)) 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 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('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} ejecuta 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('Numero: ')) 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{Tuples, lists and dictionaries}\es{Tuplas, listas y diccionarios}} \en{As well as integers, strings and booleans, Python has three more data types: tuples, lists and dictionaries. A list is just like in real life: an ordered sequence of items. A tuple is like a list, except that a list has a variable number of items (they can be added or removed); a tuple has a fixed number 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 tres más tipos de datos: tuplas, listas y diccionarios. Una lista es igual que en la vida real: una secuencia ordenada de elementos. Una tupla es como una lista, con la excepción de que la lista tiene un número variable de elementos (que pueden ser añadidos o eliminados), una tupla tiene un número fijo de elementos. Un diccionario también es similar a la vida real: un mapeo no ordenada de llaves a valores.} \en{This example demonstrates constructing a tuple of four items and accessing the 1st and 3rd items. Note that, like other programming languages, ordinal numbering starts from 0. Tuples are written as a pair of brackets around their elements, which are separated by commas.} \es{Este ejemplo demuestra la construcción de una tupla de cuatro elementos y el acceso a los elementos primero y tercero. Tenga un cuenta que, al igual que otros lenguajes de programación, numeración ordinal comienza desde 0. Las tuplas se escriben como paréntesis alrededor de sus elementos, que están separados por comas.} \begin{frame}[fragile] \frametitle{\en{Tuples}\es{Tuplas}} \begin{lstlisting}[language=Python,numbers=none] >>> tupla = ('hola', 5, true, 'mundo') >>> print(tupla[0]) hola >>> print(tupla[2]) true \end{lstlisting} \end{frame} \en{The example below demonstrates constructing a list of three items and accessing the 1st and 2nd items in the list. Lists are written as a pair of square brackets surrounding their items, which are separated by commas.} \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. Las listas se escriben como paréntesis que encierran sus elementos, separados por comas.} \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 adelante.} \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} \en{A dictionary is a mapping of keys to values. Each key has exactly one value, which can be retrieved or updated by providing the dictionary with the key. Formally, a dictionary is like a partial function in mathematics. All of its keys must be unique.} \es{Un diccionario es una asignación de llaves a los valores. Cada llave tiene exactamente un valor, que puede ser recuperada o actualiza proporcionando el diccionario con la llave. Formalmente, un diccionario es como una función parcial en matemáticas. Todos sus claves deben ser únicas.} \en{A dictionary is created using curly brackets, with keys being separated from their values by a colon, and all key--value pairs separated by commas. A value can be looked up in a dictionary by using square brackets and the key; the key's value can be updated similarly. To add a new entry to a dictionary, just assign to the new key. To remove an old entry from a dictionary, use the \texttt{del} keyword. A key can be tested for membership in a dictionary using the \texttt{in} operator.} \es{Un diccionario es creado usando llaves, con las llaves están separadas de sus valores por dos puntos, y toda la llave--valor pares separados por comas. Un valor se puede consultar en un diccionario mediante corchetes y la llave. El valor de la llave se puede actualizar de manera similar. Para añadir una nueva entrada a un diccionario, simplemente asignar a la nueva llave. Para eliminar una entrada vieja de un diccionario, utilice la instrucción \texttt{del}. Una de las llaves puede ser probado para ser miembro de un diccionario con el \texttt{in} operador.} \begin{frame}[fragile] \frametitle{\en{Dictionaries}\es{Diccionarios}} \begin{lstlisting}[language=Python,numbers=none] >>> dict = {'llave': 'valor', 'otra': 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, pero sólo en inglés. 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 \en{my-file.py}\es{mi-archivo.py}}.} \es{Desde un terminal, ejecute \texttt{python \en{my-file.py}\es{mi-archivo.py}}.}} \end{itemize} \end{frame} \begin{frame}{\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}