28
Taller de Python

Python Tutorial Presentation

Embed Size (px)

Citation preview

Page 1: Python Tutorial Presentation

Taller de Python

Page 2: Python Tutorial Presentation

Introduccion a Python

• "Scripting Language"o Interpretadoo Dinamico

Page 3: Python Tutorial Presentation

"Python Console"

Ejecutando Python:

% pythonPython 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] onwin32Type "help", "copyright", "credits" or "license" for more information.>>>

Page 4: Python Tutorial Presentation

"Hello World" en Python

En la consola:

% python>> print "Hello, World!"Hello, World

O en un archivo:

# hello_world.pyprint "Hello, World"

% python hello_world.pyHello, World

Page 5: Python Tutorial Presentation

Expresiones Matematicas

Las operaciones matematicas funcionan igual que en otros lenguajes:

% python>> 1 + 12>> 1 * 2 + 35>> 2**38

Page 6: Python Tutorial Presentation

Variables

Las variables en Python no necesitan un tipo como lo es en C++ o en Java. Para declarar un variable solamente excribes el nombre de la variable seguido por un valor:

a = 1000saludo = "Hola"gravedad = -9.81

El interpretador de Python reconocera los tipos de cada variable automaticamente.

Page 7: Python Tutorial Presentation

Bloques

Un bloque es un grupo de instruciones, por ejemplo un if,un while o una funcion:

if a > b:    return a

Los bloques en Python no se indican con corchetes ({ }) como en otros lenguajes, sino por espacios ("Indentation").

if a > b:    a = a + b    b = b + a    return a * b

Page 8: Python Tutorial Presentation

Bloques (...)

La estructura basica de los bloques:

keyword expression:    statement 1    statement 2    ...out_of_the_block_statement

El proximo enunciado que no este a la misma cantidad de espacios del anterior termina el bloque.

Page 9: Python Tutorial Presentation

Condicionales (if)

if-else:if a < b and c > d:    return a + b + c + delse    return 0if-elif-else:if a > b:    return aelif a < b and b > c    return belse:    return c

Page 10: Python Tutorial Presentation

Condicionales (...)

pass:if a > b:    return aelse:    passImplicit and:if a < b < c:    # No se puede en C++    return b

Page 11: Python Tutorial Presentation

"Loops" (while y for)

while:while a < b:    print a    b += 1   # No existe b++for:for i in range(100):    print i

Page 12: Python Tutorial Presentation

Funciones

Declaracion de una funcion:

def f(a, b, c):    return a + b + c

def hello():    print "Hello"

Llamadas a funciones:

a = f(1, 2, 3)hello()

Page 13: Python Tutorial Presentation

Clases

Declaracion de un clase:class ClassName:    def __init__(self):        pass    def f(self):        passInstanciacion de una clase:c = ClassName()c.f()

Page 14: Python Tutorial Presentation

Tipos de Datos

Tipos de datos basicos:a = 100        # intb = 80.8       # floatc = "Hello"    # stringSequencias:t = (1, 2, 3, 4)            # tuplel = [1, 2, 3, 4]             # listad = {'a':1, 'b':2, 'c':3}   # diccionario

Page 15: Python Tutorial Presentation

Tipos de Datos (Sequencias)

Tuple - Arreglos immutables:t = (1, 2, 3, 4)Lista - Arreglos mutables":l = [1, 2, 3, 4]Diccionario - Arreglos indexables:d = {'a':1, 'b':2, 'c':3}

Page 16: Python Tutorial Presentation

Ejemplos

Page 17: Python Tutorial Presentation

Modulos

• Los modulos en Python son lo que se le conoce como librerias en otros lenguajes.

• Cualquier archivo valido de Python puede ser un modulo.

Page 18: Python Tutorial Presentation

Modulos (...)

Para utilizar un modulo, este se debe importar de la siguiente manera:

import modulename

Por ejemplo, el siguiente codigo importa el modulo os:

import os

Multiples modulos se pueden importar de la siguiente manera:

import os, sys, Tkinter

Page 19: Python Tutorial Presentation

"File I/O"

open() - Abre un archivof1 = open( 'filename1.txt', 'w' )f2 = open( 'filename2.txt', 'r' )read() -  Lee todo el archivodata = f2.read()write() - Escribe en el archivof2.write(data)Leer un archivo linea por linea:for line in f2:    print line

Page 20: Python Tutorial Presentation

Modulo os

• Encapsula las operaciones basicas del systema operativo como las siguientes:o Creacion y manejo de archivoso Creacion y manejo de directorioso ...

Page 21: Python Tutorial Presentation

Modulo os (...)

os.listdir() - Enlista todos el contenido de un directorioos.listdir('tmp')os.mkdir() - Crea un directorioos.mkdir( 'my_directory' )os.remove() - Borra un archivoos.remove( 'text.txt' )os.rmdir()  - Borra un directorio (si esta vacio)os.rmdir( 'my_directory' )

os.rename() - Cambia el nombre de un archivoos.rename( 'name.txt', 'other.txt' )

Page 22: Python Tutorial Presentation

Modulo os.path

os.path.exist() - Devuelve cierto si el archivo indicado existeif os.path.exist( 'name.txt' ):    print "Ok"os.path.basename() - Devuelve el nombre base de un 'path'print os.path.basename( 'my\folder\1\name.txt' )name.txtos.path.join() - Une a dos o mas 'paths'print os.path.join( 'my\folder', 'is', 'this\name.txt')my\folder\is\this\name.txt

Page 23: Python Tutorial Presentation

Ejemplos

Page 24: Python Tutorial Presentation

Programacion Grafica (GUIs)

• Python provee una interface graphica a traves del modulo Tkinter.

• Aunque un poco limitado el modulo Tkinter es muy facil de utilizar y applicaciones con interface graphica se pueden lograr con muy poco esfuerzo

Page 25: Python Tutorial Presentation

Ejemplos

Page 26: Python Tutorial Presentation

"Networking"

• Python provee muchas facilidades para trabajar con Networking.

• Los modulos socket y SocketServer se pueden utilizar para crear servidores y aplicaciones cliente muy facilmente.

Page 27: Python Tutorial Presentation

Ejemplos

Page 28: Python Tutorial Presentation

THE END

Wait for the sequel...