Download PYTHON
Document related concepts
no text concepts found
Transcript
Pontificia Universidad Católica de Chile Escuela de Ingeniería DILab pensamiento visual ING1015 Ayudantia 1 PYTHON básico fase II: VISUALIZACION 2d 1. Procesamiento de datos - Python + Excel 2. Visualización - Lenguajes Web: HTML + CSS - JavaScript - Github Python - Variables - Strings <texto> - Condiciones y control de flujo - Funciones - (extra) Objetos Python documentacion http://www.python.org tutoriales http://www.codecademy.com/tracks/python http://www.learnpython.org/ http://docs.python.org/3/tutorial/ Por qué programación ? “ Ordenar secuencias lógicas de información. '' PYTHON VARIABLES var = 1 Python VARIABLES Las variables se definen de forma dinámica. Un_texto = “Mi primera variable” Un_numero = 5 Python VARIABLES Mostrar/imprimir variables. #Código Un_numero = “100.000” print Un_numero #Resultado en consola 100.000 Python VARIABLES Comentarios: con # podemos comentar. #Esto #Otro #Sigo #Esto es un comentario comentario comentando... no se ejecutará ‘‘‘ Comentarios con más de 1 línea ‘‘‘ Un_numero = 7 #También se puede comentar aquí Python VARIABLES Funciones matemáticas. #Potencias var = 10**2 #Módulo var = 3%2 print var print var #Resultado 100 #Resultado 1 PYTHON strings var = “Textos” Python STRINGS Se crean por medio ‘‘ o ““. # Código texto = ‘Mi primer texto’ print texto # Resultado Mi primera texto Python STRINGS Escapar caracteres ‘This isn’t flying, this is falling with style!’ Se soluciona utilizando \ antes del caracter ‘This isn\’t flying, this is falling with style!’ Python STRINGS Conseguir la letra en una cierta posición c = “cats” letra = c[0] print letra print c.capitalize() print len(c) #Resultado c Cats 4 Python STRINGS Combinar variables y strings # En los tres siguientes ejemplos consigues el mismo resultado var = 20 print (“If we add 10 to your number, we get “, var) print ”If we add 10 to your number, we get %s “ % var print ”If we add 10 to your number, we get {0} “.format(var) # Resultado If we add 10 to your number, we get 20 If we add 10 to your number, we get 20 If we add 10 to your number, we get 20 PYTHON condiciones y control de flujo if name == “Maca Maggi” && age == 22 print “Es estudiante del major.” Python CONDICIONES Y CONTROLES DE FLUJO Comparadores == igual que ! = distinto/desigual < menor que <= menor o igual que > mayor que >= mayor o igual que Python CONDICIONES Y CONTROLES DE FLUJO Condicionales: ejemplos de uso. edad = 21 nombre = “Mauro” if edad > 18 : print nombre + “ es mayor de edad” #resultado Mauro es mayor de edad Python CONDICIONES Y CONTROLES DE FLUJO Condicionales: ejemplos de uso. edad = 23 nombre = “Luis” if edad < 18 : print nombre + “ elif edad >= 21 : print nombre + “ else : #entre 18 y print nombre + “ es menor de edad” es mayor de edad internacionalmente” 21 es mayor de edad” #Resultado Luis es mayor de edad internacionalmente Python CONDICIONES Y CONTROLES DE FLUJO Ciclos: while count = 0 if count < 5: print(“Hello, I am an if statement and count is ”, count) while count < 5: print(“Hello, I am a while and count is ”, count) count += 1 #Resultado Hello, I am Hello, I am Hello, I am Hello, I am Hello, I am Hello, I am an if statement and count is a while statemente and count a while statemente and count a while statemente and count a while statemente and count a while statemente and count 0 is is is is is 0 1 2 3 4 Python CONDICIONES Y CONTROLES DE FLUJO Ciclos: for print “Counting...” for i in range(10) : print i #Resultado Counting… 0 1 2 3 4 5 6 7 8 9 ... Python CONDICIONES Y CONTROLES DE FLUJO Ciclos: for lists numbers = [7, 9, 12, 54, 99] print “This list contains:” for num in numbers: print num #resultado This list contains: 7 9 12 54 99 PYTHON FUNCIONES def mul(x,y): return x*y Python FUNCIONES definición variables def nombre (var_1, var_2, ...): mul = var_1*var_2*... return mul ¡Ojo con las tabulaciones! iniciar con “:” Python FUNCIONES def tax(bill) : #Adds 8% tax to a restaurant bill. bill *= 1.08 print ”With tax: %f” %bill return bill Python FUNCIONES def tax(bill) : #Adds 8% tax to a restaurant bill. bill *= 1.08 print(”With tax: %f” % bill) return bill def tip(bill): #Adds 15% tip to a restaurant bill. bill *= 1.15 print(“With tip: %f” % bill) return bill Python FUNCIONES def tax(bill) : #Adds 8% tax to a restaurant bill. bill *= 1.08 print(”With tax: %f” % bill) return bill def tip(bill): #Adds 15% tip to a restaurant bill. bill *= 1.15 print(“With tip: %f” % bill) return bill meal_cost = 100 meal_with_tax = tax(meal_cost) meal_with_tip = tip(meal_with_tax) print meal_with_tip PYTHON MODELACION DE PROBLEMAS Python PROBLEMA MODELACIÓN DE PROBLEMAS Construir un programa que nos permita dibujar figuras con diferentes características (triángulo, círculo y cuadrado). Ahora, queremos dibujar en diferentes formatos también, los cuales pueden ser: consola, archivo txto, generar una imagen. Python MODELACIÓN DE PROBLEMAS triángulo cuadrado círculo <Variables> <Métodos o Funciones> <Variables> <Métodos o Funciones> <Variables> <Métodos o Funciones> impresora <Variables> <Métodos o Funciones> PYTHON CLASES Y OBJETOS triángulo cuadrado círculo Método: cambiarColor impresora dibujo Python CLASES Y OBJETOS Una CLASE es una parte del programa que encapsula funcionalidades, es decir, métodos y variables. class Matematica def __init__(self,n) self.nombre = n def sumar(x,y) return (x+y) def restar(x,y) return (x-y) Tiende a ser la representación abstracta de un objeto. Python CLASES Y OBJETOS Python es un lenguaje de PROGRAMACIÓN ORIENTADA A OBJETOS (OOP) INTERACCIÓN DE OBJETOS Python CLASES Y OBJETOS Un OBJETO es una entidad dentro de un programa que posee un comportamiento característico según su clase. CLASE OBJETO Cuando queremos MODELAR COMPORTAMIENTOS en un programa desearemos trabajar con objetos. Python CLASES Y OBJETOS Estructura de una clase: class <Nombre de clase> def __init__(self, parametroIngresado_1,..., parametroIngresado_n): self.atributo_1 = parametroIngresado_1 self.atributo_2 = parametroIngresado_2 #... self.atributo_n = parametroIngresado_n <Contenido adicional del constructor> def metodo_1(self, parametro_1, ..., parametro_n) <Contenido del método> def metodo_2(self, parametro_2, ..., parametro_n) <Contenido del método> #... ¿Qué pasa si quiero GUARDAR DE FORMA PERMANENTE la información? ¿Y si NECESITO USAR DATOS EXTERNOS a mi programa? SOLUCIon: ´ Leer y Escribir Archivos de Texto PYTHON ARCHIVOS nameArchivo = open(“archivo.txt”, “r”) Python ARCHIVOS LEER ARCHIVOS modo: read nombre del archivo miArchivo = open(“archivo.txt”,“r”) lineas del archivo = miArchivo.readlines() miArchivo.close() cerrar archivo acción sobre el archivo * Otra opción es .readline(). Python ARCHIVOS ESCRIBIR ARCHIVOS modo: write nombre del archivo miArchivo = open(“archivo.txt”,“w”) s = “hola” miArchivo.write(s) miArchivo.close() cerrar archivo acción sobre el archivo * Si el archivo no existe, Python lo creará. Si el archivo ya existe se borrará y escribirá uno nuevo. Python ARCHIVOS ESCRIBIR ARCHIVOS modo: append nombre del archivo miArchivo = open(“archivo.txt”,“a”) miArchivo.write(“Hola \n”) miArchivo.write(“Soy un archivo de texto.”) miArchivo.close() * Si el archivo ya existe escribe en el archivo existente sin borrar su contenido. } INFOR MA CION DATOS FORMATOS "PERIODO";"MES";"PAIS_ORIGEN";"ARANCEL";"TOTAL_CIF_ITEM_US$" "2016";"01";"AFGHANISTAN";"82060000";4139,95 "2016";"01";"ALBANIA";"91021100";189,63 "2016";"01";"ALBANIA";"64039110";88192,68 "2016";"01";"ALEMANIA";"90272000";17861,93 "2016";"01";"ALEMANIA";"72122000";10360,82 "2016";"01";"ALEMANIA";"90283010";904,32 "2016";"01";"ALEMANIA";"96170010";4958,19 "2016";"01";"ALEMANIA";"73079300";380,29 .CSV Comma-Separated Values "2016";"01";"ALEMANIA";"95030070";244,03 "2016";"01";"ALEMANIA";"12099182";295,24 "2016";"01";"ALEMANIA";"82076000";351,93 "2016";"01";"ALEMANIA";"76072090";93898,24 "2016";"01";"ALEMANIA";"49011010";844,3 "2016";"01";"ALEMANIA";"29395900";250 "2016";"01";"ALEMANIA";"04061030";34649,19 "2016";"01";"ALEMANIA";"83024220";1317,35 "2016";"01";"ALEMANIA";"48202090";38,57 "2016";"01";"ALEMANIA";"95044000";45,76 "2016";"01";"ALEMANIA";"62114200";75,86 "PERIODO" "MES" "PAIS_ORIGEN" "ARANCEL" "TOTAL_CIF_ITEM_US$" "2016" "01" "AFGHANISTAN" "82060000" 4139,95 "2016" "01" "ALBANIA" "91021100" 189,63 "2016" "01" "ALBANIA" "64039110" 88192,68 "2016" "01" "ALEMANIA" "90272000" 17861,93 "2016" "01" "ALEMANIA" "72122000" 10360,82 "2016" "01" "ALEMANIA" "90283010" 904,32 "2016" "01" "ALEMANIA" "96170010" 4958,19 "2016" "01" "ALEMANIA" "73079300" 380,29 "2016" "01" "ALEMANIA" "95030070" 244,03 "2016" "01" "ALEMANIA" "12099182" 295,24 "2016" "01" "ALEMANIA" "82076000" 351,93 "2016" "01" "ALEMANIA" "76072090" 93898,24 "2016" "01" "ALEMANIA" "49011010" 844,3 "2016" "01" "ALEMANIA" "29395900" 250 "2016" "01" "ALEMANIA" "04061030" 34649,19 "2016" "01" "ALEMANIA" "83024220" 1317,35 "2016" "01" "ALEMANIA" "48202090" 38,57 "2016" "01" "ALEMANIA" "95044000" 45,76 "2016" "01" "ALEMANIA" "62114200" 75,86 .TSV Tab-Separated Values { "id" : 167291010, "name" : "Description", "dataTypeName" : "text", "description" : "Text description of the specific charge.", "fieldName" : "description", "position" : 6, "renderTypeName" : "text", "tableColumnId" : 20333367, "width" : 720, "cachedContents" : { "non_null" : 711721, "smallest" : ", ATTEMPTING TO DRIVE MOTOR VEHICLE ON HIGHWAY WITHOUT REQUIRED LICENSE AND AUTHORIZATION", "null" : 5, "largest" : "XX", "top" : [ { "count" : 20, "item" : "DRIVER FAILURE TO OBEY PROPERLY PLACED TRAFFIC CONTROL DEVICE INSTRUCTIONS" }, { "count" : 19, "item" : "DRIVING VEHICLE ON HIGHWAY WITH SUSPENDED REGISTRATION" .JSON JavaScript Object Notation <Row> <Cell> <Data ss:Type="String">RESUMEN GASTOS CONSEJEROS REGIONALES</Data> </Cell> </Row> <Row> <Cell> <Data ss:Type="String">PERIODO DICIEMBRE 2012</Data> </Cell> </Row> <Row ss:Index="4"> <Cell ss:Index="5"> <Data ss:Type="String">A S I S T E N C I A</Data> </Cell> <Cell ss:Index="8"> <Data ss:Type="String">SESIONES ORDINARIAS Y EXTRAORDINARIAS</Data> </Cell> </Row> <Row> <Cell> <Data ss:Type="String">NOMBRE CONSEJERO</Data> </Cell> </Row> .XML eXtesible Markup Language PYTHON CONSEJOS o envía un mail a ejsandoval@uc.cl