Aprendiendo a programar con Python - PowerPoint PPT Presentation

About This Presentation
Title:

Aprendiendo a programar con Python

Description:

Aprendiendo a programar con Python Curso en 8 horas Qu es un programa? Un programa es un conjunto de instrucciones dise adas para ordenar a la computadora a ... – PowerPoint PPT presentation

Number of Views:4941
Avg rating:3.0/5.0
Slides: 75
Provided by: genesdigi
Category:

less

Transcript and Presenter's Notes

Title: Aprendiendo a programar con Python


1
Aprendiendo a programar con Python
  • Curso en 8 horas

2
Qué es un programa?
  • Un programa es un conjunto de instrucciones
    diseñadas para ordenar a la computadora a hacer
    algo.
  • Es similar a una receta de cocina, que consiste
    en una lista de ingredientes e instrucciones paso
    a paso donde se usan dichos ingredientes.

3
Receta
  • Tomates fritos.
  •  
  • Ingredientes
  • 1 Tomate
  • 200 gr Queso
  • 1 huevo
  • 100 gr Pan rallado
  • Aceite
  • Instrucciones
  • Cortar el tomate en 2 rodajas. Poner queso entre
    las rodajas, mezclar con huevo, cubrir con pan
    rallado y freir en aceite hasta que se dore.

4
Primer programa
Código
seq1 'Hola' seq2 ' mundo!' total seq1
seq2 print total
Resultado
Hola mundo!
5
Niveles de abstracción
6
Ejemplo bajo y alto nivel
Bajo nivel (código máquina x86) 8B542408
83FA0077 06B80000 0000C383 FA027706 B8010000
00C353BB 01000000 B9010000 008D0419 83FA0376
078BD98B C84AEBF1 5BC3 Alto nivel (Python) def
fib(n) a, b 0, 1 for i in range(n)
a, b b, a b return a
7
Ejemplo bajo y alto nivel
  • Bajo nivel (bytecode de Python)
  • 0 LOAD_CONST 1 ('Hello, world!')
  • 3 PRINT_ITEM
  • 4 PRINT_NEWLINE
  • Alto nivel (Python)
  • print 'Hello, world!'

8
Compilación
Traducción desde el código fuente a
instrucciones ejecutables
Gráfico CC-SA-NC 3.0 Fuentehttps//www.cs.utk.ed
u/help/doku.php?idcompilec
9
Consecuencias de la compilación
  • Tiempo de compilación
  • Aceleración en la ejecución del software
  • Software dependiente de una plataforma

10
Paradigmas de programación
  • Procedural / Estructurada C, Pascal, Perl.
  • Orientada a Objetos C, Java.
  • Lógico Prolog, Lisp.

11
Programación procedural
  • Los programas tienen rutinas o funciones con los
    pasos a seguir.
  • Beneficios
  • Estructurar el código en bloques para
    reutilizarlos.
  • Seguimiento de la lógica del programa (sin saltos
    a posiciones arbitrarias, aka go to).

12
POO (OOP)
Se usan objetos para diseñar los programas. Los
objetos son estructuras de datos que tienen
propiedades (caracteristicas) y métodos
(acciones) que le son propios.
  • Caracteristicas
  • Encapsulación
  • Abstracción de datos
  • Polimorfismo
  • Herencia

13
Python Especificación e implementación
  • Especificación Definición de caracteristicas del
    lenguaje
  • Implementación Programa que cumple con dicha
    especificación. Ej. CPython, IronPython, Jython

14
Características de Python
  • Fácil de aprender y de programar
  • Fácil de leer (similar a pseudocódigo)
  • Interpretado (Rápido para programar)
  • Datos de alto nivel (listas, diccionarios, sets,
    etc)
  • Libre y gratuito
  • Multiplataforma (Win, Linux y Mac)
  • Pilas incluidas
  • Cantidad de bibliotecas con funciones extras
  • Comunidad

15
Leer archivo y cargarlo en arrayVB
  • Dim i, j, Array_Used As Integer
  • Dim MyArray() As String
  • Dim InBuffer, Temp As String
  • Array_Used 0
  • ReDim MyArray(50)
  • 'open a text file here . . .
  • Do While Not EOF(file_no)
  • Line Input file_no, MyArray(Array_Used)
  • Array_Used Array_Used 1
  • If Array_Used UBound(MyArray) Then
  • ReDim Preserve MyArray(UBound(MyArray)
    50)
  • End If
  • Loop
  • 'simple bubble sort
  • For i Array_Used - 1 To 0 Step -1
  • For j 1 To i
  • If MyArray(j - 1) gt MyArray(j) Then
  • 'swap
  • Temp MyArray(j - 1)

16
Leer archivo y cargarlo en listaPython
  • Abrir un archivo de texto . . .
  • file_object open(FILENAME)
  • Leer todas las lineas del texto en una lista
    (similar a un array)
  • lista file_object.readlines()
  • Ordenar la lista
  • lista.sort()

17
Las pilas puestas
  • La biblioteca estándar ayuda con...
  • Servicios del sistema, fecha y hora, subprocesos,
    sockets, i18n y l10n, base de datos, threads,
    formatos zip, bzip2, gzip, expresiones regulares,
    XML (DOM y SAX), Unicode, SGML, HTML, XHTML,
    email, manejo asincrónico de sockets, clientes
    HTTP, FTP, SMTP, NNTP, POP3, IMAP4, servidores
    HTTP, SMTP, debugger, random, curses, logging,
    compilador, decompilador, CSV, análisis
    lexicográfico, interfaz gráfica incorporada,
    matemática real y compleja, criptografía,
    introspección, unit testing, doc testing, etc.,
    etc...

18
Bibliotecas externas
  • Bases de datos
  • MySQL, PostgresSQL, MS SQL, Informix, DB/2,
    SQLite
  • Interfaces gráficas
  • Qt, GTK, win32, wxWidgets, Cairo
  • Frameworks Web
  • Django, Turbogears, Zope, Plone, webpy
  • Y un montón más de temas...
  • Biopython Manejo de secuencias genéticas
  • PIL para trabajar con imágenes
  • PyGame juegos, presentaciones, gráficos
  • SymPy matemática simbólica
  • Numpy calculos de alta performance
  • ...

19
Mas pilas...
  • Bases de datos
  • MySQL, PostgresSQL, MS SQL, Informix, DB/2,
    SQLite
  • Interfaces gráficas
  • Qt, GTK, win32, wxWidgets, Cairo
  • Frameworks Web
  • Django, Turbogears, Zope, Plone, webpy
  • Y un montón más de temas...
  • Biopython Manejo de secuencias genéticas
  • PIL para trabajar con imágenes
  • PyGame juegos, presentaciones, gráficos
  • SymPy matemática simbólica
  • Numpy calculos de alta performance
  • ...

20
CPython e IDLE
21
Práctica en intérprete interactivo
gtgtgt 22 4 gtgtgt _4 16 gtgtgt 10/3 3 gtgtgt
float(10)/3 3.3333333333333335 gtgtgt
10.0/3 3.3333333333333335 gtgtgt int(2.1) 2 gtgtgt
int(2.9) 2 gtgtgt round(2.9) 3.0 gtgtgt
int(round(2.9)) 3 gtgtgt round(2.932224,2) 2.93000000
00000002 gtgtgt print round(2.932224,2) 2.93
22
Práctica en intérprete interactivo II
gtgtgt "hola" " mundo!" 'hola mundo!' gtgtgt ("hola"
" mundo!").upper() 'HOLA MUNDO!' gtgtgt '
123'.strip() '123' gtgtgt 123.strip() File
"ltstdingt", line 1 123.strip()
SyntaxError invalid syntax gtgtgt gtgtgt
str(123) '123' gtgtgt int('123') 123
23
Help incorporado
gtgtgt help() Welcome to Python 2.6! This is the
online help utility. If this is your first time
using Python, you should definitely check out the
tutorial on the Internet at http//docs.python.org
/tutorial/. Enter the name of any module,
keyword, or topic to get help on writing Python
programs and using Python modules. To quit this
help utility and return to the interpreter, just
type "quit". To get a list of available modules,
keywords, or topics, type "modules", "keywords",
or "topics". Each module also comes with a
one-line summary of what it does to list the
modules whose summaries contain a given word such
as "spam", type "modules spam".
24
Tipo de datos Primarios y derivados
Primarios (o primitivos) No necesitan de otro
tipo de datos, como numericos (int, float,
decimal, complex) y str (cadenas). Derivados
Agrupan a alguno de los anteriores, como listas,
diccionarios, tuplas, etc. Se pueden
subclasificar según distintos parámetros Ordenad
os (o secuenciales) Desordenados Mutables
Inmutables
25
gtgtgt type(5) lttype 'int'gt gtgtgt type(5.0) lttype
'float'gt gtgtgt type(5 5.0) lttype 'float'gt gtgtgt 5
5.0 10.0 gtgtgt type(23j) lttype 'complex'gt gtgtgt
(23j).real 2.0 gtgtgt (23j).imag 3.0 gtgtgt
type('Hola!') lttype 'str'gt gtgtgt 'hola' '
mundo!' 'hola mundo!' gtgtgt 'hela' 2 Traceback
(most recent call last) File "ltpyshell32gt",
line 1, in ltmodulegt 'hela' 2 TypeError
cannot concatenate 'str' and 'int' objects gtgtgt
'hela' str(2) 'hela2'
26
Decimal El problema de los números
flotantes gtgtgt 0.1 0.1 0.1 -
0.3 5.5511151231257827e-17 Una manera de evitar
esto gtgtgt round(0.1 0.1 0.1 -
0.3,1) 0.0 Alternativamente, para no perder
precisión gtgtgt from decimal import Decimal gtgtgt
Decimal('0.1') Decimal('0.1') Decimal('0.1')
- Decimal('0.3') Decimal('0.0') Mas
información http//docs.python.org/library/decima
l.html
27
str (String o Cadenas) gtgtgt 'Hola mundo!' 'Hola
mundo!' gtgtgt a'Hola mundo!' gtgtgt len(a) 11 gtgtgt
a.lower() 'hola mundo!' gtgtgt a.count('o') 2 gtgtgt
a.find('H') 0 gtgtgt a.find('mundo') 5 gtgtgt
a.find('e') -1 gtgtgt a.index(' ') 4 gtgtgt
a.index('e') Traceback (most recent call last)
File "ltpyshell52gt", line 1, in ltmodulegt
a.index('e') ValueError substring not found gtgtgt
a.split(' ') 'Hola', 'mundo!' http//docs.pytho
n.org/library/string.html
28
Datos ordenados Listas
gtgtgt mi_lista 1,2,3 gtgtgt mi_lista.append(5) gtgtgt
mi_lista 1, 2, 3, 5 gtgtgt mi_lista.pop() 5 gtgtgt
mi_lista 1, 2, 3 gtgtgt mi_lista 4 1, 2, 3,
4 gtgtgt mi_lista 1, 2, 3 gtgtgt mi_lista mi_lista
4 gtgtgt mi_lista 1, 2, 3, 4 gtgtgt
mi_lista.extend(5,6) gtgtgt mi_lista 1, 2, 3, 4,
5, 6 gtgtgt mi_lista0 1 gtgtgt mi_lista3 4 gtgtgt
mi_lista35 4, 5 gtgtgt mi_lista-2 5
29
Mas sobre listas
gtgtgt variada 'boga', 'cornalito',
'tararira' gtgtgt variada2 'tararira' gtgtgt
variada228 'rarira' gtgtgt variada22 'rarir
a' gtgtgt variada.append('pulpo') gtgtgt
variada 'boga', 'cornalito', 'tararira',
'pulpo' gtgtgt variada.remove('cornalito') gtgtgt
variada 'boga', 'tararira', 'pulpo' gtgtgt
variada.sort() gtgtgt variada 'boga', 'pulpo',
'tararira' gtgtgt variada.index('pulpo') 1 gtgtgt
variada.index('pulpa') Traceback (most recent
call last) File "ltpyshell33gt", line 1, in
ltmodulegt variada.index('pulpa') ValueError
list.index(x) x not in list gtgtgt 'pulpo' in
variada True gtgtgt 'pulpa' in variada False
30
List comprehesion
gtgtgt vec 2, 4, 6 gtgtgt 3x for x in vec 6,
12, 18 gtgtgt 3x for x in vec if x gt 3 12,
18 gtgtgt 3x for x in vec if x lt 2 gtgtgt
x,x2 for x in vec 2, 4, 4, 16, 6, 36
31
Tuplas Similares a listas, aunque inmutables.
gtgtgt t1 ('sgn1545',5,45) gtgtgt t10 'sgn1545' gtgtgt
5 in t1 True gtgtgt t1.index(45) 2 gtgtgt
t1.count(45) 1 gtgtgt t1.append(4) Traceback (most
recent call last) File "ltpyshell39gt", line 1,
in ltmodulegt t1.append(4) AttributeError
'tuple' object has no attribute 'append' gtgtgt
t1.pop() Traceback (most recent call last)
File "ltpyshell40gt", line 1, in ltmodulegt
t1.pop() AttributeError 'tuple' object has no
attribute 'pop' gtgtgt t1.remove(45) Traceback (most
recent call last) File "ltpyshell44gt", line 1,
in ltmodulegt t1.remove(45) AttributeError
'tuple' object has no attribute 'remove'
32
Diccionarios Datos agrupados por clave-valor,
sin orden.
gtgtgt en2es 'blue''azul','red''rojo','black''n
egro' gtgtgt en2es'blue' 'azul' gtgtgt
en2es'azul' Traceback (most recent call last)
File "ltpyshell47gt", line 1, in ltmodulegt
en2es'azul' KeyError 'azul' gtgtgt 'blue' in
en2es verifico que una clave exista en 1
dict. True gtgtgt en2es.keys() 'blue', 'black',
'red' gtgtgt en2es.values() 'azul', 'negro',
'rojo' gtgtgt en2es.items() ('blue', 'azul'),
('black', 'negro'), ('red', 'rojo') gtgtgt
en2es.get('green','N/D') 'N/D' gtgtgt es2en
Diccionario vacio gtgtgt es2en'azul' 'blue'
Cargo un par clave-valor gtgtgt es2en 'azul'
'blue'
33
Ejemplo de diccionario
tom_map 1992 1 ('1A', 8.9), ('1B',
13.6), ('1C', 22.3), ('1D', 60.8), ('1E', 70.4),
('1F-G', 93.6), ('1H', 111.7), ('1I', 129.2),
('1J', 10000), 2 ('2A', 1.6), ('2B', 16.2),
('2C', 18.6), ('2D', 22.5), ('2E', 27.6), ('2F',
44.8), ('2G', 68), ('2H', 72.4), ('2I', 76.1),
('2J', 100.5), ('2K', 122.9), ('2L', 10000), 3
('3A', 24.2), ('3B', 30.4), ('3C', 54.8), ('3D',
61.1), ('3E', 64.4), ('3F', 97), ('3G', 98.4),
('3H', 108), ('3I', 100000), 4 ('4A', 2),
('4B', 6.6), ('4C', 32.9), ('4D', 38), ('4E',
50), ('4F', 58.4), ('4G', 100.5), ('4H', 113.2),
('4I', 10000), 5 ('5A', 4.6), ('5B', 17.2),
('5C', 42.8), ('5D', 44.6), ('5E', 72.7), ('5F',
75), ('5G', 84.9), ('5H', 92.3), ('5I', 10000),
6 ('6A', 25), ('6B', 31.8), ('6C', 42), ('6D',
61.9), ('6E', 69.6), ('6F', 89.6), ('6G',
10000), 7 ('7A', 3), ('7B', 11), ('7C', 21),
('7D', 36.8), ('7E', 52.6), ('7F', 70.6), ('7G',
75.7), ('7H', 10000), 8 ('8A-B', 18.2), ('8C',
20.1), ('8D', 41.1), ('8E', 61.3), ('8F', 80.6),
('8G', 89.1), ('8H', 10000), 9 ('9A', 8.9),
('9B', 22), ('9C', 28.9), ('9D', 39), ('9E',
56.4), ('9F', 57.4), ('9G', 64.2), ('9H', 69.1),
('9I', 79), ('9J', 102.6), ('9K', 10000), 10
('10A', 12), ('10B', 37.3), ('10C-D', 48.8),
('10E', 64.6), ('10F', 84.1), ('10G', 10000),
11 ('11A', 20.8), ('11B', 32.3), ('11C', 45.4),
('11D', 59.3), ('11E', 79.9), ('11F', 83.3),
('11G', 83.8), ('11H', 10000), 12 ('12A',
13.8), ('12B', 28.2), ('12C', 32.5), ('12D', 41),
('12E', 47.6), ('12F', 67.3), ('12G', 86),
('12H', 91.8), ('12I', 10000) , 2000
1 ('1A', 19.5), ('1B', 25), ('1C', 31.8),
('1D', 70), ('1E', 92.7), ('1F-G', 127.6), ('1H',
142), ('1I', 163), ('1J', 10000), 2 ('2A', 4),
('2B', 13), ('2C', 16), ('2D-E', 31), ('2F',
45.1), ('2G', 81.2), ('2H', 85), ('2I', 90.1),
('2J', 116.1), ('2K', 143), ('2L', 10000), 3
('3A', 32), ('3B', 33), ('3C', 71.5), ('3D', 83),
('3E', 85), ('3F', 129), ('3G', 140), ('3H-I',
10000), 4 ('4A-B', 12), ('4C', 46), ('4D',
56), ('4E', 72.5), ('4F', 75), ('4G', 101),
('4H', 124), ('4I', 10000), 5 ('5A', 13.5),
('5B', 30), ('5C', 69), ('5D', 71.1), ('5E',
102), ('5F', 104), ('5G', 110.1), ('5H', 112),
('5I', 10000), 6 ('6A', 33.5), ('6B', 38.6),
('6C', 50), ('6D', 71), ('6E', 81), ('6F', 96),
('6G', 10000), 7 ('7A', 2), ('7B', 7), ('7C',
21.5), ('7D', 45.5), ('7E', 48), ('7F', 72.3),
('7G', 73), ('7H', 10000), 8 ('8A', 2), ('8B',
23.8), ('8C', 30), ('8D', 40), ('8E', 57), ('8F',
68.3), ('8G', 84), ('8H', 10000), 9 ('9A', 4),
('9B', 28), ('9C', 32), ('9D', 35), ('9E', 50.3),
('9F', 53.7), ('9G', 57.5), ('9H', 62), ('9I',
72.5), ('9J', 102), ('9K', 10000), 10 ('10A',
11), ('10B', 43), ('10C-E', 61.5), ('10F', 80),
('10G', 10000), 11 ('11A', 20.5), ('11B',
36.5), ('11C', 49), ('11D', 76), ('11E', 90),
('11F-G', 92), ('11H', 10000), 12 ('12A', 21),
('12B', 32.5), ('12C', 38), ('12D', 55.3),
('12E', 68.5), ('12F-G', 114), ('12H', 117),
('12I', 10000)
34
Sets (Conjuntos)
gtgtgt mi_set set() gtgtgt mi_set.add('jose') gtgtgt
mi_set.add('juan') gtgtgt mi_set.add('natalia') gtgtgt
mi_set.add('viki') gtgtgt mi_set set('jose',
'juan', 'viki', 'natalia') gtgtgt
mi_set.pop() 'jose' gtgtgt mi_set set('juan',
'viki', 'natalia') gtgtgt mi_set.add('jose') gtgtgt
mi_set set('jose', 'juan', 'viki',
'natalia') gtgtgt mi_set.add('jose') gtgtgt
mi_set set('jose', 'juan', 'viki',
'natalia') gtgtgt otro_set set('juan','karina','d
iana') gtgtgt otro_set set('diana', 'juan',
'karina') gtgtgt mi_set.intersection(otro_set) set(
'juan') gtgtgt mi_set.union(otro_set) set('jose',
'viki', 'natalia', 'diana', 'juan',
'karina') gtgtgt mi_set.difference(otro_set) set('j
ose', 'viki', 'natalia')
35
(No Transcript)
36
Conversión de datos En Python siempre es
explicito
gtgtgt rgbdict(('blue','0000FF'),('black','000000
'),('red','FF0000')) gtgtgt rgb'black' '000000'
gtgtgt list(t1) 'sgn1545', 5, 45 gtgtgt lista
list('Hago 1 lista') gtgtgt lista 'H', 'a', 'g',
'o', ' ', '1', ' ', 'l', 'i', 's', 't', 'a' gtgtgt
tuple(lista) ('H', 'a', 'g', 'o', ' ', '1', ' ',
'l', 'i', 's', 't', 'a') gtgtgt str(lista) "'H',
'a', 'g', 'o', ' ', '1', ' ', 'l', 'i', 's', 't',
'a'" gtgtgt ''.join(lista) 'Hago una lista' gtgtgt
'Hago una lista'.split(' ') 'Hago', 'una',
'lista'
37
Data I/O
Entrada input('prompt') raw_input('prompt') gtgtgt
edad input('Ingrese la edad ') Ingrese la
edad 33 gtgtgt edad 33 gtgtgt edad
raw_input('Ingrese la edad ') Ingrese la edad
33 gtgtgt edad '33' Python 3 input() es
raw_input() Salida print Python 3 print()
38
Estructuras de control de flujo
  • if Condición
  • for Repetición
  • while Repetición

39
if
if ltexpresion1gt ltInstruccionesgt elif
ltexpresion2gt ltInstruccionesgt else
ltInstruccionesgt if coord ! 'N/A' year
int(coord0-4)
40
for
for ltvargt in ltiterablegt ltinstruccionesgt fo
r x in 1, 3, 4 print x
41
while
while ltexpresiongt ltinstruccionesgt while
mi_set print mi_set.pop()
42
Ejercicios
43
  • Archivos
  • Lectura
  • Abrir (open)
  • Leer (read, readlines, readline)
  • Cerrar (close)
  • Escritura
  • (1) Abrir (open)
  • (2) Guardar (write)
  • (3) Cerrar (close)

44
Leyendo un archivo (1) La función open crea
un filehandle. open(filename, mode,
bufsize) Ej fh open('mi_archivo.txt','r')
(2) read(n) Lee n bytes, por defecto lee el
archivo entero. readline() Devuelve str con una
sola linea readlines() Devuelve una lista con
str por cada línea
45
fh open('archivo.txt') contenido
fh.read() print contenido fh
open('archivo.txt') contenido
fh.readlines() print contenido contenido
'' fh open('archivo.txt') while True line
fh.readline() contenido line if
line'' break print contenido Para
todos fh.close()
46
Apertura secuencial de un archivo
fh open('archivo.txt') contenido '' for line
in fh contenido line fh.close()
47
Leyendo con 'with' (Python 2.6 en
adelante) with EXPRESION as VARIABLE
BLOQUE DE CODIGO with open('archivo.txt') as
fh for line in fh print line
48
Escribiendo archivos
Modos de escritura w Write, graba un archivo
nuevo, si existe, borrarlo. a Append (agregar),
agrega información al final de un archivo
pre-existente. Si no existe, crea uno nuevo (uso
típico logs).
Ejemplo fh open('/home/yo/archivo.txt','w') f
h.write('1\n2\n3\n4\n5\n') fh.close()
49
Archivos CSV (Comma separated file) Ejemplo Se
bastián,Perez,33,23566777 Jose,Martinez,23,4212132
9 Karina,Gonzalez,32,24159857 Maria
Laura,Yañes,19,43852144 Otro separador Sebastiá
nPerez3323566777 JoseMartinez2342121329 Kari
naGonzalez3224159857 Maria LauraYañes1943852
144
50
Leyendo CSV sin usar módulo CSV fh
open('archivo.txt') for line in fh linea
line.split(',') procesar elementos
nombre linea0 apellido linea1
etc, etc fh.close()
51
CSV con módulo CSV import csv lineas
csv.reader(open('fn.csv')) for line in lineas
nombre line0 apellido
line1 Cambiando separador (delimitador) line
as csv.reader(open('fn.csv'),delimiter'') Di
alectos gtgtgt csv.list_dialects() 'excel-tab',
'excel'
52
Escribiendo archivos CSV gtgtgt import csv gtgtgt
spamWriter csv.writer(open('eggs.csv', 'w'),
delimiter' ', ...
quotechar'', quotingcsv.QUOTE_MINIMAL) gtgtgt
spamWriter.writerow('Spam' 5 'Baked
Beans') gtgtgt spamWriter.writerow('Spam', 'Lovely
Spam', 'Wonderful Spam')
53
Lectura y escritura de Excel xlrd y xlwt
Instalando Easy_install En Windows
http//pypi.python.org/pypi/setuptools
Leyendo Excel
import xlrd iedb Empty dictionary book
xlrd.open_workbook('sampledata.xls') sh
book.sheet_by_index(0) for i in
range(1,sh.nrows) skips fist line.
iedbsh.cell_value(rowxi, colx1) \
sh.cell_value(rowxi, colx2)
54
Creando planillas Excel
import xlwt list1 1,2,3,4,5 list2
234,267,281,301,331 wb xlwt.Workbook() ws
wb.add_sheet('Primera hoja') ws.write(0,0,'Column
A') ws.write(0,1,'Column B') i 1 for x,y in
zip(list1,list2) Walk 2 list _at_ once.
ws.write(i,0,x) Fila, Columna, Datos.
ws.write(i,1,y) i 1 wb.save('mynewfile.xls'
)
55
Pickle Persistencia simple de datos. Pickle vs.
cPickle Grabar gtgtgt spdict 'blue''azul','red
''rojo' gtgtgt spdict 'blue' 'azul', 'red'
'rojo' gtgtgt import cPickle gtgtgt fh
open('spict.data','w') gtgtgt cPickle.dump(spdict,
fh) gtgtgt fh.close() Leer gtgtgt spdict
cPickle.load(open('spict.data')) gtgtgt
spdict 'blue' 'azul', 'red' 'rojo'
56
Modularizando el código
Ejemplo de función Parámetros fijos gtgtgt
len('Hola') 4 Parámetros variables gtgtgt
range(5) 0, 1, 2, 3, 4 gtgtgt range(2,5) 2, 3,
4 gtgtgt range(2,5,2) 2, 4
57
Definición de función def Nombre_Funcion(param
etro1, parametro2, etc) ''' Descripcion
optativa ''' código de la función
return DATA Ejemplo def tair_data(f_in)
tair9_d for rec in SeqIO.parse(open(f_in)
,'fasta') tair9_drec.id
rec.description return tair9_d Importante
Ambito de variables
58
Mas ejemplos def sgn_u(bacsgn,rango_ini,rango_en
d,sgn_u_tomato_d) """ Procesa un nombre
tipo 'C02HBa0106H06.1' con sus posiciones,
compara con datos en sgn_u_tomato_d y retorna
cuales son. """ sgn_u if bacsgn
in sgn_u_tomato_d for gendata in
sgn_u_tomato_dbacsgn if gendata0
lt rango_ini lt rango_end lt gendata1
sgn_u.append(sgns.get(gendata2,gendata2
)) return sgn_u def august(name,rango_ini,ran
go_end,crms_d) """ Procesa un nombre
tipo 'C02HBa0106H06.1' con sus posiciones,
compara con datos en crms_d y dice si es AUGUST
o -. """ if name in crms_d for x
in crms_dname if x0 lt rango_ini
lt rango_end lt x1 return
True return False
59
Función que no devuelve nada (devuelve
None) def savelist(L, fn) ''' Una
lista (L) es grabada como archivo con nombre
fn ''' fh open(fn,'w') for x in L
fh.write(x'\n') fh.close() return
None
60
Parametros por defecto def savelist(L,
fn'tmp.txt') ''' Una lista (L) es
grabada como archivo con nombre fn '''
fh open(fn,'w') for x in L
fh.write(x'\n') fh.close() return
None
61
Número indeterminado de argumentos
No se conoce de antemano cuantos argumentos irán
en la función. El argumento que tenga el
(asterisco) será pasado como una tupla.
def promedio(numeros) if len(numeros)0
return None else
return(float(sum(numeros))/len(numeros))
62
Número indeterminado de argumentos con claves
Los argumentos en exceso son pasados como
diccionario
def cli(nombre,parametros) linea ''
for p_key,p_vals in parametros.iteritems()
linea ' -' p_key ' ' p_vals return
nombrelinea
63
Módulos
Los módulos son archivos con instrucciones
(funciones, clases) y datos para ser usado desde
un programa.
Usando módulos gtgtgt import os gtgtgt
os.getcwd() '/home/sbassi' gtgtgt from os import
getcwd gtgtgt getcwd() '/home/sbassi' gtgtgt from os
import gtgtgt getcwd() '/home/sbassi' gtgtgt
sep '/' gtgtgt import xml.etree.ElementTree as ET
64
Instalando módulos
(1) Copiar al PYTHONPATH gtgtgt import sys gtgtgt
sys.path '', '/usr/local/lib/python2.6/dist-packa
ges/xlrd-0.7.1-py2.6.egg', '/usr/local/lib/python2
.6/dist-packages/biopython-1.52-py2.6-linux-i686.e
gg', '/usr/lib/python2.6', '/usr/lib/python2.6/pla
t-linux2', '/usr/lib/python2.6/lib-tk',
'/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
lib-dynload', '/usr/lib/python2.6/dist-packages',
'/usr/lib/python2.6/dist-packages/Numeric',
'/usr/lib/python2.6/dist-packages/PIL',
'/usr/lib/python2.6/dist-packages/gst-0.10',
'/var/lib/python-support/python2.6',
'/usr/lib/python2.6/dist-packages/gtk-2.0',
'/var/lib/python-support/python2.6/gtk-2.0',
'/usr/lib/python2.6/dist-packages/wx-2.6-gtk2-unic
ode', '/usr/local/lib/python2.6/dist-packages'
65
Instalando módulos
(2) Usar gestor de paquetes rpm, apt-get,
etc (3) Easy Install (easy_install) sudo
apt-get install python-setuptools sudo
easy_install NOMBRE_DEL_MODULO
Modulos como programas if __name__
"__main__" hacer algo
66
Biblioteca estándar (PSL) http//docs.python.org/
library/
import os directorio actual? print
os.getcwd() listo todos los archivos del dir
actual ma os.listdir(os.getcwd()) necesito
solo los terminados en .txt ma2 for x in
ma if x.endswith('.txt')
ma2.append(x) print ma2 otra manera de retener
los terminados en .txt ma2 x for x in ma if
x.endswith('.txt') print ma2
67
import glob
import glob directorio actual? print
os.getcwd() listo todos los archivos del dir
actual ma os.listdir(os.getcwd()) necesito
solo los terminados en .txt ma2 for x in
ma if x.endswith('.txt')
ma2.append(x) print ma2 otra manera de retener
los terminados en .txt ma2 x for x in ma if
x.endswith('.txt') print ma2
68
import zipfile a_list "Test1.txt",
"Test2.txt", "Test3.txt" Guardar archivos en
un zip zfilename "mi_archivozipeado.zip" zout
zipfile.ZipFile(zfilename, "w") for fname in
a_list zout.write(fname) zout.close()
69
import zipfile myfile zipfile.ZipFile('archivo.
zip') if myfile.is_zipfile(archivo.zip)
print "Es un archivo zip OK" for fn in
myfile.namelist() print fn
myfile.extractall() else print "No es un
archivo zip valido"
70
gtgtgt import time gtgtgt esperar n segundos. gtgtgt
time.sleep(2) gtgtgt time.asctime() 'Tue Dec 1
200734 2009' gtgtgt time.time() 1259708878.824398 gt
gtgt time.time() 1259708882.5425911 gtgtgt a
time.time() gtgtgt b time.time() gtgtgt
b-a 6.0693800449371338 Para medir tiempo de
procesos, usar módulo timeit
71
import sys from optparse import
OptionParser usage "usage prog
password_file dictionary_file\n" usage "or
prog options password_file\n\n" usage
"Type prog -h for more information" parser
OptionParser(usage, version"prog
1.0") parser.add_option("-i", "--input",
dest"input_file", help"Input
file. ") parser.add_option("-d", "--dictionary",
dest"dict_file", help"Use a
dictionary file. ") (opts, args)
parser.parse_args() if opts.input_file fh
open(opts.input_file) elif args fh
open(args0) elif sys.stdin fh
sys.stdin else parser.error("Enter an input
file") if len(args)2 fd
open(args1) elif opts.dict_file fd
open(opts.dict_file) else parser.error('Enter
a dictionary file or aspell dictionary')
72
Subprocess import subprocess cmd 'ps',
'-eo', 'pcpu' p subprocess.Popen(cmd,
stdoutsubprocess.PIPE) std p.communicate()0 a
llstatus str(std).split('\n')
73
webbrowser
gtgtgt import webbrowser gtgtgt webbrowser.open('http//
www.py4bio.com') True gtgtgt b webbrowser.get('oper
a') gtgtgt url 'http//www.py4bio.com' gtgtgt
b.open(url) True
74
Mas ayuda...
Manual de Python http//pyspanishdoc.sourceforge
.net/tut/tut.html Mailing list
http//python.org.ar/pyar/ListaDeCorreo List
para incio http//groups.google.com/group/a-pytho
n Mas recursos http//python.org.ar/pyar/Aprend
iendoPython
Write a Comment
User Comments (0)
About PowerShow.com