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                >>> abs(-3)

    help               >>> help([])

    len                >>> len("hello")

    max                >>> max(3, 5)

    min                >>> min(3, 4)

    range              >>> range(1,6)

    round              >>> 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()          >>> primero.displayNombre()
>>> segundo = claseNombre()         >>> segundo.displayNombre()
>>> primero.createNombre('UNI') >>> 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              #Nueva Ventana
#modulomio.py               #modulomio.py
def testmod():              def testmod():
  print "Este es un Test“        print "Este es un NUEVO
En la Terminal                MODULOS“
>>> import modulomio        En la Terminal
>>> holas=                  >>> import modulomio
  modulomio.testmod()       >>> 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 AQUIn')
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.movie
pygame.cursors       pygame.music
pygame.display       pygame.overlay
pygame.draw          pygame Contains
pygame.event         pygame.rect
pygame.font          pygame.sndarray
pygame.image         pygame.sprite
pygame.joystick      pygame.surface
pygame.key           pygame.surfarray
pygame.mixer         pygame.time
pygame.mouse         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

Python Tercera Sesion de Clases

  • 1.
    Python + Sugar Carlos Mauro Cardenas Fernandez http://unimauro.blogspot.com http://www.twitter.com/unimauro [email protected]
  • 2.
    if else elif #001.py animal=raw_input("Escribeen 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"
  • 3.
    Sentencias de ControlAnidadas accion1="Correr" accion2="Parar“ if accion1=="Correr": if accion2=="Parar": print "Avanzo 2 espacios" elif: print "Sigue avanzando" else: print "Permanece parado"
  • 4.
    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
  • 5.
    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
  • 6.
    for and while Repeticioneso 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
  • 7.
    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]
  • 8.
    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
  • 9.
    Repeticiones infinitas yel 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
  • 10.
    Funciones por Defecto  abs >>> abs(-3)  help >>> help([])  len >>> len("hello")  max >>> max(3, 5)  min >>> min(3, 4)  range >>> range(1,6)  round >>> round(10.2756, 2)
  • 11.
    Funciones deb: >>> defcadena(y): return y+'Es una cadena' >>> print cadena('Hola') >>> print cadena('Bien') >>> def cubo(x): return math.pow(x,3) >>> print cubo(10)
  • 12.
    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)
  • 13.
    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')
  • 14.
    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 )
  • 15.
    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)
  • 16.
    Programación Orientada aObjetos >>> class clasePython: ojos="negros" edad="21" def thisMethod(self): return 'Hey eres tú’ >>> clasePython >>> claseObject=clasePython() >>> claseObject.edad >>> claseObject.ojos >>> claseObject.thisMethod()
  • 17.
    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() >>> primero.displayNombre() >>> segundo = claseNombre() >>> segundo.displayNombre() >>> primero.createNombre('UNI') >>> primero.decir(): >>> >>> segundo.decir():
  • 18.
    Sub Clases YSuper Clases >>> class clasePapa: var1="variable 1" var2="variable 2" >>> class claseHijo(clasePapa): pass >>> objPapa=clasePapa() >>> objPapa.var1 >>> objHijo=claseHijo() >>> objHijo.var2
  • 19.
    Sobre Escribir unaVariable >>> 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
  • 20.
    Importando Mas MódulosCreados Por Nosotros #Nueva Ventana #testmodulos.py def testmod(): print "Este es un Test" En la Terminal >>> import testmodulos >>> testmodulos.testmod()
  • 21.
    Recargando Módulos #Nueva Ventana #Nueva Ventana #modulomio.py #modulomio.py def testmod(): def testmod(): print "Este es un Test“ print "Este es un NUEVO En la Terminal MODULOS“ >>> import modulomio En la Terminal >>> holas= >>> import modulomio modulomio.testmod() >>> holas= modulomio.testmod() >>> reload(modulomio)
  • 22.
    Informacion de losMódulos >>> import math >>> math.sqrt(100) >>> dir(math) >>> import time >>> dir(math) >>> help(math) >>> math.__doc__
  • 23.
    Modulo de datetime >>>from datetime import datetime >>> the_time = datetime.now() >>> the_time.ctime()
  • 24.
    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()
  • 25.
    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 AQUIn')
  • 26.
    Escribiendo Líneas >>> fob=open('c:/python26/test.txt','r') >>> linea = fob.readlines() >>> linea >>> fob.close() >>> linea[2]="Mirando Mirando" >>> linea
  • 27.
    Simulador de Números importrandom 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)
  • 28.
    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.
  • 29.
    #Arhivo tanque.py class Tanque(object): def __init__(self, name): self.name = name self.vida = True self.armadura = 5 self.municion = 60
  • 30.
    #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
  • 31.
    #Arhivo tanque.py Continuacion deffuego_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!"
  • 32.
    #Arhivo tanque.py Continuacion defhit(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!"
  • 33.
    #Arhivo tanquejuego.py from tanqueimport Tanque tanques = { "a":Tanque("Alice"), "b":Tanque("Bob"), "c":Tanque("Carol") } vida_tanques = len(tanques)
  • 34.
    #Arhivo tanquejuego.py Continuación whilevida_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
  • 35.
    #Arhivo tanquejuego.py Continuación ifnot 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
  • 36.
    #Arhivo tanquejuego.py Continuación fortanque in tanques.values(): if tanque.vida: print tanque.name, "Este Tanque GANO!" break
  • 37.
    PyGame pygame.cdrom pygame.movie pygame.cursors pygame.music pygame.display pygame.overlay pygame.draw pygame Contains pygame.event pygame.rect pygame.font pygame.sndarray pygame.image pygame.sprite pygame.joystick pygame.surface pygame.key pygame.surfarray pygame.mixer pygame.time pygame.mouse pygame.transform
  • 39.
    Py Game >>> importpygame >>> print pygame.ver if pygame.font is None: print “No se encuentra los FONT" exit()
  • 40.
    #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()
  • 41.
    #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()
  • 45.