Python Tercera Sesion de Clases

Preview:

DESCRIPTION

Sentencias de Control, Bucles, Funciones, Clases y Pygame

Citation preview

Python +

Sugar

Carlos Mauro Cardenas Fernandez

http://unimauro.blogspot.com

http://www.twitter.com/unimauro

unimauro@gmail.com

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"

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"

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

<

<=

>

>=

==

!=

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

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

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]

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

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

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)

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)

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)

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')

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 )

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)

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()

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():

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

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

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()

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)

Informacion de los Módulos

>>> import math

>>> math.sqrt(100)

>>> dir(math)

>>> import time

>>> dir(math)

>>> help(math)

>>> math.__doc__

Modulo de datetime

>>> from datetime import datetime

>>> the_time = datetime.now()

>>> the_time.ctime()

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()

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')

Escribiendo Líneas

>>> fob =open('c:/python26/test.txt','r')

>>> linea = fob.readlines()

>>> linea

>>> fob.close()

>>> linea[2]="Mirando Mirando"

>>> linea

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)

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.

#Arhivo tanque.py

class Tanque(object):

def __init__(self, name):

self.name = name

self.vida = True

self.armadura = 5

self.municion = 60

#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

#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!"

#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!"

#Arhivo tanquejuego.py

from tanque import Tanque

tanques = { "a":Tanque("Alice"), "b":Tanque("Bob"),

"c":Tanque("Carol") }

vida_tanques = len(tanques)

#Arhivo tanquejuego.py Continuación

while vida_tanques > 1:

print

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

#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

#Arhivo tanquejuego.py Continuación

for tanque in tanques.values():

if tanque.vida:

print tanque.name, "Este Tanque

GANO!"

break

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

Py Game

>>> import pygame

>>> print pygame.ver

if pygame.font is None:

print “No se encuentra los FONT"

exit()

#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()

#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()

Bibliografía