49. 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
51. 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?
52. 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
53. 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'
54. Cadenas y Caracteres Especiales >>>"Hi. What's the problem?" >>>'Hi. Whatapos;s the problem?' >>>"Romulo Dijo: "Yó ha hice" " >>>"Romulo Dijo: amp;quot;Yó ha hice Gracias Hijita " "
55. 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(amp;quot;repite el platoamp;quot;) con " +`num2` + " a favor"
56. 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']
57. 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']
59. Secuencias y Tuplas familia =['ma','pa','tio','abue','herm1','herm2'] familia[2] familia[-2] semana =['lun','mar','mier','jue','vie','sab','dom']
60. 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]
61.
62. ¡¡¡Más Listas!!! familia =['ma','pa','tio','abue','herm1','herm2'] >>>'ma' in familia >>>len(familia) >>>max(familia) >>>min(familia) >>>numeros =[156,635,0.5,56,895, 98,1,-77] >>>numeros[4]=78 >>>list('Curso de Python') >>>nom= list('Curso de Python') >>> del numeros[4] >>> lista1 = list('VamosBien') >>> lista2 = list('creo') >>> lista1 >>> lista2 >>> lista1[5:]=list('...Anda!!') >>> lista2[2:2]=[25,16,58,63] >>> lista1[1:8]=[]
64. 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')
65. 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')
68. 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}
69. 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"
70. 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"
77. 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
78. 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
79. 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]
80. 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
81. 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 amp;quot;Samp;quot; y Salir amp;quot;Namp;quot; : ") if opcion == "S": continue else: break
82. 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
102. 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ó
104. 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):
105.
106. 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__.
108. #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); }
109. Copia de archivo en Python in=open("input.txt") out=open("output.txt", "w") out.writelines(in)
110. 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()
111. 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)
112. Informacion de los Módulos >>> import math >>> math.sqrt(100) >>> dir(math) >>> import time >>> dir(math) >>> help(math) >>> math.__doc__
113. Modulo de datetime >>> from datetime import datetime >>> the_time = datetime.now() >>> the_time.ctime()
114. Nuevos Módulos >>> import operator >>> reduce(operator.__mul__,[1,2,3,4,5]) >>> from apihelper import info >>> li=() >>> info(li)
129. Escribiendo Líneas >>> fob =open('c:/python26/test.txt','r') >>> linea = fob.readlines() >>> linea >>> fob.close() >>> linea[2]="Mirando Mirando" >>> linea
130. 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)
151. 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()
152. 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()
153. 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()
154. 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()
178. 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)
179. 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()
180. 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()
181. 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()
182. 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')
183. 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))
189. 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)
190. 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
216. Carlos Mauro Cárdenas Fernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]
Notas do Editor
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], ...)