diff options
author | Philip Withnall <philip@tecnocode.co.uk> | 2013-08-22 14:53:37 (GMT) |
---|---|---|
committer | Philip Withnall <philip@tecnocode.co.uk> | 2013-08-22 14:53:37 (GMT) |
commit | 6f90359fc30c2d599eddba4bc30f67a28713576d (patch) | |
tree | 5c42c0b6c3f492f8c16430a6c3bfb00450ee1d90 |
Initial commit of version 1 of the presentation
42 files changed, 1833 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4e23e3b --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +handout.aux +handout.log +handout.out +handout.pdf +presentation.aux +presentation.log +presentation.nav +presentation.out +presentation.pdf +presentation.snm +presentation.toc +presentation.vrb diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..6fdba1d --- /dev/null +++ b/Makefile @@ -0,0 +1,48 @@ +PDFS = presentation.pdf handout.pdf +EN_EXERCISES = \ + 1_printing-names \ + 2_arithmetic \ + 3_squares \ + 4_fibonacci \ + 5_while \ + 6_break \ + 7_lists \ + 8_lists-min \ + 9_dicts \ + $(NULL) +ES_EXERCISES = \ + 1_imprimir-nombres \ + 2_aritmetica \ + 3_cuadrados \ + 4_fibonacci \ + 5_while \ + 6_break \ + 7_listas \ + 8_listas-min \ + 9_dicts \ + $(NULL) + +all: $(PDFS) + +presentation.pdf: presentation.tex slides.tex + pdflatex $< + pdflatex $< + +handout.pdf: handout.tex slides.tex + pdflatex $< + pdflatex $< + +check: + $(foreach ex,$(EN_EXERCISES),pep8 exercises/en/${ex}.py exercises/en/${ex}_solution.py;) + $(foreach ex,$(ES_EXERCISES),pep8 exercises/es/${ex}.py exercises/es/${ex}_solucion.py;) + +clean: + rm -f $(PDFS:.pdf=.aux) + rm -f $(PDFS:.pdf=.log) + rm -f $(PDFS:.pdf=.out) + rm -f $(PDFS:.pdf=.nav) + rm -f $(PDFS:.pdf=.snm) + rm -f $(PDFS:.pdf=.toc) + rm -f $(PDFS:.pdf=.vrb) + +.PHONY: all clean check diff --git a/Practice programs b/Practice programs new file mode 100644 index 0000000..a19ce14 --- /dev/null +++ b/Practice programs @@ -0,0 +1,5 @@ +Ideas for additional programs which people could write as practice: + - Reverse a list. + - Convert a list into a histogram dictionary. + - Implement Euler’s method. + - List all the prime numbers up to a given maximum. diff --git a/exercises/en/1_printing-names.py b/exercises/en/1_printing-names.py new file mode 100644 index 0000000..2ec299c --- /dev/null +++ b/exercises/en/1_printing-names.py @@ -0,0 +1,12 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This code asks the user for their name, stores it in a variable, then prints +it again. + +You must extend the code to also ask the user for their surname, store it in a +second variable, and concatenate it to the forename to print out the user's +full name. +""" +forename = raw_input('Enter your forename: ') +print('Your name is: %s' % forename) diff --git a/exercises/en/1_printing-names_solution.py b/exercises/en/1_printing-names_solution.py new file mode 100644 index 0000000..f27eb94 --- /dev/null +++ b/exercises/en/1_printing-names_solution.py @@ -0,0 +1,13 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This code asks the user for their name, stores it in a variable, then prints +it again. + +You must extend the code to also ask the user for their surname, store it in a +second variable, and concatenate it to the forename to print out the user's +full name. +""" +forename = raw_input('Enter your forename: ') +surname = raw_input('Enter your surname: ') +print('Your name is: %s' % (forename + ' ' + surname)) diff --git a/exercises/en/2_arithmetic.py b/exercises/en/2_arithmetic.py new file mode 100644 index 0000000..472cd43 --- /dev/null +++ b/exercises/en/2_arithmetic.py @@ -0,0 +1,19 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Below are a few sums demonstrating Python's arithmetic operators. + +You must extend the code to also print the total (sum) and average (mean) of +the 5 results. + +Extension: Calculate the average as a floating-point number, rather than as an +integer. You will find the float() function useful, which is similar to the +int() function used before. +""" +add = 1 + 2 + 3 +subtract = 10 - 9 - 8 +multiply = 4 * 5 * 6 +divide = 8 / 4 +exponentiate = 2 ** 5 + +print('Sums: %i,%i,%i,%i,%i' % (add, subtract, multiply, divide, exponentiate)) diff --git a/exercises/en/2_arithmetic_solution.py b/exercises/en/2_arithmetic_solution.py new file mode 100644 index 0000000..06d0b75 --- /dev/null +++ b/exercises/en/2_arithmetic_solution.py @@ -0,0 +1,31 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Below are a few sums demonstrating Python's arithmetic operators. + +You must extend the code to also print the total (sum) and average (mean) of +the 5 results. + +Extension: Calculate the average as a floating-point number, rather than as an +integer. You will find the float() function useful, which is similar to the +int() function used before. +""" +add = 1 + 2 + 3 +subtract = 10 - 9 - 8 +multiply = 4 * 5 * 6 +divide = 8 / 4 +exponentiate = 2 ** 5 + +print('Sums: %i,%i,%i,%i,%i' % (add, subtract, multiply, divide, exponentiate)) + +# Calculate and print the total. +total = add + subtract + multiply + divide + exponentiate +print('Total: %i' % total) + +# Calculate and print the integer average. +average = total / 5 +print('Average: %i' % average) + +# Extension: Calculate and print the floating point average. +floating_average = float(total) / 5.0 +print('Floating average: %f' % floating_average) diff --git a/exercises/en/3_squares.py b/exercises/en/3_squares.py new file mode 100644 index 0000000..06d189b --- /dev/null +++ b/exercises/en/3_squares.py @@ -0,0 +1,11 @@ +#!/usr/bin/python +# coding=utf-8 + +"""The code below prints the first 10 square numbers. + +You must modify the code to instead print the first 10 powers of a number +entered by the user. For example, if the user enters '3', the program will +print the first 10 powers of 3 (1, 3, 9, 27, 81, ...). +""" +for i in range(10): + print(i ** 2) diff --git a/exercises/en/3_squares_solution.py b/exercises/en/3_squares_solution.py new file mode 100644 index 0000000..80edfef --- /dev/null +++ b/exercises/en/3_squares_solution.py @@ -0,0 +1,12 @@ +#!/usr/bin/python +# coding=utf-8 + +"""The code below prints the first 10 square numbers. + +You must modify the code to instead print the first 10 powers of a number +entered by the user. For example, if the user enters '3', the program will +print the first 10 powers of 3 (1, 3, 9, 27, 81, ...). +""" +base = int(raw_input('Enter a base number: ')) +for i in range(10): + print(base ** i) diff --git a/exercises/en/4_fibonacci.py b/exercises/en/4_fibonacci.py new file mode 100644 index 0000000..825a7d7 --- /dev/null +++ b/exercises/en/4_fibonacci.py @@ -0,0 +1,18 @@ +#!/usr/bin/python +# coding=utf-8 + +"""You must write code to print the first N numbers in the Fibonacci sequence. + +Your program must read N from the user, with the prompt 'How many Fibonacci +numbers should be printed?'. It must then print the first N numbers from the +sequence defined by: + F_0 = 0 + F_1 = 1 + F_n = F_{n - 1} + F_{n - 2} + +e.g. The sequence: 0, 1, 1, 2, 3, 5, 8, 13, ... +""" +total = int(raw_input('How many Fibonacci numbers should be printed? ')) + +# Add your code here. Hint: use two variables to store most recent two values +# in the sequence. diff --git a/exercises/en/4_fibonacci_solution.py b/exercises/en/4_fibonacci_solution.py new file mode 100644 index 0000000..021bd88 --- /dev/null +++ b/exercises/en/4_fibonacci_solution.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# coding=utf-8 + +"""You must write code to print the first N numbers in the Fibonacci sequence. + +Your program must read N from the user, with the prompt 'How many Fibonacci +numbers should be printed?'. It must then print the first N numbers from the +sequence defined by: + F_0 = 0 + F_1 = 1 + F_n = F_{n - 1} + F_{n - 2} + +e.g. The sequence: 0, 1, 1, 2, 3, 5, 8, 13, ... +""" +total = int(raw_input('How many Fibonacci numbers should be printed? ')) +fn = 0 +fm = 1 +for i in range(total): + # Print the oldest number we know before updating it. + print(fn) + + # Update the fn and fm values. + fn_old = fn + fn = fm + fm = fn_old + fm diff --git a/exercises/en/5_while.py b/exercises/en/5_while.py new file mode 100644 index 0000000..aaef9d0 --- /dev/null +++ b/exercises/en/5_while.py @@ -0,0 +1,21 @@ +#!/usr/bin/python +# coding=utf-8 + +import random + +"""This program should divide the initial number by random divisors. + +Once the result is smaller than 1, the program should stop. The program is +complete apart from a loop statement. Add one on the indicated line to complete +the program. + +Hint: A 'for' loop iterates a fixed number of times, and so might be +unsuitable. +""" + +num = 100 +# Replace this line with a loop statement. + # This prints the number, then divides it by a random number + # between 2 and 5. + print(num) + num = num / random.randint(2, 5) diff --git a/exercises/en/5_while_solution.py b/exercises/en/5_while_solution.py new file mode 100644 index 0000000..007c5c8 --- /dev/null +++ b/exercises/en/5_while_solution.py @@ -0,0 +1,21 @@ +#!/usr/bin/python +# coding=utf-8 + +import random + +"""This program should divide the initial number by random divisors. + +Once the result is smaller than 1, the program should stop. The program is +complete apart from a loop statement. Add one on the indicated line to complete +the program. + +Hint: A 'for' loop iterates a fixed number of times, and so might be +unsuitable. +""" + +num = 100 +while num >= 1: + # This prints the number, then divides it by a random number + # between 2 and 5. + print(num) + num = num / random.randint(2, 5) diff --git a/exercises/en/6_break.py b/exercises/en/6_break.py new file mode 100644 index 0000000..6af1581 --- /dev/null +++ b/exercises/en/6_break.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This program repeatedly asks the user for a number and prints it. + +Currently, it will never terminate: you must press Ctrl+C to end the program. +However, Python has a 'break' statement which causes execution to leave a loop +and continue with the code below the loop. For example, the following code will +print only the numbers 0, 1, 2, 3, 4. When (i == 5), the 'if' condition is +True, and the break statement is executed, ending the loop. + + for i in range(10): + print(i) + if i >= 5 + break + +Modify the program below to leave the loop if the user enters a number greater +than 10. When doing so, your program must also print 'Number was too big!'. +Otherwise, if the number is 10 or less, your program must print 'Your +number...' as before. +""" + +while True: + num = int(raw_input('Enter a number: ')) + print('Your number: %i' % num) diff --git a/exercises/en/6_break_solution.py b/exercises/en/6_break_solution.py new file mode 100644 index 0000000..4203a62 --- /dev/null +++ b/exercises/en/6_break_solution.py @@ -0,0 +1,29 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This program repeatedly asks the user for a number and prints it. + +Currently, it will never terminate: you must press Ctrl+C to end the program. +However, Python has a 'break' statement which causes execution to leave a loop +and continue with the code below the loop. For example, the following code will +print only the numbers 0, 1, 2, 3, 4. When (i == 5), the 'if' condition is +True, and the break statement is executed, ending the loop. + + for i in range(10): + print(i) + if i >= 5 + break + +Modify the program below to leave the loop if the user enters a number greater +than 10. When doing so, your program must also print 'Number was too big!'. +Otherwise, if the number is 10 or less, your program must print 'Your +number...' as before. +""" + +while True: + num = int(raw_input('Enter a number: ')) + if num > 10: + print('Number was too big!') + break + else: + print('Your number: %i' % num) diff --git a/exercises/en/7_lists.py b/exercises/en/7_lists.py new file mode 100644 index 0000000..2d6371e --- /dev/null +++ b/exercises/en/7_lists.py @@ -0,0 +1,21 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This program defines a list of names and checks whether the user's name is +in it. + +The check to see if the user's name is in the list is not implemented. You must +implement it, then add an 'else' statement which appends the user's name to the +list if it's not already there then prints all the names on the list. + +You can loop over the list using "for nom in lista:". +""" + +lista = ['Angelica', 'Juan', 'Maria', 'Ariel', 'Jorge'] +nombre = raw_input('Escribir su nombre: ') + +# Modify this 'if' statement to be executed if nombre is in lista. +if False: + print('Su nombre es en la lista.') +# Add an 'else' statement and another instruction to add nombre to lista then +# print all the names in lista. diff --git a/exercises/en/7_lists_solution.py b/exercises/en/7_lists_solution.py new file mode 100644 index 0000000..00a7323 --- /dev/null +++ b/exercises/en/7_lists_solution.py @@ -0,0 +1,22 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This program defines a list of names and checks whether the user's name is +in it. + +The check to see if the user's name is in the list is not implemented. You must +implement it, then add an 'else' statement which appends the user's name to the +list if it's not already there then prints all the names on the list. + +You can loop over the list using "for nom in lista:". +""" + +lista = ['Angelica', 'Juan', 'Maria', 'Ariel', 'Jorge'] +nombre = raw_input('Escribir su nombre: ') + +if nombre in lista: + print('Su nombre es en la lista.') +else: + lista.append(nombre) + for nom in lista: + print(nom) diff --git a/exercises/en/8_lists-min.py b/exercises/en/8_lists-min.py new file mode 100644 index 0000000..59d3560 --- /dev/null +++ b/exercises/en/8_lists-min.py @@ -0,0 +1,20 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This program builds a list of numbers, then should print the minimum number. + +Currently, it only builds a list of numbers. You must modify the program to +print the smallest number in the list, for example: + print('The smallest number is: %i' % something) + +There are several ways to do this. The simplest is to use a method described in +the API reference for lists, which finds the minimum element in a list: + http://docs.python.org/2.7/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange +""" + +# Start with an empty list, and append 5 numbers to it. +lista = [] +for i in range(5): + lista.append(int(raw_input('Enter a number: '))) + +# Add code here to print the minimum number in the list. diff --git a/exercises/en/8_lists-min_solution.py b/exercises/en/8_lists-min_solution.py new file mode 100644 index 0000000..43994fc --- /dev/null +++ b/exercises/en/8_lists-min_solution.py @@ -0,0 +1,23 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This program builds a list of numbers, then should print the minimum number. + +Currently, it only builds a list of numbers. You must modify the program to +print the smallest number in the list, for example: + print('The smallest number is: %i' % something) + +There are several ways to do this. The simplest is to use a method described in +the API reference for lists, which finds the minimum element in a list: + http://docs.python.org/2.7/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange +""" + +# Start with an empty list, and append 5 numbers to it. +lista = [] +for i in range(5): + lista.append(int(raw_input('Enter a number: '))) + +# Print the minimum element in the list using the min() method, which is +# described here: +# http://docs.python.org/2.7/library/functions.html#min +print('The smallest number is: %i' % min(lista)) diff --git a/exercises/en/9_dicts.py b/exercises/en/9_dicts.py new file mode 100644 index 0000000..4d92ddd --- /dev/null +++ b/exercises/en/9_dicts.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This program looks up the user's favourite colour or asks them about it. + +This program has a dictionary which maps users' names to their favourite +colour. If the user is _not_ in the dictionary, you must add code which asks +the user for their favourite colour, then adds a mapping to the dictionary from +the user's name to their colour. +""" + +colores = { + 'Anna': 'rojo', + 'Jorge': 'verde', + 'Max': 'verde', + 'Felix': 'negro', + 'Ariel': 'amarillo', +} + +nombre = raw_input('Escribir su nombre: ') +if nombre in colores: + print('Su color favorito es: %s' % colores[nombre]) +# Add code here to, if nombre is not in the dictionary, ask the user for their +# favourite colour and add a new entry to the dictionary mapping their name to +# their favourite colour. diff --git a/exercises/en/9_dicts_solution.py b/exercises/en/9_dicts_solution.py new file mode 100644 index 0000000..a669513 --- /dev/null +++ b/exercises/en/9_dicts_solution.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# coding=utf-8 + +"""This program looks up the user's favourite colour or asks them about it. + +This program has a dictionary which maps users' names to their favourite +colour. If the user is _not_ in the dictionary, you must add code which asks +the user for their favourite colour, then adds a mapping to the dictionary from +the user's name to their colour. +""" + +colores = { + 'Anna': 'rojo', + 'Jorge': 'verde', + 'Max': 'verde', + 'Felix': 'negro', + 'Ariel': 'amarillo', +} + +nombre = raw_input('Escribir su nombre: ') +if nombre in colores: + print('Su color favorito es: %s' % colores[nombre]) +else: + color = raw_input('Escribir su color favorito: ') + colores[nombre] = color diff --git a/exercises/es/1_imprimir-nombres.py b/exercises/es/1_imprimir-nombres.py new file mode 100644 index 0000000..26955e9 --- /dev/null +++ b/exercises/es/1_imprimir-nombres.py @@ -0,0 +1,12 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este código le pide al usario su nombre, lo guarda en una variable, luego +imprime de nuevo. + +Usted debe extender el código para también pedir al usario su apellido, guárdelo +en un segunda variable, y concatenar al nombre y luego imprimir el nombre +completo del usario. +""" +nombre = raw_input('Escribe su nombre: ') +print('Su nombre es: %s' % nombre) diff --git a/exercises/es/1_imprimir-nombres_solucion.py b/exercises/es/1_imprimir-nombres_solucion.py new file mode 100644 index 0000000..a547973 --- /dev/null +++ b/exercises/es/1_imprimir-nombres_solucion.py @@ -0,0 +1,13 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este código le pide al usario su nombre, lo guarda en una variable, luego +imprime de nuevo. + +Usted debe extender el código para también pedir al usario su apellido, guárdelo +en un segunda variable, y concatenar al nombre y luego imprimir el nombre +completo del usario. +""" +nombre = raw_input('Escribe su nombre: ') +apellido = raw_input('Escribe su apellido: ') +print('Su nombre completo es: %s' % (nombre + ' ' + apellido)) diff --git a/exercises/es/2_aritmetica.py b/exercises/es/2_aritmetica.py new file mode 100644 index 0000000..76bf589 --- /dev/null +++ b/exercises/es/2_aritmetica.py @@ -0,0 +1,20 @@ +#!/usr/bin/python +# coding=utf-8 + +"""A continuación se presentan algunas sumas que demuestran operadores +aritméticos de Python. + +Usted debe extender el código para también imprimir del total (suma) y el +promedio (media) de los 5 resultados. + +Extensión: Calcular el promedio como un número de coma flotante, en lugar de +como un número entero. Usted encontrará la función float() útil, que es similar +a la función int() utiliza antes. +""" +sumar = 1 + 2 + 3 +restar = 10 - 9 - 8 +multiplicar = 4 * 5 * 6 +dividir = 8 / 4 +exponenciar = 2 ** 5 + +print('Sumas: %i,%i,%i,%i,%i' % (sumar, restar, multiplicar, dividir, exponenciar)) diff --git a/exercises/es/2_aritmetica_solucion.py b/exercises/es/2_aritmetica_solucion.py new file mode 100644 index 0000000..f7d06c9 --- /dev/null +++ b/exercises/es/2_aritmetica_solucion.py @@ -0,0 +1,32 @@ +#!/usr/bin/python +# coding=utf-8 + +"""A continuación se presentan algunas sumas que demuestran operadores +aritméticos de Python. + +Usted debe extender el código para también imprimir del total (suma) y el +promedio (media) de los 5 resultados. + +Extensión: Calcular el promedio como un número de coma flotante, en lugar de +como un número entero. Usted encontrará la función float() útil, que es similar +a la función int() utiliza antes. +""" +sumar = 1 + 2 + 3 +restar = 10 - 9 - 8 +multiplicar = 4 * 5 * 6 +dividir = 8 / 4 +exponenciar = 2 ** 5 + +print('Sumas: %i,%i,%i,%i,%i' % (sumar, restar, multiplicar, dividir, exponenciar)) + +# Calcular e imprimir el total. +total = sumar + restar + multiplicar + dividir + exponenciar +print('Total: %i' % total) + +# Calcular e imprimir el promedio de número entero. +promedio = total / 5 +print('Promedio: %i' % promedio) + +# Extensión: Calcular e imprimir el promiedo de punto flotante. +promedio_flotante = float(total) / 5.0 +print('Promedio de punto flotante: %f' % promedio_flotante) diff --git a/exercises/es/3_cuadrados.py b/exercises/es/3_cuadrados.py new file mode 100644 index 0000000..2ed1d7f --- /dev/null +++ b/exercises/es/3_cuadrados.py @@ -0,0 +1,11 @@ +#!/usr/bin/python +# coding=utf-8 + +"""El código siguiente imprime los 10 primeros números cuadrados. + +Usted debe modificar el código para su lugar imprime las 10 primeras potencias +de un número introducido por el usario. Por ejemplo, si el usario introduce '3', +el programa se imprimir los primero 10 poderes de 3 (1, 3, 9, 27, 81, ...). +""" +for i in range(10): + print(i ** 2) diff --git a/exercises/es/3_cuadrados_solucion.py b/exercises/es/3_cuadrados_solucion.py new file mode 100644 index 0000000..5a62663 --- /dev/null +++ b/exercises/es/3_cuadrados_solucion.py @@ -0,0 +1,12 @@ +#!/usr/bin/python +# coding=utf-8 + +"""El código siguiente imprime los 10 primeros números cuadrados. + +Usted debe modificar el código para su lugar imprime las 10 primeras potencias +de un número introducido por el usario. Por ejemplo, si el usario introduce '3', +el programa se imprimir los primero 10 poderes de 3 (1, 3, 9, 27, 81, ...). +""" +base = int(raw_input('Escribir un número de la base: ')) +for i in range(10): + print(base ** i) diff --git a/exercises/es/4_fibonacci.py b/exercises/es/4_fibonacci.py new file mode 100644 index 0000000..60ea55e --- /dev/null +++ b/exercises/es/4_fibonacci.py @@ -0,0 +1,19 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Usted debe escribir código para imprimir los primeros N números en el +secuencia de Fibonacci. + +Su programa debe leer N por parte del usario, con el mensaje '¿Cuántos Fibonacci +números deben ser impresas?'. A continuación, deberá imprimir los primeros N +números de la secuencia definida por: + F_0 = 0 + F_1 = 1 + F_n = F_{n - 1} + F_{n - 2} + +Por ejemplo la secuencia: 0, 1, 1, 2, 3, 5, 8, 13, ... +""" +total = int(raw_input('¿Cuántos Fibonacci números deben ser impresas? ')) + +# Añadir su código aquí. Consejo: usar dos variables para guardar y actualizar +# los dos valores más recientes de la secuencia. diff --git a/exercises/es/4_fibonacci_solucion.py b/exercises/es/4_fibonacci_solucion.py new file mode 100644 index 0000000..e2dbbee --- /dev/null +++ b/exercises/es/4_fibonacci_solucion.py @@ -0,0 +1,26 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Usted debe escribir código para imprimir los primeros N números en el +secuencia de Fibonacci. + +Su programa debe leer N por parte del usario, con el mensaje '¿Cuántos Fibonacci +números deben ser impresas?'. A continuación, deberá imprimir los primeros N +números de la secuencia definida por: + F_0 = 0 + F_1 = 1 + F_n = F_{n - 1} + F_{n - 2} + +Por ejemplo la secuencia: 0, 1, 1, 2, 3, 5, 8, 13, ... +""" +total = int(raw_input('¿Cuántos Fibonacci números deben ser impresas? ')) +fn = 0 +fm = 1 +for i in range(total): + # Imprimir el número más antiguo que conocemos antes de actualizarlo. + print(fn) + + # Actualizar los valores fn y fm. + fn_old = fn + fn = fm + fm = fn_old + fm diff --git a/exercises/es/5_while.py b/exercises/es/5_while.py new file mode 100644 index 0000000..464c14c --- /dev/null +++ b/exercises/es/5_while.py @@ -0,0 +1,20 @@ +#!/usr/bin/python +# coding=utf-8 + +import random + +"""Este programa debe dividir el número inicial de divisores azar. + +Cuando el resultado es menor que 1, el programa debe terminar. El programa es +completar aparte de una instrucción de bucle. Añadir una en la línea indicada +para completar el programa. + +Consejo: Un bucle 'for' se repite un número fijo de veces, y por lo tanto puede +ser inadecuado. +""" + +num = 100 +# Reemplace esta línea con una instrucción de bucle. + # Imprime el número y lo divide por un número aleatorio entre 2 y 5. + print(num) + num = num / random.randint(2, 5) diff --git a/exercises/es/5_while_solucion.py b/exercises/es/5_while_solucion.py new file mode 100644 index 0000000..65bdbfb --- /dev/null +++ b/exercises/es/5_while_solucion.py @@ -0,0 +1,20 @@ +#!/usr/bin/python +# coding=utf-8 + +import random + +"""Este programa debe dividir el número inicial de divisores azar. + +Cuando el resultado es menor que 1, el programa debe terminar. El programa es +completar aparte de una instrucción de bucle. Añadir una en la línea indicada +para completar el programa. + +Consejo: Un bucle 'for' se repite un número fijo de veces, y por lo tanto puede +ser inadecuado. +""" + +num = 100 +while num >= 1: + # Imprime el número y lo divide por un número aleatorio entre 2 y 5. + print(num) + num = num / random.randint(2, 5) diff --git a/exercises/es/6_break.py b/exercises/es/6_break.py new file mode 100644 index 0000000..4927b00 --- /dev/null +++ b/exercises/es/6_break.py @@ -0,0 +1,26 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este programa le pregunta repetidamente al usario un número y lo imprime. + +En la actualidad, nunca se dará por terminado: hay que pulsar Ctrl+C para +finalizar el programa. Sin embargo, Python tiene una instrucción 'break' que +hace que la ejecución de abandonar el bucle y continuar la ejecución del código +después del bucle. Por ejemplo, el siguiente código imprimir sólo los números +0, 1, 2, 3, 4. Cuando (i == 5), el condición 'if' es True, y la instrucción +'break' se ejecuta, finalizando el bucle. + + for i in range(10): + print(i) + if i >= 5 + break + +Modificar el programa a continuación para abandonar el bucle si el usario +escribe un número mayor de 10. Al hacer esto, el programa debe imprimir 'Número +era demasiado grande!'. De lo contrario, si el número es 10 o menos, el programa +debe imprimir 'Su número...' como antes. +""" + +while True: + num = int(raw_input('Escribe un número: ')) + print('Su número: %i' % num) diff --git a/exercises/es/6_break_solucion.py b/exercises/es/6_break_solucion.py new file mode 100644 index 0000000..9e251f3 --- /dev/null +++ b/exercises/es/6_break_solucion.py @@ -0,0 +1,30 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este programa le pregunta repetidamente al usario un número y lo imprime. + +En la actualidad, nunca se dará por terminado: hay que pulsar Ctrl+C para +finalizar el programa. Sin embargo, Python tiene una instrucción 'break' que +hace que la ejecución de abandonar el bucle y continuar la ejecución del código +después del bucle. Por ejemplo, el siguiente código imprimir sólo los números +0, 1, 2, 3, 4. Cuando (i == 5), el condición 'if' es True, y la instrucción +'break' se ejecuta, finalizando el bucle. + + for i in range(10): + print(i) + if i >= 5 + break + +Modificar el programa a continuación para abandonar el bucle si el usario +escribe un número mayor de 10. Al hacer esto, el programa debe imprimir 'Número +era demasiado grande!'. De lo contrario, si el número es 10 o menos, el programa +debe imprimir 'Su número...' como antes. +""" + +while True: + num = int(raw_input('Escribe un número: ')) + if num > 10: + print('Número era demasiado grande!') + break + else: + print('Su número: %i' % num) diff --git a/exercises/es/7_listas.py b/exercises/es/7_listas.py new file mode 100644 index 0000000..609d8c5 --- /dev/null +++ b/exercises/es/7_listas.py @@ -0,0 +1,23 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este program define una lista de nombres y comprueba si el nombre del usario +es en ella. + +La comprobación para ver si el nombre del usario se encuentra en la lista no se +ha implementado. Usted debe ponerlo en práctica, a continuación, agregar una +instrucción 'else', que añade el nombre del usario de la lista si no está ya +allí, entonces imprime todos los nombres en la lista. + +Usted puede utilizar un bucle en la lista con "for nom in lista:". +""" + +lista = ['Angelica', 'Juan', 'Maria', 'Ariel', 'Jorge'] +nombre = raw_input('Escribe su nombre: ') + +# Modificar este instrucción 'if' para ser ejecutado si 'nombre' está en +# 'lista'. +if False: + print('Su nombre es en la lista.') +# Agregue una instrucción 'else' y otra instrucción para añadir 'nombre' a +# 'lista' y luego imprimir todos los nombres de 'lista'. diff --git a/exercises/es/7_listas_solucion.py b/exercises/es/7_listas_solucion.py new file mode 100644 index 0000000..9847bfd --- /dev/null +++ b/exercises/es/7_listas_solucion.py @@ -0,0 +1,23 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este program define una lista de nombres y comprueba si el nombre del usario +es en ella. + +La comprobación para ver si el nombre del usario se encuentra en la lista no se +ha implementado. Usted debe ponerlo en práctica, a continuación, agregar una +instrucción 'else', que añade el nombre del usario de la lista si no está ya +allí, entonces imprime todos los nombres en la lista. + +Usted puede utilizar un bucle en la lista con "for nom in lista:". +""" + +lista = ['Angelica', 'Juan', 'Maria', 'Ariel', 'Jorge'] +nombre = raw_input('Escribe su nombre: ') + +if nombre in lista: + print('Su nombre es en la lista.') +else: + lista.append(nombre) + for nom in lista: + print(nom) diff --git a/exercises/es/8_listas-min.py b/exercises/es/8_listas-min.py new file mode 100644 index 0000000..0d95568 --- /dev/null +++ b/exercises/es/8_listas-min.py @@ -0,0 +1,22 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este programa crea una lista de los números, a continuación, debe imprimir +el número mínimo. + +Actualmente, sólo se construye una lista de números. Usted debe modificar el +programa para imprimir el número más pequeño de la lista, por ejemplo: + print('El número más pequeño es: %i' % algo) + +Existen varios métodos para hacer esto. El más sencillo es utilizar un método +descrito en la referencia de API para las listas, que encuentra el elemento +mínimo de una lista: + http://docs.python.org/2.7/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange +""" + +# Comience con una lista vacía, y añadir 5 números a la misma. +lista = [] +for i in range(5): + lista.append(int(raw_input('Escribe un número: '))) + +# Agregue el código aquí para imprimir el número más pequeño de la lista. diff --git a/exercises/es/8_listas-min_solucion.py b/exercises/es/8_listas-min_solucion.py new file mode 100644 index 0000000..627c346 --- /dev/null +++ b/exercises/es/8_listas-min_solucion.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este programa crea una lista de los números, a continuación, debe imprimir +el número mínimo. + +Actualmente, sólo se construye una lista de números. Usted debe modificar el +programa para imprimir el número más pequeño de la lista, por ejemplo: + print('El número más pequeño es: %i' % algo) + +Existen varios métodos para hacer esto. El más sencillo es utilizar un método +descrito en la referencia de API para las listas, que encuentra el elemento +mínimo de una lista: + http://docs.python.org/2.7/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange +""" + +# Comience con una lista vacía, y añadir 5 números a la misma. +lista = [] +for i in range(5): + lista.append(int(raw_input('Escribe un número: '))) + +# Imprimir el elemento mínimo de la lista, utilizando el método min(), que se +# describe aquí: +# http://docs.python.org/2.7/library/functions.html#min +print('El número más pequeño es: %i' % min(lista)) diff --git a/exercises/es/9_dicts.py b/exercises/es/9_dicts.py new file mode 100644 index 0000000..b24bc17 --- /dev/null +++ b/exercises/es/9_dicts.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este programa busca el color favorito del usario o les pregunta al respecto. + +Este programa tiene un diccionario que mapea los nombres de los usarios a sus +colores favoritos. Si el usario _no_ es en el diccionario, usted debe agregar +código que pide el usario de su color favorito, y luego agrega una asignación +para el diccionario de el nombre del usario a su color. +""" + +colores = { + 'Anna': 'rojo', + 'Jorge': 'verde', + 'Max': 'verde', + 'Felix': 'negro', + 'Ariel': 'amarillo', +} + +nombre = raw_input('Escribe su nombre: ') +if nombre in colores: + print('Su color favorito es: %s' % colores[nombre]) +# Agregue código para, si 'nombre' no está en el diccionario, pida al usario +# su color favorito y añadir una nueva entrada en el diccionario mapear su +# nombre a su color favorito. diff --git a/exercises/es/9_dicts_solucion.py b/exercises/es/9_dicts_solucion.py new file mode 100644 index 0000000..3107eaa --- /dev/null +++ b/exercises/es/9_dicts_solucion.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# coding=utf-8 + +"""Este programa busca el color favorito del usario o les pregunta al respecto. + +Este programa tiene un diccionario que mapea los nombres de los usarios a sus +colores favoritos. Si el usario _no_ es en el diccionario, usted debe agregar +código que pide el usario de su color favorito, y luego agrega una asignación +para el diccionario de el nombre del usario a su color. +""" + +colores = { + 'Anna': 'rojo', + 'Jorge': 'verde', + 'Max': 'verde', + 'Felix': 'negro', + 'Ariel': 'amarillo', +} + +nombre = raw_input('Escribe su nombre: ') +if nombre in colores: + print('Su color favorito es: %s' % colores[nombre]) +else: + color = raw_input('Escribe su color favorito: ') + colores[nombre] = color diff --git a/handout.tex b/handout.tex new file mode 100644 index 0000000..d1280c8 --- /dev/null +++ b/handout.tex @@ -0,0 +1,4 @@ +\documentclass[12pt,a4paper]{article} +\usepackage{a4wide} +\usepackage{beamerarticle} +\input{slides} diff --git a/presentation.tex b/presentation.tex new file mode 100644 index 0000000..fc41fa4 --- /dev/null +++ b/presentation.tex @@ -0,0 +1,2 @@ +\documentclass[ignorenonframetext]{beamer} +\input{slides} diff --git a/slides.tex b/slides.tex new file mode 100644 index 0000000..7090dba --- /dev/null +++ b/slides.tex @@ -0,0 +1,1005 @@ +% Designed to be included by presentation.tex or handout.tex. + +\usepackage[english,spanish]{babel} +\usepackage{ccicons} +\usepackage[T1]{fontenc} +\usepackage{graphicx} +\usepackage{hyperref} +\usepackage[utf8]{inputenc} +\usepackage{listings} +\usepackage{textcomp} +\usepackage{ifthen} + +% TeX function that generates the language commands. +% See: http://en.wikibooks.org/wiki/LaTeX/Internationalization#Multilingual_versions +\def\localedef#1#2{ +\ifthenelse{ \equal{\locale}{#1} }{ + \selectlanguage{#2} + \expandafter\def\csname#1\endcsname ##1{##1} + }{ + \expandafter\def\csname#1\endcsname ##1{} + } +} + +% Selected language. Can be placed anywhere before the language commands. +\providecommand\locale{es} + +%% Language commands. +\localedef{es}{spanish} +\localedef{en}{english} + +% Tango colours. +% Syntax highlighting colours from the Tango palette: http://pbunge.crimson.ch/2008/12/tango-syntax-highlighting/ +\definecolor{LightButter}{rgb}{0.98,0.91,0.31} +\definecolor{LightOrange}{rgb}{0.98,0.68,0.24} +\definecolor{LightChocolate}{rgb}{0.91,0.72,0.43} +\definecolor{LightChameleon}{rgb}{0.54,0.88,0.20} +\definecolor{LightSkyBlue}{rgb}{0.45,0.62,0.81} +\definecolor{LightPlum}{rgb}{0.68,0.50,0.66} +\definecolor{LightScarletRed}{rgb}{0.93,0.16,0.16} +\definecolor{Butter}{rgb}{0.93,0.86,0.25} +\definecolor{Orange}{rgb}{0.96,0.47,0.00} +\definecolor{Chocolate}{rgb}{0.75,0.49,0.07} +\definecolor{Chameleon}{rgb}{0.45,0.82,0.09} +\definecolor{SkyBlue}{rgb}{0.20,0.39,0.64} +\definecolor{Plum}{rgb}{0.46,0.31,0.48} +\definecolor{ScarletRed}{rgb}{0.80,0.00,0.00} +\definecolor{DarkButter}{rgb}{0.77,0.62,0.00} +\definecolor{DarkOrange}{rgb}{0.80,0.36,0.00} +\definecolor{DarkChocolate}{rgb}{0.56,0.35,0.01} +\definecolor{DarkChameleon}{rgb}{0.30,0.60,0.02} +\definecolor{DarkSkyBlue}{rgb}{0.12,0.29,0.53} +\definecolor{DarkPlum}{rgb}{0.36,0.21,0.40} +\definecolor{DarkScarletRed}{rgb}{0.64,0.00,0.00} +\definecolor{Aluminium1}{rgb}{0.93,0.93,0.92} +\definecolor{Aluminium2}{rgb}{0.82,0.84,0.81} +\definecolor{Aluminium3}{rgb}{0.73,0.74,0.71} +\definecolor{Aluminium4}{rgb}{0.53,0.54,0.52} +\definecolor{Aluminium5}{rgb}{0.33,0.34,0.32} +\definecolor{Aluminium6}{rgb}{0.18,0.20,0.21} + +% Listings setup. http://pbunge.crimson.ch/2008/12/tango-syntax-highlighting/ +\lstset{numbers=left,breaklines=true} +\lstset{ + keywordstyle=[1]{\color{DarkSkyBlue}}, + keywordstyle=[2]{\color{DarkScarletRed}}, + keywordstyle=[3]{\bfseries}, + keywordstyle=[4]{\color{DarkPlum}}, + keywordstyle=[5]{\color{SkyBlue}}, + commentstyle={\color{Aluminium4}}, + stringstyle={\color{Chocolate}}, + basicstyle={\ttfamily}, +} + +% Document properties. +\title{\en{Introduction to Python}\es{Introducción a Python}} +\author{Philip Withnall} +\date{\en{August 2013}\es{agosto 2013}} + + +\begin{document} + +\frame[plain]{ +\maketitle +\hfill +\begin{center}\ccbysa\end{center} +} + + +\section{\en{Introduction}\es{Introducción}} + +\en{Python is an interpreted programming language, and we're going to learn it +because most of Sugar is written in it, and it's one of the recommended ways to +develop new activities.} +\es{Python es un lenguaje de programación interpretado, y vamos a aprender +porque la mayoría de Sugar está escritorio en ella.} + +\en{Python is well-supported; so if you encounter a problem you can't solve, +googling the error message is often helpful.} +\es{Hay mucho apoyo disponible para Python; así que si usted tiene un problema +que no puede resolvar, google el mensaje de error.} + +\en{There are currently two versions of Python: Python 2 and Python 3. Python 3 +is the future of Python, but many projects, including Sugar, still use Python 2; +so we will use Python 2. Python 3 is mostly the same, with a few important +differences.} +\es{Hay actualmente dos versiones de Python: Python 2 y Python 3. Python 3 es +el futuro de Python, pero muchos proyectos, Sugar incluido, aún utilizan +Python 2; así que aprenderemos Python 2. Python 3 es prácticamente el mismo, +con algunas diferencias importantes.} + +\note{\en{Please ask questions throughout.} + \es{Por favor, hacer preguntas durante.}} + +\begin{frame}{Python} +\begin{itemize} + \item{\en{Interpreted programming language}\es{Lenguaje de programación interpretado}} + \item{\en{Used to write most of Sugar}\es{Utiliza para escribir la mayoría de Sugar}} + \item{\en{Popular and well-supported}\es{Popular y hay mucho apoyo}} + \item{\en{Two versions: Python 2 and Python 3}\es{Dos versiones: Python 2 y Python 3}} +\end{itemize} +\end{frame} + + +\section{\en{Course structure}\es{Estructura de capacitación}} + +\en{The best way to learn a programming language is to practice with it and write a +lot of programs. Therefore the lecturing (and my poor Spanish) is kept to a +minimum, and exercises are available for you to complete in your own time.} +\es{La mejor manera que aprender un lenguaje de programación es practicar con +ella y escribir una gran cantidad de programas. Por lo tanto la docencia (y +mi mal español) se mantiene al mínimos y hay ejercicios para usted para +completar en su propio tiempo.} + +\en{Teaching a programming language from scratch would normally take 16--32 hours in +a university, plus independent learning time. We don't have that much time, so +this training is compressed and many of the advanced features of Python have +been omitted. You are encouraged to learn about them yourselves once you're more +comfortable with the basics of Python.} +\es{La enseñanza de un lenguaje de programación desde cero toma normalmente 16 +a 32 horas en una universidad, más el tiempo de aprendizaje autónomo. No tenemos +mucho tiempo, así que esta capacitación se comprime y muchas de las funciones +avanzadas de Python tienen sido omitido. Todos ustedes están animamos a aprender +acerca de ellos cuando están más cómodo con los conceptos básicos de Python.} + +\en{There are some fantastic Python resources available online which you should +investigate in your spare time. The Spanish +``\href{http://docs.python.org.ar/tutorial/2/}{Tutorial de Python}'' +from Argentina is good, as is \href{http://pythonmonk.com/}{Python Monk} (only +available in English though).} +\es{Hay algunos recursos fantásticos para Python disponibles en línea que +ustedes deben en su tiempo libre. El español +``\href{http://docs.python.org.ar/tutorial/2/}{Tutorial de Python}'' de +Argentina es bueno, al igual que \href{http://pythonmonk.com/}{Python Monk} +(sólo disponible en inglés, aunque).} + +\begin{frame}{\en{Course structure}\es{Estructura de capacitación}} +\begin{itemize} + \item{\en{A couple of hours' lectures}\es{Clases para un par de horas}} + \item{\en{Exercises to complete in your own time} + \es{Ejercicios para su propio tiempo}} + \item{\en{More resources available}\es{Más recursos disponible}:\begin{itemize} + \item{\url{http://docs.python.org.ar/tutorial/2/}} + \item{\url{http://pythonmonk.com/}} + \end{itemize}} +\end{itemize} +\end{frame} + + +\section{\en{Development environment}\es{Entorno de desarrollo}} + +\en{While Python can run on Windows or Linux, Sugar activities can only be developed +on Linux, so we will use Linux. There are three options available: booting into +a Live USB image of Fedora, using a Fedora VM from Windows, or using VNC to +program on an XO from Windows.} +\es{Aunque Python se ejecutar en Windows o en Linux, actividades de Sugar sólo +se pueden desarrollar en Linux, así que vamos a utilizar Linux. Hay trés +opciones disponibles: arrancar en un medio vivo de Fedora, utilizar una maquína +virtual Fedora desde Windows, o utilizar VNC para programar en un XO desde +Windows.} + +\note{\en{I'll help you set up the VMs later.} + \es{Yo les ayudaré a configurar las maquínas virtuales después.}} + +\begin{frame}{\en{Development environment}\es{Entorno de desarrollo}} +\begin{itemize} + \item{\en{Develop on Linux}\es{Desarrollar en Linux}} + \item{\en{Necessary for Sugar development}\es{Necesario para desarrollo para Sugar}} + \item{\en{Fedora Live USB, VM or VNC to an XO}\es{Fedora medio vivo, VM o VNC a un XO}} +\end{itemize} +\end{frame} + + +\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} + + +\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 función no tiene parametros') + +def funcion_con_parametros(para1, para2): + print('Este función 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 número más pequeño 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 número más pequeño 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 vehículos están gravados por el número 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 + + +\section{\en{Miscellany}\es{Miscelánea}} + +\begin{frame}{\en{What's missing}\es{Temas no abarcados}} + % TODO: Things which haven't been lectured: exceptions, lambdas, licensing, tuples, file I/O + % Unicode, optional arguments, varargs, functional programming, list comprehensions, iterators, + % multiple inheritance, generators, standard library +\end{frame} + +\end{document} |