introducción a python - argentina en python · baterías incluídas datetime, os, threading,...

42
Introducción a Python Manuel Kaufmann [email protected] http://elblogdehumitos.com.ar/ Universidad Autónoma de Encarnación Mayo 2015

Upload: others

Post on 09-Oct-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Introducción a Python

Manuel [email protected]

http://elblogdehumitos.com.ar/

Universidad Autónoma

de Encarnación

Mayo 2015

Page 2: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

-DisclaimerNuevo en Jupyter1 y Pysenteishon2

Introducción a Python

[1] https://jupyter.org/[2] https://github.com/edvm/pysenteishon/

Page 3: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

“Python es un lenguaje de programación poderoso y fácil de aprender…

– http://tutorial.python.org.ar

Introducción a Python

Page 4: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

“… y está buenísimo– Python Argentina

Introducción a Python

Page 5: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Agenda

● ¿Qué es Python?

● Intérprete interactivo

● Manipulando datos

● Tomando decisiones

● Organizando el código

Introducción a Python

Page 6: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

1¿Qué es Python?Propiedades y características

Introducción a Python

Page 7: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Características básicas

● Gratis y Libre

● Maduro e inquieto (+24 años)

● Fácil de aprender

● Sintaxis limpia y simple

● “Demasiado” portable

(Windows, Linux, Mac, Android, …)

● Enorme comunidad

Introducción a Python

Page 8: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Propiedades del lenguaje

● Compila a bytecode interpretado

✔ La compilación es implícita y automática

✔ Tipado dinámico, pero fuerte

● Multi-paradigma ✔ Todo es un objeto

✔ Pero puede usarse de manera procedural

● Manjeo moderno de errores

Introducción a Python

Page 9: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Características “pulenta”

● Baterías incluídas

✔ Extensa biblioteca estándar

● Tipos de datos de alto nivel✔ Enteros sin límites, strings, diccionarios, listas

✔ Pero puede usarse de manera procedural

● Intérprete interactivo✔ Permite explorar, probar e incluso ver la doc

Introducción a Python

Page 10: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Baterías incluídas

datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging, socket, json, math, glob, urlparser, optparser, sqlite3, subprocess, hashlib, collections, antigravity, decimal, pdb, gettext, md5, user, smtplib, shutil, webbrowser, xml, turtle, encodings, time, doctest, mutex, email…

Introducción a Python

Page 11: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Baterías añadidas

● Base de datos

✔ MySQL, PostgreSQL, Sybase

● Interfaces gráficas✔ Qt, GTK, win32, wxWidgets

● Frameworks Web✔ Django, webpy, Flask

● Imágenes, Juegos, Ciencia…

Introducción a Python

Page 12: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Python Argentina

● ¿Quienes somos?

✔ Grupo de entusiastas del lenguaje

● ¿Cómo participar?

✔ Suscribiéndote a la Lista de Correo (~ 1300)

✔ Canal de IRC: #pyar en Freenode

● PyAr es federal

✔ Eventos en todas las provincias

Introducción a Python

http://python.org.ar

Page 13: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

2Intérprete interactivoAcción y diversión

Introducción a Python

Page 14: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

-Preguntas¡Decilo!

Introducción a Python

Page 15: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

3Manipulando datosTipos y usos

Introducción a Python

Jupyter Notebook

Page 16: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Números

● Enteros✔ Suma

✔ Paréntesis

✔ Módulo

✔ Potencia

● Float

● Otras bases (0xf4, hex(), bin())

Introducción a Python

http://bit.ly/1HsoOIV

Page 17: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Strings (cadenas)

● Comillas, apóstrofes y multilínea

● Operaciones

✔ Suma

✔ Multiplicación

● Funciones y métodos

✔ len()

✔ .encode('utf-8')

Introducción a Python

http://bit.ly/1L6wUVp

Page 18: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Acceso a strings (cadenas)

● Posicionales

✔ Indice (positivo / negativo)

● Rebanadas

✔ [cerrado, abierto)

✔ Indices (positivo / negativo / omitido)

● De a saltos

Introducción a Python

Page 19: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Listas

● Diferentes tipos de elementos

● Accedemos como cualquier secuencia

● Concatenamos, reemplazamos, borramos

● Listas dentro de listas

● Métodos

✔ .index(“elemento”)

✔ .sort()

Introducción a Python

http://bit.ly/1AcVMuh

Page 20: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Conjuntos

● Diferentes tipos de elementos

● Se definen con llaves y valores

● Propiedades matemáticas de conjuntos

● Operaciones ( | & - …)

✔ .update([…])

✔ .intersection({…})

✔ .union({…})

Introducción a Python

http://bit.ly/1AcVrrK

Page 21: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Diccionarios

● Diferentes tipos de elementos

● Se definen con llaves y pares (key, value)

● No poseen orden

● Operaciones

✔ .keys()

✔ .get(…)

✔ .copy()

Introducción a Python

http://bit.ly/1JXn3kv

Page 22: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

-Preguntas¡Decilo!

Introducción a Python

Page 23: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

4Tomando decisionesSi pasa esto, voy por acá

Introducción a Python

Page 24: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Si pasa, esto… si no, aquello…

● Estructura

✔ if, elif, else

● Comparadores

✔ or, and, not

✔ < > == != <= >= in is

✔ Todo evalúa a True o False

Introducción a Python

http://bit.ly/1Fybhit

Page 25: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Por cada elemento…

● Estructura

✔ for, in

● continue, break, else

● ¿Se terminó la secuencia?✔ Sigo

✔ Paro

● ¿Y si necesitamos sólo números?

Introducción a Python

http://bit.ly/1IOXWBz

Page 26: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Mientras suceda…

● Estructura

✔ while

● continue, break, else

● ¿Se cumple la condición?✔ Sigo

✔ Paro

Introducción a Python

http://bit.ly/1FsNdMg

Page 27: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Excepciones

● Estructura

✔ try, except

● else, finally

● Algo se escapa de lo normal✔ Podemos capturarlas

✔ Nos aparece un error

● Podemos generar excepciones

Introducción a Python

http://bit.ly/1dii43O

Page 28: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

-Preguntas¡Decilo!

Introducción a Python

Page 29: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

5Organizando el códigoFunciones, clases, módulos y paquetes

Introducción a Python

Page 30: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Funciones

● Definen un conjunto de operaciones

● Son objetos

● Amplia flexibilidad con los argumentos

✔ Opcionales

✔ Nombrados

✔ Cantidad indefinida

Introducción a Python

Page 31: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Clases

● Encapsulan valores y comportamiento

● Soporta herencia múltiple

… no voy a explicar el paradigma de objetos ;)

Introducción a Python

Page 32: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Módulos

● Funciones, clases, constantes en un archivo

● Es un .py normal que lo importo

Introducción a Python

Page 33: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Paquetes

● Un conjunto de módulos

● Ni más ni menos que un directorio normal

● Utilizamos un archivo __init__.py

Introducción a Python

Page 34: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

-Preguntas¡Decilo!

Introducción a Python

Page 35: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

0Algunas perlitasSyntactic sugar, tipos 'copados', decoradores

Introducción a Python

Jupyter Notebook

Page 36: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Generadores

● Similar a los iterables

● Generan los elementos cuando es necesario

● Optimizan los recursos

Introducción a Python

Page 37: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

List Comprehensions

● Operaciones rápidas sobre iterables

● Puede dificultar la lectura

Introducción a Python

Page 38: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Context Managers

● Estructura

✔ with

● Dentro de un contexto

● Ejecutar “algo” al ingresar y al salir

Introducción a Python

Page 39: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Namespaces

● Muy útiles para organizar el código

● Aislan diferentes espacios de variables

● Local y global

Introducción a Python

Page 40: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Tipos “copados”

● collections.namedtuple

● collections.deque

● collections.OrderedDict

● collections.defaultdict

Introducción a Python

Page 41: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

Decoradores

● Se meten en el medio de la función

● Muy útiles para logging

● Hacen algo antes y/o después de la llamada

Introducción a Python

Page 42: Introducción a Python - Argentina en Python · Baterías incluídas datetime, os, threading, urllib, unittest, sys, zipfile, csv, re, random, Tkinter, tarfile, mimetypes, logging,

argentina

en

¿Preguntas? ¿Sugerencias?

Gracias por su tiempo …

… y espero que hayan disfrutado

[email protected]

http://elblogdehumitos.com.ar/

Manuel Kaufmann

Este obra está bajo una licencia de Creative CommonsReconocimiento-CompartirIgual 4.0 Internacional.

Introducción a Python