Python Tercera Sesion de Clases
-
Upload
carlos-cardenas -
Category
Documents
-
view
2.551 -
download
0
description
Transcript of Python Tercera Sesion de Clases
![Page 1: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/1.jpg)
Python +
Sugar
Carlos Mauro Cardenas Fernandez
http://unimauro.blogspot.com
http://www.twitter.com/unimauro
![Page 2: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/2.jpg)
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"
![Page 3: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/3.jpg)
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"
![Page 4: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/4.jpg)
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
<
<=
>
>=
==
!=
![Page 5: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/5.jpg)
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
![Page 6: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/6.jpg)
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
![Page 7: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/7.jpg)
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]
![Page 8: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/8.jpg)
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
![Page 9: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/9.jpg)
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
![Page 10: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/10.jpg)
Funciones por Defecto
abs help len max min range round
>>> abs(-3)
>>> help([])
>>> len("hello")
>>> max(3, 5)
>>> min(3, 4)
>>> range(1,6)
>>> round(10.2756, 2)
![Page 11: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/11.jpg)
Funciones deb:
>>> def cadena(y):
return y+'Es una cadena'
>>> print cadena('Hola')
>>> print cadena('Bien')
>>> def cubo(x):
return math.pow(x,3)
>>> print cubo(10)
![Page 12: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/12.jpg)
Parametros por Defecto
>>> def nombres(nombre, apepa,apema):
print "%s %s %s" % (nombre, apepa,apema)
>>> def nombres(nombre='NN',
apepa='NN',apema='NN'):
print "%s %s %s" % (nombre,
apepa,apema)
![Page 13: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/13.jpg)
Enviando Parametros Múltiples
>>> def listas(*algo):
print algo
>>> listas('frutas')
>>> listas('uva','fresa','piña','mango','pera')
>>> def portafolio(codigo, *cursos):
print codigo
print cursos
>>> portafolio('20090001','MA100','MA101','MA102')
![Page 14: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/14.jpg)
Diccionarios como Parametros
>>> def carta(**listado):
print listado
>>> carta(chifa=7,pollo=9,parrillada=8)
>>> def recibos(tipo,*responsable,**montos):
print tipo
print responsable
print montos
>>> recibos('impuestos', 'sunat', 'municipalidad', igv=19,
autovaluo=4 )
![Page 15: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/15.jpg)
Tuplas como Parametros
>>> def calificacion(a,b,c):
if a+b+c="10":
return 'Buena Nota'
else:
return 'desparobado'
>>> puntos=(5,5,0)
>>> calificacion(*puntos)
>>> def familia(**habi):
print habi
>>> padres={'mama'=45, 'papa'=48}
>>> familia(**padres)
![Page 16: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/16.jpg)
Programación Orientada a
Objetos >>> class clasePython:
ojos="negros"
edad="21"
def thisMethod(self):
return 'Hey eres tú’
>>> clasePython
>>> claseObject=clasePython()
>>> claseObject.edad
>>> claseObject.ojos
>>> claseObject.thisMethod()
![Page 17: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/17.jpg)
Clases y self>>> class claseNombre:
def createNombre(self,name):
self.name=name
def displayNombre(self):
return self.name
def decir(self):
print "hola %s" % self.name
>>> primer = claseNombre()
>>> segundo =
claseNombre()
>>>
primero.createNombre('UNI'
)
>>>
segundo.createNombre('FIIS
‘)
>>> primero.displayNombre()
>>>
segundo.displayNombre()
>>> primero.decir():
>>> segundo.decir():
![Page 18: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/18.jpg)
Sub Clases Y Super Clases
>>> class clasePapa:
var1="variable 1"
var2="variable 2"
>>> class claseHijo(clasePapa):
pass
>>> objPapa=clasePapa()
>>> objPapa.var1
>>> objHijo=claseHijo()
>>> objHijo.var2
![Page 19: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/19.jpg)
Sobre Escribir una Variable>>> class paremetros:
var1="Nombre"
var2="Apellido"
>>> class hijo(parametros):
var2="Es el Padre"
>>> pob.parametros()
>>> nin=hijo()
>>> pob.var1
>>> pob.var2
>>> nin.var1
>>> nin.var2
![Page 20: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/20.jpg)
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()
![Page 21: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/21.jpg)
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)
![Page 22: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/22.jpg)
Informacion de los Módulos
>>> import math
>>> math.sqrt(100)
>>> dir(math)
>>> import time
>>> dir(math)
>>> help(math)
>>> math.__doc__
![Page 23: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/23.jpg)
Modulo de datetime
>>> from datetime import datetime
>>> the_time = datetime.now()
>>> the_time.ctime()
![Page 24: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/24.jpg)
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()
![Page 25: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/25.jpg)
Leiendo y Escribiendo
>>> fob =open('c:/python26/leer.txt','r')
>>> print fob.readline()
>>> print fob.readlines()
>>> fob.close()
>>> fob =open('c:/python26/leer.txt','w')
>>> fob.write('Holas AQUI\n')
![Page 26: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/26.jpg)
Escribiendo Líneas
>>> fob =open('c:/python26/test.txt','r')
>>> linea = fob.readlines()
>>> linea
>>> fob.close()
>>> linea[2]="Mirando Mirando"
>>> linea
![Page 27: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/27.jpg)
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)
![Page 28: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/28.jpg)
Juego de Tanques
Posicion: ¿ Dónde esta el Tanque? Direccion: ¿En que dirección se está moviendo? Rapidez: ¿ Que tan rápido es? Armadura: armadura ¿Cuánto tiene? Municion: ¿Cuántos depósitos tiene? Mover: Mover el tanque. Rotar: Rotar el Tanque izquierda/derecha. Fuego: Lanzar un disparo. Hit: Esta es la acción cuando un enemigo golpea el tanque. Explotar: El tanque sufre una explosión.
![Page 29: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/29.jpg)
#Arhivo tanque.py
class Tanque(object):
def __init__(self, name):
self.name = name
self.vida = True
self.armadura = 5
self.municion = 60
![Page 30: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/30.jpg)
#Arhivo tanque.py
Continuacion def __str__(self):
if self.vida:
return "%s (%i municion, %i DISPAROS)"%(self.name,
self.municion, self.armadura)
#return self.name+" ("+str(self.municion)+" municion,
"+str(self.armadura)+" DISPARO)"
else:
return "%s (MURIO)"%self.name
![Page 31: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/31.jpg)
#Arhivo tanque.py
Continuacion def fuego_en(self, enemigo):
if self.armadura >= 1:
self.armadura-= 1
print self.name, "FUEGO EN", enemigo.name
enemigo.hit()
else:
print self.name, "NO LE DIERON!"
![Page 32: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/32.jpg)
#Arhivo tanque.py
Continuacion def hit(self):
self.municion-= 20
print self.name, "LE DIERON"
if self.municion <= 0:
self.exploto()
def exploto(self):
self.vida = False
print self.name, "exploto!"
![Page 33: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/33.jpg)
#Arhivo tanquejuego.py
from tanque import Tanque
tanques = { "a":Tanque("Alice"), "b":Tanque("Bob"),
"c":Tanque("Carol") }
vida_tanques = len(tanques)
![Page 34: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/34.jpg)
#Arhivo tanquejuego.py Continuación
while vida_tanques > 1:
for tanque_name in sorted( tanques.keys() ):
print tanque_name, tanques[tanque_name]
primero = raw_input("Quien Dispara? ").lower()
segundo = raw_input("A quien? " ).lower()
try:
primero_tanque = tanques[primero]
segundo_tanque = tanques[segundo]
except KeyError:
print "No se encontro el tanque!"
continue
![Page 35: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/35.jpg)
#Arhivo tanquejuego.py Continuación
if not primero_tanque.vida or not segundo_tanque.vida:
print "Uno de esos tanques murio!"
continue
print "*"*30
primero_tanque.fuego_en(segundo_tanque)
if not segundo_tanque.vida:
vida_tanques-= 1
print "*"*30
![Page 36: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/36.jpg)
#Arhivo tanquejuego.py Continuación
for tanque in tanques.values():
if tanque.vida:
print tanque.name, "Este Tanque
GANO!"
break
![Page 37: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/37.jpg)
PyGame
pygame.cdrom
pygame.cursors
pygame.display
pygame.draw
pygame.event
pygame.font
pygame.image
pygame.joystick
pygame.key
pygame.mixer
pygame.mouse
pygame.movie
pygame.music
pygame.overlay
pygame Contains
pygame.rect
pygame.sndarray
pygame.sprite
pygame.surface
pygame.surfarray
pygame.time
pygame.transform
![Page 38: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/38.jpg)
![Page 39: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/39.jpg)
Py Game
>>> import pygame
>>> print pygame.ver
if pygame.font is None:
print “No se encuentra los FONT"
exit()
![Page 40: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/40.jpg)
#holaPygame.py
#!/usr/bin/env python
back_img_fn = ‘Imagen.jpg‘
mouse_img_fn = ‘mouse.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption(“HOLA A TODOS!")
background = pygame.image.load(back_img_fn).convert()
mouse_cursor = pygame.image.load(mouse_img_fn).convert_alpha()
![Page 41: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/41.jpg)
#Continua holaPygame.py
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
![Page 42: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/42.jpg)
![Page 43: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/43.jpg)
![Page 44: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/44.jpg)
![Page 45: Python Tercera Sesion de Clases](https://reader036.fdocuments.mx/reader036/viewer/2022062418/555a6fc7d8b42ae7218b5296/html5/thumbnails/45.jpg)
Bibliografía