Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Inexact : >>> getcontext() Context(..., flags=[Rounded, Inexact], ...) Rounded : This signal is used to detect loss of significant digits. >>> getcontext() Context(..., flags=[Rounded], ...)
Taller I Coreis Python 10112009 - Presentation Transcript
Taller I Python Carlos Mauro Cárdenas Fernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]
Temario
Python
Python Básico y Práctica
GUI TK, WX
Python 3.0
Python Sugar
Python
Algunos usuarios de Python
Algunas características
Gratis Y Libre
Y Open Source, todo por el mismo precio: cero
Maduro (+14 años)
Diseño elegante y robusto
Pero evoluciona
Fácil de aprender
Se lee como pseudo-código
Sintaxis sencilla
Extremadamente portable
Unix, Windows, Mac, BeOS, Win/CE
DOS, OS/2, Amiga, VMS, Cray...
Propiedades del lenguaje
Compila a bytecode interpretado
La compilación es implícita y automática
Tipado dinámico , pero fuerte
Multi-paradigma
Todo son objetos
Pero puede usarse de manera procedural
Módulos, clases, funciones, generadores
Viene con las baterias incluidas
Extensa biblioteca estándar
Clave en la productividad de Python
Más propiedades
Manejo moderno de errores
Por excepciones
Muy útil detalle de error
Tipos de datos de alto nivel
Enteros sin límites , strings, flotantes, complejos
Listas, diccionarios , conjuntos
Intérprete interactivo
Clave en el bajo conteo de bugs
Acelera sorprendentemente el tiempo de desarrollo
Permite explorar , probar e incluso ver la documentación
Las baterías incluídas
La Biblioteca Estándar ayuda con...
Servicios del sistema, fecha y hora, subprocesos, sockets, internacionalización y localización, base de datos, threads, formatos zip, bzip2, gzip, tar, expresiones regulares, XML (DOM y SAX), Unicode, SGML, HTML, XHTML, XML-RPC (cliente y servidor), email, manejo asincrónico de sockets, clientes HTTP, FTP, SMTP, NNTP, POP3, IMAP4, servidores HTTP, SMTP, herramientas MIME, interfaz con el garbage collector, serializador y deserializador de objetos, debugger, profiler, random, curses, logging, compilador, decompilador, CSV, análisis lexicográfico, interfaz gráfica incorporada, matemática real y compleja, criptografía (MD5 y SHA), introspección, unit testing, doc testing, etc., etc...
Le ponemos más pilas
Bases de datos
MySQL, PostgresSQL, MS SQL, Informix, DB/2, Sybase
Asignando Variables en Python >>> a = 19 >>> a * 6 >>> a ** 9 >>> b = 73 >>> b + a >>> c = b * a >>> d = c/2.5 >>> mun1 =input("Ingrese un numero: ") >>> nun1*d >>> nun1 ** 0.5 >>> mun2 =input("Ingrese un numero: ") >>> e = nun1 * mun2
Trabajando con Cadenas :D >>>"Hola a todos" >>>'Hola a todos' >>>a = "Uno" >>>b = "Dos" >>>a + b >>>a, b >>>mvar='2' >>>mvar >>>int(mvar) >>>mvar_num= in(mvar) >>>mvar_num >>>¿Qué Sale?
Cadenas Comillas , apóstrofos, triples >>> 'Una cadena es una secuencia de caracteres' 'Una cadena es una secuencia de caracteres' >>> "Ella dijo: 'si'" "Ella dijo: 'si'" >>> """Una linea ... y la otra""" 'Una linea
y la otra' Algunas operaciones >>> "Hola" + " mundo" 'Hola mundo' >>> "Eco " * 4 'Eco Eco Eco Eco ' >>> " Hola mundo ".strip() 'Hola mundo' >>> len("Hola mundo") 10
Accediendo a las cadenas Por posición >>> saludo = 'Hola mundo' >>> saludo[0] 'H' >>> saludo[3] 'a' >>> saludo[-2] 'd' Rebanando >>> saludo[2:5] 'la ' >>> saludo[2:8] 'la mun' >>> saludo[:4] 'Hola' >>> saludo[-2:] 'do'
Cadenas y Caracteres Especiales >>>"Hi. What's the problem?" >>>'Hi. What's the problem?' >>>"Romulo Dijo: "Yó ha hice" " >>>"Romulo Dijo: "Yó ha hice. Gracias Hijita " "
Concatenando Números con Cadenas >>> ns = 28 >>> ns + 1 >>> ns >>> print "Hoy!!!. La pasare con " + ns+ " Amigos" >>> num1 = str(40) >>> print "Hoy!!!. La pasare con " + num1 + " Amigos... Somos" >>> num2 = 4 >>> print "El Rector Padilla("repite el plato") con " +`num2` + " a favor"
Listas Corchetes , varios tipos de elementos >>> a = ['harina', 100, 'huevos', 'manteca'] >>> a ['harina', 100, 'huevos', 'manteca'] Accedemos como cualquier secuencia >>> a[0] 'harina' >>> a[-2:] ['huevos', 'manteca'] Concatenamos, reemplazamos >>> a + ['oro', 9] ['harina', 100, 'huevos', 'manteca', 'oro', 9] >>> a[0] = "sal" >>> a ['sal', 100, 'huevos', 'manteca']
Y dale con las listas Pueden tener incluso otras listas >>> a ['sal', 100, 'huevos', 'manteca'] >>> a[1] = ["Hola", 7] >>> a ['sal', ['Hola', 7], 'huevos', 'manteca'] Borramos elementos >>> del a[-1] >>> a ['sal', ['Hola', 7], 'huevos'] Tenemos otros métodos >>> a.index(“huevos”) 2 >>> a.sort() >>> a [['Hola', 7], 'huevos', 'sal']
Secuencias y Tuplas familia =['ma','pa','tio','abue','herm1','herm2'] familia[2] familia[-2] semana =['lun','mar','mier','jue','vie','sab','dom']
Extracción de Partes de una Secuencia ejemplo=[0,1,2,3,4,5,6,7,8,9] ejemplo[2:6] ejemplo[-1:-6] ejemplo[:8] ejemplo[:] ejemplo[2:6:8] ejemplo[9:2:-3] ejemplo[::-5]
Ordenamientos >>>nuevo=[12,3,2,65,55,663,12,5,5] >>>nuevo.sort() >>>sorted('Palabras de un Diario') >>>entradas ="Holas %s , tu edad es %d" >>>var=('Jackson', 50) >>>print entradas % var >>>noticia="El Astro Michael murió a los 50 años" >>>noticia.find('Michael')
Agregando y Formateando >>> familia =['ma','pa','tio','abue','herm1','herm2'] >>> invitamos='herm3' >>> glue.join(familia) >>> oracion="universidad NACIONAL of ingenieria" >>> oracion.lower() >>> oracion.replace('of','de')
Más diccionarios Viendo qué hay >>> "marzo" in dias False >>> dias.keys() ['enero', 'junio', 'agosto'] >>> dias.values() [31, 30, 31] Otros métodos >>> dias.get("agosto", "No tenemos ese mes") 31 >>> dias.get("mayo", "No tenemos ese mes") 'No tenemos ese mes' >>> dias.pop("agosto") 31 >>> dias {'enero': 31, 'junio': 30}
if else elif #001.py animal=raw_input("Escribe en nombre de un animal de casa: ") if animal=="perro": print 'Es un animal' elif animal=="gato": print 'Es un animal' elif animal=="canario": print "Es un animal" else print "No lo es"
Sentencias de Control Anidadas accion1="Correr" accion2="Parar“ if accion1=="Correr": if accion2=="Parar": print "Avanzo 2 espacios" elif: print "Sigue avanzando" else: print "Permanece parado"
Comparaciones >>> 9<7 >>> 9<=9 >>> 9!=10 >>> one = [21,22,23] >>> two = ["sol","luna"] >>> astro ="sol" >>> astro in two >>> 's' in astro >>> three = one >>> one is three
<
<=
>
>=
==
!=
and y or >>> "perro" < "gato" >>> num1 = "5" >>> if num1 > 3 and num1 < 10: print " Claro que lo es :D " >>> num2 = int(raw_input("Nuevo Numero: ")) >>> if num2 > 3 or num2 < 10: print " Claro que lo es :D " print num2
for and while Repeticiones o Loop >>> >>> b = 1 >>> while b <=10: print b b +=1 >>> cocina=["olla","sarten","cocina","tazon"] >>> cocina >>> for instrumento in cocina: print "Yo tengo en mi cocina 1: "+ instrumento
for and while >>> alumnos={'Alumno1'=19.'Alumno2'=21,'Alumno3'=22} >>> alumnos >>> for edad in alumnos: print edad >>> for edad in alumnos: print edad, alumnos[edad]
For For >>> compras=['fugu', 'ramen', 'sake', 'shiitake mushrooms', 'soy sauce', 'wasabi'] >>> prices={'fugu':100.0, 'ramen':5.0, 'sake':45.0, 'shiitake mushrooms':3.5,➥ 'soy sauce':7.50, 'wasabi':10.0} >>> total=0.00 >>> for item in compras: ... total+= prices[item] >>> total
Repeticiones infinitas y el Break >>> while 1: name = raw_input("Escribe tu Codigo : ") if name == "Quit": break >>> while 1: name = raw_input("Escribe tu Codigo : ") opcion = raw_input("Para Continuar presione "S" y Salir "N" : ") if opcion == "S": continue else: break
Funciones Estructura básica >>> def alcuadrado ( n ) : ... res = n ** 2 ... return res ... >>> alcuadrado(3) 9 Las funciones son objetos >>> alcuadrado < function alcuadrado at 0xb7c30b54> >>> f = alcuadrado >>> f(5) 25
Mas listas >>> l1=['host=local','id=user','pass=word','db=data'] >>> s=";".join(li) >>> s >>> s.split(";") >>> s.split(";",1 )
Suceden cuando algo se escapa de lo normal >>> 14 / 2 7 >>> 14 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError : integer division or modulo by zero Podemos capturarlas >>> try: ... print 14 / 0 ... except ZeroDivisionError : ... print "error!" ... error!
Es muy versátil
try : Acá va el bloque de código que queremos supervisar
except : Atrapa todo, o sólo lo que se le especifique
else : Si no hubo una excepción, se ejecuta esto
finally : Lo que esta acá se ejecuta siempre
Se pueden combinar de cualquier manera
Y podemos generar excepciones >>> raise ValueError("Aca contamos que pasó") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Aca contamos que pasó
Clases Armando una clase >>> class MiClase: ... x = 3 ... def f(self): ... return 'Hola mundo' ... >>> c = MiClase() >>> c.x 3 >>> c.f() 'Hola mundo Heredando >>> class MiClase(ClasePadre): >>> class MiClase(ClasePadre, ClaseTio):
Python: Clases y Objetos
• Python está completamente orientado a
objetos: puede definir sus propias clases, heredar de las que usted defina o de las incorporadas en el lenguaje, e instanciar las clases que haya definido. • En Python las clases se definen mediante la palabra reservada class seguida del nombre de la clase, dos puntos (:) y a continuación, indentado, el cuerpo de la clase.
Las clases de Python no tienen constructores o destructores explícitos. Las clases de Python tienen algo similar a un constructor: el método __init__.
Clase Imaginaria
#include <stdio.h> int main(int argc, char **argv) { FILE *in, *out; int c; in = fopen("input.txt", "r"); out = fopen("output.txt", "w"); while ((c = fgetc(in)) != EOF) { fputc(c, out); } fclose(out); fclose(in); }
Copia de archivo en Python in=open("input.txt") out=open("output.txt", "w") out.writelines(in)
Importando Mas Módulos Creados Por Nosotros #Nueva Ventana #testmodulos.py def testmod(): print "Este es un Test" En la Terminal >>> import testmodulos >>> testmodulos.testmod()
Recargando Módulos #Nueva Ventana #modulomio.py def testmod(): print "Este es un Test“ En la Terminal >>> import modulomio >>> holas= modulomio.testmod() #Nueva Ventana #modulomio.py def testmod(): print "Este es un NUEVO MODULOS“ En la Terminal >>> import modulomio >>> holas= modulomio.testmod() >>> reload(modulomio)
Informacion de los Módulos >>> import math >>> math.sqrt(100) >>> dir(math) >>> import time >>> dir(math) >>> help(math) >>> math.__doc__
Modulo de datetime >>> from datetime import datetime >>> the_time = datetime.now() >>> the_time.ctime()
Nuevos Módulos >>> import operator >>> reduce(operator.__mul__,[1,2,3,4,5]) >>> from apihelper import info >>> li=() >>> info(li)
Nuevos Módulos
>>> dir()
>>> dir(__builtins__)
>>> import urllib2
>>> dir(urllib2)
>>> dir(urllib2.bisect)
Ir al PathBrowser
>>> import inspect
>>> dir(inspect)
>>> inspect.getsource(inspect.getsource)
>>> print _
>>> see(inspect.getsource)
>>> see(urllib2.urlopen)
Trabajando con Archivos >>> fob =open('c:/python26/algo.txt','w') >>> fob.write('Mi primer Archivo') >>> fob.writelines('Mi primer Archivo') >>> fob.close() >>> fob =open('c:/python26/algo.txt','r') >>> fob.read(2) >>> fob.read() >>> fob.close()
Escribiendo Líneas >>> fob =open('c:/python26/test.txt','r') >>> linea = fob.readlines() >>> linea >>> fob.close() >>> linea[2]="Mirando Mirando" >>> linea
Simulador de Números import random random.seed(100) for roll in xrange(10): print random.randint(1, 6) print "Re-seeded“ random.seed(100) for roll in xrange(10): print random.randint(1, 6)
Tinker
Widgets en Tkinter
Widget ->Descripción
Button -> Botones
Canvas -> Area para Dibujos y Gráficos
Checkbutton -> Una Caja clickeable
Entry -> Entrada Simple de Texto
Frame -> Un Contenedor de Widget
Label -> Etiqueta para colocar texto dentro de la Ventana
Listbox -> Una Lista desplegable
Menu -> Un Menu Desplegable
Message -> Un Mensaje de Alerta con texto
Menubutton -> Botón dentro del Menu
Text A multiline -> Texto de multiples líneas
TopLevel -> Una Ventana Adicional
01Tkinter.py from Tkinter import * window = Tk() label = Label(window, text="La Primera Etiqueta.") label.pack()
02Tkinter.py from Tkinter import * import time window = Tk() label = Label(window, text="Primera Etiqueta.") label.pack() time.sleep(2) label.config(text="Segunda Etiqueta.")
Tipos en Tkinter Tipos Inmutables -> Tipos Mutables en Tkinter
int IntVar
string StringVar
bool BooleanVar
double DoubleVar
03Tkinter.py DATA from Tkinter import * window = Tk() data = StringVar() data.set(“Mostrando la Data :D ") label = Label(window, textvariable=data) label.pack() window.mainloop()
04Tkinter.py Frames from Tkinter import * window = Tk() frame = Frame(window) frame.pack() first = Label(frame, text="First label") first.pack() second = Label(frame, text="Second label") second.pack() third = Label(frame, text="Third label") third.pack() window.mainloop()
05Tinkter.py Entrada de Texto from Tkinter import * window = Tk() frame = Frame(window) frame.pack() var = StringVar() label = Label(frame, textvariable=var) label.pack() entry = Entry(frame, textvariable=var) entry.pack() window.mainloop()
06Tinkter.py Modelo, Vista y Controlador from Tkinter import * #Controlador def click(): counter.set(counter.get() + 1) if __name__ == '__main__' : window = Tk() # Modelo counter = IntVar() counter.set(0) # Vista frame = Frame(window) frame.pack() button = Button(frame, text="Click", command=click) button.pack() label = Label(frame, textvariable=counter) label.pack() window.mainloop()
03WxPython.py > Un Menu import wx class wxpython(wx.Frame): def __init__ (self,parent,id): wx.Frame.__init__(self,parent,id,'Nueva Ventana', size=(300,200)) panel=wx.Panel(self) status=self.CreateStatusBar() menubar=wx.MenuBar() uno=wx.Menu() dos=wx.Menu() uno.Append(wx.NewId(),"Nuevo Archivo","Esto son los Archivos") uno.Append(wx.NewId(),"Abrir...", "Abrir el Archivo") menubar.Append(uno,"Archivo") menubar.Append(dos,"Editar") self.SetMenuBar(menubar)
04WxPython.py > Ventana de Diálogo import wx class wxpython(wx.Frame): def __init__ (self,parent,id): wx.Frame.__init__(self,parent,id,'Nueva Ventana', size=(300,200)) panel=wx.Panel(self) box=wx.MessageDialog(None,'Que paso','Alerta',wx.YES_NO) answer=box.ShowModal() box.Destroy() if __name__ == '__main__': app=wx.PySimpleApp() frame=wxpython(parent=None,id=-1) frame.Show() app.MainLoop()
05WxPython.py > TextEntryDialog import wx class wxpython(wx.Frame): def __init__ (self,parent,id): wx.Frame.__init__(self,parent,id,'Nueva Ventana', size=(300,200)) panel=wx.Panel(self) box=wx.TextEntryDialog(None,"Nombre","Titulo","Escriba su Nombre") if box.ShowModal()== wx.ID_OK: answer=box.GetValue() if __name__ == '__main__': app=wx.PySimpleApp() frame=wxpython(parent=None,id=-1) frame.Show() app.MainLoop()
06WxPython.py > SingleChoiceDialog import wx class wxpython(wx.Frame): def __init__ (self,parent,id): wx.Frame.__init__(self,parent,id,'Nueva Ventana', size=(300,200)) panel=wx.Panel(self) box=wx.SingleChoiceDialog(None, 'Cuales son tus Curso','Preguntas',['Matematica','Fisica','Quimica']) if box.ShowModal()== wx.ID_OK: answer=box.GetStringSelection()
07WxPython.py > StaticText import wx class wxpython(wx.Frame): def __init__ (self,parent,id): wx.Frame.__init__(self,parent,id,'Nueva Ventana', size=(300,200)) panel=wx.Panel(self) wx.StaticText(panel,-1,"Esto es un Texto",(10,10)) custom=wx.StaticText(panel,-1,"Esto es una Personalización",(10,30),(260,-1),wx.ALIGN_CENTER) custom.SetForegroundColour('yellow') custom.SetBackgroundColour('red')
08WxPython.py > TextEntry & StaticText import wx class wxpython(wx.Frame): def __init__ (self,parent,id): wx.Frame.__init__(self,parent,id,'Nueva Ventana', size=(300,200)) panel=wx.Panel(self) test=wx.TextEntryDialog(None,"Holitas",'title','ingresa tu nombre') if test.ShowModal()==wx.ID_OK: applica=test.GetValue() wx.StaticText(panel, -1,applica,(10,10))
Diccionarios >>>d = {1:"dead", 2:"parrot"} >>>print(d.items()) >>>1 in d # test for membership >>>for values in d.items(): ... print(values) ... >>>keys = list(d.keys()) >>>print(keys)
Python 3 PEPs * PEP 318: Decorators for Functions and Methods * PEP 3107: Function Annotations * PEP 3129: Class Decorators * PEP 3127: Integer Literal Support and Syntax * PEP 3115: Metaclasses in Python 3000 * PEP 3119: Introducing Abstract Base Classes * PEP 3141: A Type Hierarchy for Numbers * PEP 3109: Raising Exceptions in Python 3000 * PEP 3110: Catching Exceptions in Python 3000 * PEP 3102: Keyword-Only Arguments
0 comments
Post a comment