iniciacion python dia1
DESCRIPTION
aprende pythonTRANSCRIPT
![Page 1: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/1.jpg)
Wednesday, March 7, 2012
![Page 2: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/2.jpg)
Objetivo• ¡Aprender a programar en Python!
• No es lo mismo que “aprender a programar” a secas. No aspiramos a escribir “C en Python”.
• Pero 25 horas tan sólo nos permitirán echar un vistazo muy superficial a todo el lenguaje... en el mejor de los casos.
• Establecer unas bases sólidas para el aprendizaje por nuestra cuenta.
• La participación es fundamental.
Wednesday, March 7, 2012
![Page 3: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/3.jpg)
¿Y estos dos?• Instituto de Astrofísica de Andalucía (Granada)
• César Husillos (ALHAMBRA, minería de datos)
• Víctor Terrón (PANIC, reducción de datos)
• Algunos años ya programando en Pyhton
• Ésta es la segunda edición de este curso
Quizá imaginéis que nuestras fiestas son algo asíEn realidad, se parecen mucho más a esto
Wednesday, March 7, 2012
![Page 4: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/4.jpg)
Evaluaciones
• Agradeceremos enormemente cualquier sugerencia que nos hagáis sobre el temario, estilo y desarrollo del curso.
• Por cualquier medio; ya sea en persona, por correo electrónico o mediante amenazas por teléfono de madrugada.
• Si esperáis al viernes para decir algo podréis mejorar la experiencia de los que vengan detrás, pero no la vuestra. Hablad ahora o callad hasta la siguiente convocatoria.
Wednesday, March 7, 2012
![Page 5: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/5.jpg)
Evaluaciones
Vosotros
Nosotros
A Granada
Nosotros
Y ahora, explicado en el lenguaje del siglo XXI
Wednesday, March 7, 2012
![Page 6: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/6.jpg)
Pythoncomo calculadora
Wednesday, March 7, 2012
![Page 7: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/7.jpg)
Aritmética básica
>>> 2 + 24
Wednesday, March 7, 2012
![Page 8: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/8.jpg)
Aritmética básica
>>> 2.1 + 4.97.0
Wednesday, March 7, 2012
![Page 9: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/9.jpg)
Aritmética básica
>>> 8 - 53
Wednesday, March 7, 2012
![Page 10: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/10.jpg)
Aritmética básica
>>> 3 * 412
Wednesday, March 7, 2012
![Page 11: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/11.jpg)
Aritmética básica
>>> 9 / 33
Wednesday, March 7, 2012
![Page 12: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/12.jpg)
Aritmética básica
>>> 3 / 40
¿Por qué?Wednesday, March 7, 2012
![Page 13: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/13.jpg)
¡Estamos operando con
int / int = int3 / 4 = 0.75int(0.75) = 0
Wednesday, March 7, 2012
![Page 14: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/14.jpg)
Necesitamos números
float / float = floatfloat / int = floatint / float = float
Wednesday, March 7, 2012
![Page 15: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/15.jpg)
Pero esto no
>> float(3/4)float(int)float(0) = 0.0
Wednesday, March 7, 2012
![Page 16: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/16.jpg)
int() trunca...
>> int(0.49) = 0>> int(1.50) = 1>> int(2.9) = 2
Wednesday, March 7, 2012
![Page 17: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/17.jpg)
... y round() redondea
>> round(0.49) = 0 >> round(1.50) = 2>> round(2.9) = 3
Wednesday, March 7, 2012
![Page 18: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/18.jpg)
from _ _future_ _ import division
>> 1 / 4
0.25
>> 4 / 7
0.5714285714285714
Wednesday, March 7, 2012
![Page 19: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/19.jpg)
Python 2.7• Publicada en julio de 2010
• Última versión de la serie 2.x
• El futuro: Python 3000; nueva versión del lenguaje incompatible con 2.x. Mejorada, reorganizada, unificada. Última versión: Python 3.2 (febrero 2011)
• La mayor parte del código existente sigue siendo 2.x. De ahí que lo usemos en este curso. Y una vez podamos defendernos en Python 2.x, el salto a Py3K es trivial (y automatizable: herramienta 2to3)
• Python 2.7 está en modo de mantenimiento: sólo se arreglan bugs.
Wednesday, March 7, 2012
![Page 20: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/20.jpg)
from _ _future_ _ import division
• La división funciona como esperaríamos desde Python 3.0. Pero en realidad estaba implementado desde la versión 2.2 (diciembre de 2001), sólo que su uso era opcional.
• Permite una transición suave, a años vista.
• La máquina del tiempo delos creadores de Python.
Wednesday, March 7, 2012
![Page 21: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/21.jpg)
Aritmética básica
>>> 7 % 21
Wednesday, March 7, 2012
![Page 22: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/22.jpg)
Aritmética básica
>>> 10 ** 21024
Wednesday, March 7, 2012
![Page 23: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/23.jpg)
Aritmética básica
>>> (1 + 3) * 4 + 218
Wednesday, March 7, 2012
![Page 24: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/24.jpg)
Long integers
>> 1024 ** 2 ** 21099511627776L
¿Y esa L?
Wednesday, March 7, 2012
![Page 25: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/25.jpg)
Long integers
• Enteros normales utilizan al menos 32 bits (máximo entero positivo representable 2,147,483,647; en el caso de 64 bits: 9,223,372,036,854,775,807)
• Por encima de ese umbral Python usa automáticamente los long ints, limitados únicamente por la memoria disponible. En otras palabras: precisión ilimitada.
Wednesday, March 7, 2012
![Page 26: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/26.jpg)
Variables
>>> x = 8.5>>> x8.5
Wednesday, March 7, 2012
![Page 27: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/27.jpg)
Variables
>>> x = 1>>> y = 2>>> x + y3
Wednesday, March 7, 2012
![Page 28: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/28.jpg)
Variables
int x;
double y;
Wednesday, March 7, 2012
![Page 29: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/29.jpg)
Variables
int x;
x = 5.6;
Wednesday, March 7, 2012
![Page 30: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/30.jpg)
Variables
>>> x = 5>>> x + 27
>>> x = 6.6>>> x + 28.6
Wednesday, March 7, 2012
![Page 31: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/31.jpg)
Asignación múltiple
>>> x, y = 5, 3>>> x + y8
Wednesday, March 7, 2012
![Page 32: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/32.jpg)
Asignación múltiple
>>> x = y = 3>>> x3
Wednesday, March 7, 2012
![Page 33: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/33.jpg)
Variables no declaradas
>>> x = 1>>> x + yNameError: name 'y' is not defined
Wednesday, March 7, 2012
![Page 34: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/34.jpg)
Operadores de comparación
>>> 2 == 3False
Wednesday, March 7, 2012
![Page 35: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/35.jpg)
Operadores de comparación
>>> 2 != 3True
Wednesday, March 7, 2012
![Page 36: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/36.jpg)
Operadores de comparación
>>> 5 < 3False
Wednesday, March 7, 2012
![Page 37: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/37.jpg)
Operadores de comparación
>>> 5 > 5False
Wednesday, March 7, 2012
![Page 38: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/38.jpg)
Operadores de comparación
>>> 5 >= 5True
Wednesday, March 7, 2012
![Page 39: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/39.jpg)
Operadores lógicos
>>> not 2 > 3True
Wednesday, March 7, 2012
![Page 40: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/40.jpg)
Operadores lógicos
>>> x = 1.56>>> x >= 0 and x <= 1False
Wednesday, March 7, 2012
![Page 41: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/41.jpg)
Operadores lógicos
>>> x = 1.56>>> x >= 0 or x <= 1True
Wednesday, March 7, 2012
![Page 42: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/42.jpg)
Operadores lógicos
>>> x = 1.56>>> 0 <= x <= 1False
Wednesday, March 7, 2012
![Page 43: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/43.jpg)
Tipos de datos básicos
• int → entero• float → real• bool → lógico• string → texto
Wednesday, March 7, 2012
![Page 44: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/44.jpg)
Tipos de datos básicos
>>> x = 4.5>>> type(x)<type 'float'>
Wednesday, March 7, 2012
![Page 45: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/45.jpg)
Strings
• Cadenas de texto:“¡Hola mundo!”
• Comillas simples o dobles:‘¡Hola mundo!’
• Inmutables
Wednesday, March 7, 2012
![Page 46: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/46.jpg)
Strings
>>> nombre = ‘Sara’>>> nombre‘Sara’
Wednesday, March 7, 2012
![Page 47: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/47.jpg)
Strings
>>> frase = ‘Sara dijo “¡hola!”’>>> frase‘Sara dijo “¡hola!”’
Wednesday, March 7, 2012
![Page 48: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/48.jpg)
Strings
Secuencia de escape:“Sara dijo \“¡hola!\””
Wednesday, March 7, 2012
![Page 49: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/49.jpg)
Strings
Triple entrecomillado: “““ Sara dijo “¡hola!” ”””
Wednesday, March 7, 2012
![Page 50: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/50.jpg)
Slices
a[index] Devuelve el index-1 elemento
a = “Abstulit qui dedit”a[0] = “A”a[6] = “i”a[-1] = “t”
Wednesday, March 7, 2012
![Page 51: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/51.jpg)
El primer elemento tiene índice = 0
Wednesday, March 7, 2012
![Page 52: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/52.jpg)
Edsger W. Dijkstra
“Why numbering should start at zero” (1982)
Wednesday, March 7, 2012
![Page 53: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/53.jpg)
Para representar la secuencia 1, 2, ..., 10 tenemos cuatro posibilidades:
a) 1 ≤ i < 11b) 0 < i ≤ 10c) 1 ≤ i ≤ 10d) 0 < i < 11
Tanto a) como b) tienen la ventaja de que la diferencia entre los límites del intervalo (11-1 y 10-0) es igual al
número de elementos de éste
b) nos obliga a utilizar un número no natural (cero) para determinar un intervalo de números naturales. Poco
elegante.
Wednesday, March 7, 2012
![Page 54: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/54.jpg)
Para representar una secuencia de N elementos, utilizando la nomenclatura a), tenemos dos opciones:
a) 1 ≤ i < N+1b) 0 ≤ i < N
La opción b) es más simple e intuitiva: el límite superior nos indica directamente el número de elementos en el intervalo
Wednesday, March 7, 2012
![Page 55: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/55.jpg)
Slices
a[start:end] Elementos desde start hasta end-1
a = “Alea jacta est”a[0:10] = “Alea jacta”
a[5:10] = “jacta”a[5:6] = “j”a[5:5] = “”
Wednesday, March 7, 2012
![Page 56: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/56.jpg)
Slices
a[start:] Elementos desde start hasta el final
a = “Fabricando fit faber”a[12:] = “fit faber”
a[-5:] = “faber”
Wednesday, March 7, 2012
![Page 57: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/57.jpg)
Slices
a[:end] Elementos desde el comienzo hasta end-1
a = “In vino veritas”a[:2] = “In”
a[:8] = “In vino”a[:-5] = “In vino ve”
Wednesday, March 7, 2012
![Page 58: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/58.jpg)
Slices
a[start:end:step] De start a end de step en step elementos
a = “Is fecit, cui prodest”a[::2] = “I ei,cipoet”
a[:12:3] = “Ifi ”a[::-1] = “tsedorp iuc ,ticef sI”
Wednesday, March 7, 2012
![Page 59: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/59.jpg)
Inmutables
>>> nombre = “Sara”
>>> nombre[0] = “M”
TypeError: 'str' objectdoes not support item assignment
Wednesday, March 7, 2012
![Page 60: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/60.jpg)
Inmutables
>>> nombre = “Sara”
>>> nombre = “Mara”
>>> nombre
‘Mara’
Wednesday, March 7, 2012
![Page 61: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/61.jpg)
Concatenación
>> nombre = “Sara”
>> nombre = “M” + nombre[1:]
>> nombre
‘Mara’
Wednesday, March 7, 2012
![Page 62: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/62.jpg)
Subcadenas
>>> “ere” in “sapere aude”
True
Wednesday, March 7, 2012
![Page 63: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/63.jpg)
Subcadenas
>>> “sapere aude”.find(“ere”)
3
La subcadena existe y empieza en el elemento 3 (es decir, el cuarto)
Wednesday, March 7, 2012
![Page 64: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/64.jpg)
Subcadenas
>>> “flux” in “et veritas”
False
Wednesday, March 7, 2012
![Page 65: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/65.jpg)
Subcadenas
>>> “et veritas”.find(“flux”)
-1
La subcadena no existe
Wednesday, March 7, 2012
![Page 66: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/66.jpg)
Tamaño
>>> len(“victoria aut mors”)
17
Wednesday, March 7, 2012
![Page 67: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/67.jpg)
Tamaño
>>> comic = “V de Vendetta”
>>> len(comic)
13
Wednesday, March 7, 2012
![Page 68: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/68.jpg)
Mayúsculas
>>> “hoygan”.upper()
“HOYGAN”
Wednesday, March 7, 2012
![Page 69: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/69.jpg)
Minúsculas
>>> vocales = “AEIOU”
>>> vocales.lower()
“aeiou”
Wednesday, March 7, 2012
![Page 70: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/70.jpg)
Eliminando espacios
>>> planeta = “ Saturno”
>>> planeta.lstrip()
“Saturno”
Wednesday, March 7, 2012
![Page 71: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/71.jpg)
Eliminando espacios
>>> lugar = “En el Sol ”
>>> print lugar.rstrip(), “hace calor”
En el Sol hace calor
Wednesday, March 7, 2012
![Page 72: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/72.jpg)
Eliminando espacios
>>> apellido = “ Lee ”
>>> print “Bruce”, apellido.strip(), “Jr.”
Bruce Lee Jr.
Wednesday, March 7, 2012
![Page 73: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/73.jpg)
EjerciciosManipulación de cadenas utilizando el
cadena = “Cabeza grande, ojos hermosos”
1. ¿El tamaño de la cadena?2. Los primeros cinco caracteres de la cadena3. Los siete últimos caracteres.4. De los cinco primeros caracteres, los que ocupan posiciones pares.5. De los últimos trece caracteres, los de posiciones impares6. En mayúscula, los caracteres en posiciones múltiplo de tres7. De dos en dos, del caracter en la posición 4 al de la 178. ¿Está el caracter “x” en la cadena?9. ¿Y “o”, en mayúscula o minúscula?
Wednesday, March 7, 2012
![Page 74: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/74.jpg)
Módulos
Instrucciones almacenadas en un fichero y ejecutadas por el
intérprete de Python
Wednesday, March 7, 2012
![Page 75: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/75.jpg)
Módulos
x = 4
y = 5
x ** (y + 1)
Wednesday, March 7, 2012
![Page 76: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/76.jpg)
Módulos
python fichero.py
El nombre del módulo es fichero(sin la extensión .py)
Wednesday, March 7, 2012
![Page 77: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/77.jpg)
Módulos
chmod +x fichero.py
Hacemos el fichero ejecutable
Wednesday, March 7, 2012
![Page 78: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/78.jpg)
Módulos
#! /usr/bin/env python
Primera línea del módulo: especifica que debe utilizarse Python para ejecutar el código
contenido en el fichero
Wednesday, March 7, 2012
![Page 79: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/79.jpg)
Módulos
udit-d41:~ vterron$ python ejemplo.py
udit-d41:~ vterron$
Wednesday, March 7, 2012
![Page 80: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/80.jpg)
Módulos
udit-d41:~ vterron$ ./ejemplo.py
udit-d41:~ vterron$
Wednesday, March 7, 2012
![Page 81: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/81.jpg)
>>> print “Abre las puertas, HAL”
‘Abre las puertas, HAL”
Wednesday, March 7, 2012
![Page 82: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/82.jpg)
>>> print “Lo siento,”
>>> print “Dave”
‘Lo siento,’
‘Dave’
Añade salto de línea al final
Wednesday, March 7, 2012
![Page 83: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/83.jpg)
>>> print “Me temo que”, “no puedo”
‘Me temo que no puedo’
Inserta espacio entre las cadenas mostradas por pantalla
Wednesday, March 7, 2012
![Page 84: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/84.jpg)
>>> x = 2
>>> y = 3
>>> print x, “^”, y, “=”, 2**3
2 ^ 3 = 8
Wednesday, March 7, 2012
![Page 85: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/85.jpg)
Formateo de cadenas
• Pero print sólo nos proporciona una funcionalidad básica de manipulación de cadenas; para un control más avanzado necesitamos necesitamos formatear la cadena.
• Idéntico al antediluviano y universal printf, presente en cualquier lenguaje de programación digno de ese hombre.
• Nos da control absoluto de la representación por pantalla de la información. Entre otro, podemos especificar tipo, precisión, signo, alineamiento, entre otros.
Wednesday, March 7, 2012
![Page 86: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/86.jpg)
Formateo de cadenas
>>> print “Numero: %d” % 42
Número: 42
>>> print “Pi: %f” % 3.1415927
Pi: 3.141593
>>> print “Pi: %.3f” % 3.1415927
Pi: 3.142
Wednesday, March 7, 2012
![Page 87: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/87.jpg)
Formateo de cadenas
>>> print “%d + %d = %d” % (5, 3, 8)
5 + 3 = 8
>>> b = 10.4
>>> e = 2
>>> print “%f ** %d = %.2d” % (b, e, b ** e)
10.400000 ** 2 = 108.16
Wednesday, March 7, 2012
![Page 88: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/88.jpg)
Comentarios
#A partir del primer # y hasta el final de la
Wednesday, March 7, 2012
![Page 89: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/89.jpg)
Comentarios
>>> x = 2
>>> x = x + 1 # incrementa x en uno
>>> x
3
Wednesday, March 7, 2012
![Page 90: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/90.jpg)
Listas
• Serie de elementos separados por comas, encerrados entre corchetes.
• Los elementos pueden ser de distinto tipo
• Dinámicas: número variable de elementos
• Mutables
Wednesday, March 7, 2012
![Page 91: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/91.jpg)
Listas
>>> v = [1, 2, 3]
>>> v
[1, 2, 3]
Wednesday, March 7, 2012
![Page 92: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/92.jpg)
Listas
>>> v = [1, 2.0, “tres”]
>>> print v[1]
2.0
Wednesday, March 7, 2012
![Page 93: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/93.jpg)
Listas
>>> v = []
>>> v
[]
Wednesday, March 7, 2012
![Page 94: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/94.jpg)
Asignación
>>> v = [4, 7, 3, 8]
>>> v[-1] = 0
>>> v
[4, 7, 3, 0]
Wednesday, March 7, 2012
![Page 95: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/95.jpg)
Tamaño
>>> v = [1, 2.0, “tres”]
>>> len(v)
3
Wednesday, March 7, 2012
![Page 96: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/96.jpg)
Inserción
>>> v = [1, 3, 4]
>>> v.append(5)
>>> v
[1, 2, 3, 5]
Wednesday, March 7, 2012
![Page 97: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/97.jpg)
Inserción
>>> v = [1, 3, 4]
>>> v.insert(9, 2)
>>> v
[1, 3, 9, 4]
Añade el elemento 9 en la posición de index = 2
Wednesday, March 7, 2012
![Page 98: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/98.jpg)
Eliminación
>>> v = [1, 3, 4]
>>> v.remove(3)
>>> v
[1, 4]
Borrado por valor
Wednesday, March 7, 2012
![Page 99: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/99.jpg)
Eliminación
>>> v = [9, 5, 8, 5, 9]
>>> del v[3]
>>> v
[9, 5, 8, 9]
Borrado por posición
Wednesday, March 7, 2012
![Page 100: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/100.jpg)
Búsqueda
>>> v = [7, 0, 7]
>>> 7 in v
True
Wednesday, March 7, 2012
![Page 101: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/101.jpg)
Búsqueda
>>> v = [7, 0, 7]
>>> v.index(7)
0
Wednesday, March 7, 2012
![Page 102: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/102.jpg)
Búsqueda
>>> v = [7, 0, 7]>>> 3 in vFalse
Wednesday, March 7, 2012
![Page 103: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/103.jpg)
Búsqueda
>>> v = [7, 0, 7]>>> 8 not in vTrue
Wednesday, March 7, 2012
![Page 104: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/104.jpg)
Búsqueda
>>> v = [7, 0, 7]
>>> v.index(3)
ValueError: list.index(x): x not in list
Wednesday, March 7, 2012
![Page 105: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/105.jpg)
Concatenación
>>> [1, 2, 3] + [9, 8]
[1, 2, 3, 9, 8]
Wednesday, March 7, 2012
![Page 106: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/106.jpg)
Concatenación
>>> x = [1, 2, 3]
>>> x.append([9, 8])
>>> x
[1, 2, 3, [9, 8]]El cuarto elemento es ahora una lista
Wednesday, March 7, 2012
![Page 107: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/107.jpg)
Máximo
>>> max([7, 2, 5])7
Wednesday, March 7, 2012
![Page 108: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/108.jpg)
Mínimo
>>> x = [7, 2, 5]>>> min(x)2
Wednesday, March 7, 2012
![Page 109: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/109.jpg)
Sumatorio
>>> sum([7, 2, 5])14
Wednesday, March 7, 2012
![Page 110: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/110.jpg)
Listas vacías
>>> x = []>>> len(x)0
Wednesday, March 7, 2012
![Page 111: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/111.jpg)
Listas vacías
>>> x = []>>> bool(x)False
Las listas vacías evalúan a False
Wednesday, March 7, 2012
![Page 112: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/112.jpg)
EjerciciosManipulación de listas utilizando el
lista = [“primero”, 2, “3.5”, 4.0, “ultimo”]
1. ¿El tamaño de la lista?2. El tamaño de la lista multiplicado por su segundo elemento3. El producto del segundo elemento de la lista por el tercero4. ¿Está 2 en la lista? ¿Y 2.0?5. Eliminar el primer elemento de la lista6. Eliminar ahora los dos últimos elementos simultaneamente7. ¿Está la lista vacía?8. Añadir el elemento “nuevo ultimo” a la lista.
Wednesday, March 7, 2012
![Page 113: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/113.jpg)
Entrada de datos
raw_input(mensaje)
• Imprime mensaje por pantalla
• Devuelve entrada en un string
Wednesday, March 7, 2012
![Page 114: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/114.jpg)
Entrada de datos
>>> persona = raw_input(“Nombre: ”)
Nombre:
>>> print “Bienvenido,”, persona
Bienvenido, Mr. Marshall
Mr. Marshall
Wednesday, March 7, 2012
![Page 115: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/115.jpg)
Entrada de datos
>>> x = raw_input(“x: ”)
x:
>>> print 2*x
5757
57
Wednesday, March 7, 2012
![Page 116: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/116.jpg)
Entrada de datos
• raw_input() siempre devuelve una cadena de texto
• Necesitamos hacer una conversión al tipo de dato que necesitamos
Wednesday, March 7, 2012
![Page 117: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/117.jpg)
Entrada de datos
>>> 3 * “adios”
“adiosadiosadios”
int * string concatena string int veces
De vuelta al ejemplo anterior...
Wednesday, March 7, 2012
![Page 118: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/118.jpg)
Entrada de datos
>>> x = int(raw_input(“x: ”))
x:
>>> print 2*x
114
57
Wednesday, March 7, 2012
![Page 119: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/119.jpg)
Entrada de datos
input(mensaje)
• También imprime mensaje por pantalla
• Pero la entrada es interpretada como una expresión de código Python
Wednesday, March 7, 2012
![Page 120: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/120.jpg)
Entrada de datos
>>> numeros = input(“Lista: ”)
Nombre:
>>> del numeros[-1]
>>> numeros
[7, 8]
[7, 8, 9]
Wednesday, March 7, 2012
![Page 121: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/121.jpg)
Entrada de datos
>>> x = [1, 2]
>>> x.append(input())
>>> x
[1, 2, 18]
18
Wednesday, March 7, 2012
![Page 122: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/122.jpg)
Entrada de datos
>>> x = [7, 8]
>>> x.append(input(“elemento: ”))
elemento:
NameError: name 'y' is not defined
y
La mayor parte del tiempo necesitamos raw_input
Wednesday, March 7, 2012
![Page 123: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/123.jpg)
Estructuras de control
if
for
while
Necesitamos modificar el flujo de ejecución del programa en función de los datos
Wednesday, March 7, 2012
![Page 124: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/124.jpg)
if
>>> if 2 > 1:
... print “obviamente”
...
obviamente
Evalúa una condición y ejecuta un bloque de instrucciones si es verdadera
Wednesday, March 7, 2012
![Page 125: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/125.jpg)
Bloque
• Un bloque es un conjunto de instrucciones que se ejecutan secuencialmente
• En este caso en particular, son aquellas instrucciones ejecutadas cuando la condición es verdadera
• Python utiliza el indentado para reconocer las líneas que forman un bloque de instrucciones
Wednesday, March 7, 2012
![Page 126: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/126.jpg)
if - else
>>> if 7 % 2 == 0:
... print “es par”
... else:
... print “no par”
...
“no par”
Evalúa una condición y ejecuta un bloque de instrucciones (bloque-if) si es verdadera. Si no lo es, ejecuta el otro bloque (bloque-else)
Wednesday, March 7, 2012
![Page 127: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/127.jpg)
if - elif - else
• Para elegir entre más de dos opciones
• Python ignora las demás condiciones en cuando una se cumple
• Funcionalidad similar al switch de C/C++
Wednesday, March 7, 2012
![Page 128: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/128.jpg)
if - elif - else>>> if 2 < 0:
... print “negativo!”
... elif 2 == 0:
... print “nada!”
... else:
... print “positivo!”
...
“positivo!”
Wednesday, March 7, 2012
![Page 129: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/129.jpg)
for
>>> for i in [1, 2, 3]:
... print i
...
1
2
3
Itera sobre los elementos de una secuencia
Wednesday, March 7, 2012
![Page 130: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/130.jpg)
for
• El cuerpo del bloque (bloque-for) se ejecuta tantas veces como elementos tenga la secuencia (por ejemplo, caracteres en un string)
• Usado para repetir un bloque de instrucciones para los que una variable toma diferentes valores.
• ¿Cómo ejecutamos un bloque n veces?
Wednesday, March 7, 2012
![Page 131: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/131.jpg)
range(n)
>> range(7)
[0, 1, 2, 3, 4, 5, 6]
Genera una lista de n valores [0, 1, 2 ... n-1]
Wednesday, March 7, 2012
![Page 132: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/132.jpg)
range(start, n)
>> range(3, 7)
[3, 4, 5, 6]
Genera la lista [start, start+1, ... n-1]
Wednesday, March 7, 2012
![Page 133: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/133.jpg)
range(start, n, step)
>>> range(1, 11, 2)
[1, 3, 5, 7, 9]
Genera la lista [start, start+step, ... n-1]
Wednesday, March 7, 2012
![Page 134: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/134.jpg)
for
>>> for i in range(3):
... print “hola”
...
hola
hola
hola
Wednesday, March 7, 2012
![Page 135: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/135.jpg)
for (en C++)
for (int i = 0 ; i < 10 ; i++)
cout << i << endl;
Wednesday, March 7, 2012
![Page 136: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/136.jpg)
for
for i in range(10):
print iNo utilizamos condiciones de inicio, parada e incremento, sino que
especificamos claramente qué elementos se utilizan
Más expresivo y seguro
Wednesday, March 7, 2012
![Page 137: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/137.jpg)
for
>>> for letra in “Sara”:
... print letra
...
S
a
r
a
Wednesday, March 7, 2012
![Page 138: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/138.jpg)
¿Y si dentro del bucle necesitamos conocer el índice del elemento?
for
>>> numeros = [2, 4, 5]
index 0 -> 2
index 1 -> 4
index 2 -> 5
Wednesday, March 7, 2012
![Page 139: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/139.jpg)
for
>>> numeros = [2, 4, 5]
>>> for i in range(len(numeros)):
... print i, “->”, numeros[i]
Wednesday, March 7, 2012
![Page 140: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/140.jpg)
enumerate(sec)
>>> for i, num in enumerate([1, 2, 3]):
... print i, “->”, num
Permite iterar simultáneamente sobre el índice y sobre el elemento de una secuencia
Wednesday, March 7, 2012
![Page 141: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/141.jpg)
while
>>> x = 1
>>> while x < 10:
... x = x + 1
... print x
...
10
Ejecuta el bucle mientras la condición sea cierta
Wednesday, March 7, 2012
![Page 142: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/142.jpg)
while
>>> x = 5
>>> factorial = 1
>>> while x > 0:
... factorial = factorial * x
... x = x - 1
... print factorial
...
120
Wednesday, March 7, 2012
![Page 143: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/143.jpg)
while
>>> x = 0
>>> while True:
... x = x + 1
...
Wednesday, March 7, 2012
![Page 144: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/144.jpg)
¿Y si necesitamos salir del bucle?
¿GOTO?
Wednesday, March 7, 2012
![Page 145: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/145.jpg)
Edsger W. Dijkstra“Go To Statement Considered Harmful,” (1968)
Wednesday, March 7, 2012
![Page 146: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/146.jpg)
Wednesday, March 7, 2012
![Page 147: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/147.jpg)
break
>>> for i in [1, 2, 3]:
... if i % 2 == 0:
... break
... print i
...
2
Abandona el bucle inmediatamente
Wednesday, March 7, 2012
![Page 148: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/148.jpg)
break
>>> x = 15
>>> while True:
... if x % 9 == 0:
... print x
... break
... x = x + 1
...
18
Wednesday, March 7, 2012
![Page 149: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/149.jpg)
continue
>>> for i in [1, 2, 3]:
... if i % 2 == 0:
... continue
... print i
...
1
3
Salta inmediatamente a la siguiente iteración
Wednesday, March 7, 2012
![Page 150: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/150.jpg)
continue
>>> while True:
... x = int(raw_input())
... if not x % 2 == 0:
... continue
... print “es par!”
Wednesday, March 7, 2012
![Page 151: Iniciacion Python Dia1](https://reader030.vdocuments.site/reader030/viewer/2022012318/577c7cbd1a28abe0549bd4f6/html5/thumbnails/151.jpg)
http://www.iaa.es/python/ejercicios
Ejerciciosif, for, while y range()
Wednesday, March 7, 2012