Vous êtes sur la page 1sur 78

http://www.eqsoft.

net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

Da1:
1.InstalandoPython(enLinux)
2.Elentornodeconsola
3.Variablesyconstantes
Da2:
4.Trabajocontiposdedatos
5.Trabajoconcadenas
6.Estructurasdecontrol
Da3:
7.Manejosdeerrores
8.Funciones
Da4:
9.Objetos
10.Conexionesabasededatos,ObjetosdeMysqlyPgsql
Da5:
11.Libreradesistemaoperativoytiempo
12.Creandolibrerasyparmetrosentrescripts

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

1.InstalandoPython(enLinux)
PythonenLinuxesmuyfcildeinstalar,deechoesprcticamentela
basedetantasherramientasdesoftwarelibrequegeneralmenteyaviene
pordefecto.
PorquelosprogramadoresprefierenusarPython?
a.TeobligaaprogramarmaslimpioquelenguajescomoPHP
b.SuengineesmasligeroqueeldePHPoJava
c.Esmultiplataforma
d.Soporteparaprogramarscripts,guiappsywebapps
e.Altamenteescalable
f.EsSIMPLE

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

1.InstalandoPython(enLinux)
PlataformasRPM(redhat,centOS,Fedora)
yuminstallpython
PlataformasDEB(Debian,Knoppix,Ubuntuentodassusvariantes)
aptgetinstallpython

OjO:vanaencontrarvariasramasdePythoncomola2.4,2.5,2.6,2.8,3.0;
larama2.xeslamasusadayconmayordesarrolloporelmomento,la3.0
podranotenertodoloquenecesitas.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

1.InstalandoPython(enLinux)
InstalarPythonconloscomandosanteriormentemencionadossolo
instalaelenginebase,pythoncuentaconunagranvariedaddelibreras
paradiferentesfuncionesycadaunadeestasconsuspropias
dependencias,porejemplo:
SideseamosinstalarlaslibrerasdeconexinaPostgreSQLdebemos
primeroinstalarpython,luegoinstalarunadelaslibrerasdeconexina
Postgresqlcomoesto:
aptgetinstallpythonpgsql
EstoinstalarprimeroelclientedeCdePostgresqlytodassus
dependenciasyluegoalfinallalibrerapythonpgsql.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

1.InstalandoPython(enLinux)
Luegodeinstaladoalejecutarpythonenlaconsolatenemosalgocomo
esto:

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

2.Elentornodelaconsola
ElentornodelaconsolanospermiteaprenderPythondeunamanera
massencilla,sepuedeprobarfuncionalidadessencillasysintaxisdel
lenguaje.
Comandosbsicos:
printholamundo<imprimealgoenlaconsola
A=22<crealavariableA
printA<imprimeelvaloralmacenadoenlavariableA
b=input(dame#:)<solicitaenlaconsolaingresarunvalorylo
guardaenlavariableb
Sepuedehacermas?

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

2.Elentornodelaconsola
(Los...significanuntab)
a=3
ifa<3:
...printesmenorque3
else:
...printesmayoroigualque3
presionar2vecesenterenlaultimalineaylaconsolasoltaraeste
mensaje:
esmayoroigualque3

Escribirsentenciascomplejasenlaconsolaescomplicado,unerrorde
sintaxishacevolveraescribirtodalasentencia,estoesmuyincmodo.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

2.Elentornodelaconsola

ParaprogramarenPythonesmejorutilizaruneditordetextocualquierao
algunoespecializadoenestelenguaje,grabarelprogramacomoun
archivodeextensin.py(noobligatorio)yluegoejecutarlosas:
pythonholamundo.py
Elresultadoloveremosenlaconsoladelsistemaoperativo.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

3.Variablesyconstantes
Pythonmanejavariostiposdedatos,eltipocorrespondealtipodedato
conelcualseinicializalavariable.
Tipossoportados:
Cadenas(strings)
Enteros
PuntoFlotante
Boolean
Compararlosresultados:
A=10A=10.0
printA/3printA/3

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

3.Variablesyconstantes
ExisteuntiponullqueenPythonseconocecomonone.
G=None
ifGisNone:
..printGesnulo
else:
...printGtienealgo:
Larespuestaes:
GesNulo
Lostiposbooleanseasignanas:

a=True<tomeencuentalaprimeraletraenmayscula
b=False

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

3.Variablesyconstantes
Arreglos.
EnPythonelconceptodeArregloesmuchomasespecializado.
*Lalista,esunconjuntodedatosingresadosenunaestructuranica,
nonecesitanserdelmismotipo(elndiceempiezaen0):
A=[1,4,6,'apesol']
forvalorinA:
...printvalor

Elresultadoes:
Elemento0:1
Elemento1: 4
Elemento2: 6
Elemento3: apesol
Practica:escribirprintA[3]

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

3.Variablesyconstantes
Arreglos.
*Lalista,incorporaelmtodoinsertparaaadirmaselementos,el
mtodoappendaadeunvaloradicionalinmediatamentealfinaldela
listayelcomandodeleliminaelementosdelalistadeunaposicin
determinada.
A.insert(4,'chicha')
delA[2]

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

3.Variablesyconstantes
Arreglos.
*Lastuplas,sonconjuntosdedatoscomoenunalistaperoes
inmutable,nosepuedeaadiroborrarelementos.
A='a',2,'c',4
forvalorinA:
...printvalor
Loselementosentreparntesisdenotanunatupladentrodeotra,este
principiosecumpleenlalista.

A='a',2,'c',4,('e',6)
forvalorinA:
...printvalor

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

3.Variablesyconstantes
Arreglos.
*Losdiccionariossoncomolosarreglostradicionales,tienenunndice
yunvalorcomopartedesuestructura,sepuedeaadiryquitardatos.
Arreglo={'a':123,'b':'holamundo',3:122}
printArreglo['b']
ahoraveamosqueobtenemosconesto:
forcinArreglo:
...printc

Yahoraas:
forcinArreglo:
...printArreglo[c]

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

3.Variablesyconstantes
Arreglos.
Lafuncinlen()permiteobtenerlacantidaddeelementosdentrode
unalista,tuplaodiccionario.
Elcomandodelpermiteeliminarunelementoeneldiccionario
haciendomencinalmismoysundice.
Parainsertarunelementoenunarreglosimplementehagamencindel
mismoycoloqueunnuevonombredendice(numerootexto)
Podemoscrearlistasdediccionarios:

a=({1:12,2:13},{1:21,2:23})
forcina:
...printc
...fordinc:
......printc[d]

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

4.TrabajoconTiposdeDatos
*Type,permitevereltipodedatosdeunavariable
x=10x=122332423423434x='abc'
type(x)type(x)type(x)
x=10.0x=Nonex=(1,2,3)x={1:10,2:20,3:30}
type(x)type(x)type(x)type(x)
*Intyfloat,convierteunfloataunenteroydeenteroafloat,puede
usarseconcadenasdetextoperoquenotenganliterales
x=10.0x=10
printx/3printx/3
printint(x)/3printfloat(x)/3

*Operadores+=,=,*=,/=parasuma,resta,multiplicacinydivisin
rpidaconelvaloryaalmacenado

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

4.TrabajoconTiposdeDatos
*%,elmoduloenlasdivisionesenteras
*//,paraladivisinentera
print9%2
print9//2
*str,transformacualquierobjeto/variableacadenadecaracteres
x=12
printstr(x)+'<elnumero'
*bool,permitetransformarunavariableabooleano,nomuyprctico.

X=12x=0x='abc'x=''x=None
printbool(x)printbool(x)printbool(x)print(x)print(x)

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

5.TrabajoconCadenas
ElmanejodecadenasenPythonesbastanteavanzadoynorequiere
funcionesexternas.
Concatenar:
a='hola'a='aaa'
b='mundo'a+='bbb'
printa+''+bprinta

Subcadena(elindicesiempreempiezaen0):

a='holamundo'
printa[3]<undgito
printa[5:10]<unaseccindecadena,comosubstr

printa[5:]<desdelaposicin5hastaelfinaldelacadena

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

5.TrabajoconCadenas
Subcadena(elindicesiempreempiezaen0):
a='holamundo'
printa[:5]<cortadesdeeliniciohastalaposicin5
printa[:5]<cortalosltimos5caracteresdelacadena
printa[2:5]<cortadesdelaposicin2hastalos5ltimos
caracteresdeunacadena
Unamaneradearmarcadenasformateadasesas:
X=12
Y=11
A=elvalordeXes:%dydeYes:%d%(X,Y)
printA

Len,retornalacantidaddecaracteresdeunacadena

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

5.TrabajoconCadenas
Unacadenaesunobjetoquetienevariosmtodosasociadosaella
mismatalescomo:
x='Hola,MunDO'
x.title()<primeraletradecadapalabraenmayscula
x.upper()<todalacadenaenmayscula
x.lower()<todalacadenaenminsculas
x.capitalize()<primeraletradelacadenaenmayscula
x.count('a')<cuentalacantidadde'a'enlacadena
x.find('a,')<ubicalaposicindelacadenadeltexto
ingresado
x.replace('a','4')<reemplazalas'a'por'4'
x.split(x)<cortalacadenaenunalista,cadapalabra
esunelementodelalista

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

5.TrabajoconCadenas
Caracteresespecialescomocomillasydoblescomillasdebenusarel
caracter\pordelante.
a=ySanMartindijo\VivaelPeru\
printa
Pararepetircadenas,multipliquelaporlacantidaddevecesrequerida
A='cuy'*5
printA
Nosepuedecambiarelvalordeuncaracterdeunacadena

A=cuy
A[2]='i'<daunerror

http://www.eqsoft.net
informes@eqsoft.net

6.EstructurasdeControl
Operadoresdecomparacion:
==<igual
<><diferente
Operadoreslogicos:
and
or
not

A=1
B=1
ifnota<>b:
...printAnoesdiferentedeB

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
informes@eqsoft.net

6.EstructurasdeControl
IF
ifa==b:
...printaybsoniguales
elifa>b:
...printaesmayorqueb
else
...printaybsondiferentes

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
informes@eqsoft.net

6.EstructurasdeControl
WHILE

X=10
Y=0
whileY<X:
...Y+=1
...printY

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

6.EstructurasdeControl
FOR,tienemuchasformasdeusarse

Enunrangodenmeros:
forainrange(1,10):<ejecutadel1al9
...printa
forainrange(10):<ejecutadel0al9
...printa
Enunalistadevalores:
forain(1,10,5,7):<puedeserunatuplaoundiccionario
..printa

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

6.EstructurasdeControl
FOR,tienemuchasformasdeusarse

Enunrangodenmeros:
forainrange(1,10,2):<ejecutadel1al9saltandode2en2
...printa
forainrange(10,1,3):<ejecutadel10al1saltandode3en3
...printa
fora,bin((1,4),(2,5),(3,6)):<soloseaceptavaloresnumricosenteros
...printa
...printb

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

6.EstructurasdeControl
Break,permitesalirdeunloop
forcinrange(1,10):<ejecutadel1al6
...printc
...ifc>5:
......break
Continue,permitevolveraiterarsinejecutarelcdigoquecontinuaenel
loop

forcinrange(1,10):<ejecutadel1al5
...ifc>5:
......continue
...printc

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

7.Manejodeerrores
Elcomandotrypermitecapturarlaposibilidaddequeseproceseun
errorenlaejecucindelsiguientecomandoparaqueelPythonnonos
botedelprograma.
try:
...a='abc'+123
except:
...printhayunerror

Elexceptrespondeadiferentesvaloresdependiendoelcomandoa
ejecutar,porejemplolaslibrerasdePostgreSQLtienendiferentes
exceptdependiendoeltipodeerror.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

7.Manejodeerrores
try:
...a='abc'+123
except:
...pass<passnohacenada
printsecomioelerror
Estasentenciadaerrorelcdigodebecontinuardebajodelniveldeltry

try:
...a='abc'+123
...printaquidebecontinuarelprograma
except:
...pass

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

7.Manejodeerrores
try:
...a='abc'+123
except:
...pass<passnohacenada
printsecomioelerror
Estasentenciadaerrorelcdigodebecontinuardebajodelniveldeltry
eneleditordeconsola,ejecutandounarchivo.pynosucedeerroryse
continuaconlaejecucindelprograma.
try:
...a='abc'+123
...printaquidebecontinuarelprogramasiestoyenconsola
except:
...pass

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

7.Manejodeerrores
try:
...a='abc'+123
except:
...raise('mensajito')<permitevertodoeltracebackdelerror
cortaelprogramaypermiteenviarunmensaje
finalpersonalizado
Existenvariostiposdeexceptparaelusocomndellenguajeestosson
losmasconocidos:

exceptRuntimeError:
printerrorenelsistema
exceptTypeError:
printerrordetipodedatos,comoelqueestamosgenerando
exceptNameError:
printcuandoseusaunnombredevariable/objetoquenoexiste

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

7.Manejodeerrores
Ejemploparaexplicar:
importsys<importaunalibrera
try:
f=open('myfile.txt')
s=f.readline()
i=int(s.strip())
exceptIOErroraserr:<tipodeexceptespecialdela
print("I/Oerror:{0}".format(err))libreriasyssinoOpen(myfile.txt)
exceptValueError:<seejecutacuandoint()nopuede
print("Couldnotconvertdatatoaninteger.")convertirelvaloraentero
except:<errorgenerico
print("Unexpectederror:",sys.exc_info()[0])
raise

http://www.eqsoft.net
informes@eqsoft.net

8.Funciones(Usareditordetexto)

defmi_funcion(mi_parametro):
...sentencias

Ejemplo:
defmi_raizcuadrada(pNumero):
...return(pNumero*pNumero)
printmi_raizcuadrada(4)
printmi_raizcuadrada(mi_raizcuadrada(4))

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
informes@eqsoft.net

8.Funciones(Usareditordetexto)

Paraasignarvalorespordefectoalosparametros:
defmi_raizcuadrada(pNumero=9):
...return(pNumero*pNumero)
printmi_raizcuadrada(4)
printmi_raizcuadrada()

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
informes@eqsoft.net

8.Funciones(Usareditordetexto)

defmi_funcion(mi_parametro):
...sentencias

Ejemplo:
defmi_raizcuadrada(pNumero):
...return(pNumero*pNumero)
printmi_raizcuadrada(4)
printmi_raizcuadrada(mi_raizcuadrada(4))

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

8.Funciones(Usareditordetexto)

Esposibleinvocarsolociertosparmetrosdeunafuncin
defmifuncion(a=1,b=2):
...returna+b
printmifuncion(2,3)
printmifuncion()
printmifuncion(b=3)

Perosilosvaloresnoinvocadosexplcitamentenotienevalorpordefecto
elPythondevolverunerror.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

8.Funciones(Usareditordetexto)

Esposiblepasarmasparmetrosdelosesperadosqueserecibenenuna
listaoenundiccionario
defmifuncion(parametro,*arguments,**keywords):
printparametro
forparametrosadicionalesinarguments:
printvalor:+parametrosadicionales
forindiceinkeywords:
printindice:+indice
printvalor:+keywords[indice]
return
mifuncion('a','b','c','d',uno='uno',dos=2,tres='tres')

OjOnosepuedeusardeindiceunnmero

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

8.Funciones(Usareditordetexto)
Lasfuncionespuedentenerfuncionesanidadas
defanidado1(argumento1):
...defanidado2(argumento2):
......returnargumento1+argumento2
...returnanidado2
...
f=anidado1(5)<enestemomentonooperanada,sologenerauna
f(3)funcinenmemoria
f(4)
d=anidado2(6)<estodaerror
printanidado1(5)<estodaunmensajedesistema

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

8.Funciones(Usareditordetexto)
Losparmetrosenlafuncinsoloestnactivosdentrodelamisma
funcin,lodeclaradofueradelafuncinpuedeserinvocadocomo
globalymodificadosifueranecesario.
A=6
defvalor():
..globalA
..printelvalores:+str(A)
..A+=10
..return
valor()
printelvalores:+str(A)

http://www.eqsoft.net
informes@eqsoft.net

8.Funciones(Usareditordetexto)
Lasfuncionespuedensimularretornarvariosvalores
defmifuncion(a,b):
returna*2,b*3
c,d=mifuncion(4,5)
printc
printd

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

8.Funciones(Usareditordetexto)
Losparmetrosvistoshastaelmomentosonporreferencia,solo
algunostiposdedatospuedenserpasadosporvalor,porejemploel
integeroelfloatsoninmutables,perolaslistasno.
defmifuncion(inmutable,mutable):
inmutable=inmutable+1
mutable.append(inmutable)
a=15
b=[15]
mifuncion(a,b)
printa
printb

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
EnsuformamasbsicapodemosdeclararclasesenPythondeesta
forma:
classMiClase:
...atributo1=123
...atributo2='abc'
...defmetodo1(self):
......printatributo:+str(self.atributo1)++self.atributo2
obj=MiClase()
obj.metodo1()
selfesunapalabrareservadayesunequivalenteathisenotros
lenguajes.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
EnsuformamasbsicapodemosdeclararclasesenPythondeesta
forma:
classMiClase:
...atributo1=123
...atributo2='abc'
...defmetodo2(self,valor):
......printatributo1+valor
obj=MiClase()
obj.metodo2(4)

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
Constructordeclasesusar__init__
classMiClase2:
...atributo1=12
...atributo3=[1,'b',3]
...def__init__(self,parametro1,parametro2):<selfsedebedeclararen
......ifparametro1<>None:todoslosmtodos
.........self.atributo1=parametro1
......self.atributo2=parametro2

obj=MiClase2(None,2)
printobj.atributo1
printobj.atributo2
printobj.atributo3
obj2=MiClase2(44,2)
printobj2.atributo1

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
Paraalgunoscasosespecialespodemosdesearconvertirunobjeto
enteroaunacadenadecaracteres,estosehacercon__str__
classMiClase:
...def__str__(self)
......returnmeconvertiencadena
obj=MiClase()
printobj

Tambinesposibleimplementarelmtodo__repr__paraobtenerun
efectosimilarperoconuntextoformateado.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
LosobjetosenPythonpermitencrearmasatributosdelosdefinidosenla
clase,demaneraindiscriminadalastimosamente:
obj=MiClase()
obj.atributoquenoexiste=1
printobj.atributoquenoexiste
Sinembargopodemossetearqueestonosucedaconelmtodo
__setattr__
classmiClase:
...atributo1=123
...def__setattr__(self,nombre,valor):
......printnomepuedescambiar,elparametroanadidoes:+nombre+yelvalores:+repr(valor)

obj=miClase()
obj.atributoquenoexiste=1

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
Paraelcasodequedeseemosadvertirsobreelhacergetaunatributo
quenoexisteusamoselmtodo__getattr__
classmiClase5:
...atributo1=123
...def__getattr__(self,name):
......print"losiento,noexisteatributo:"+name
obj=miClase5()
printvalor:+obj.atributo12

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
Paraborraratributosaadidosalobjetosusardel:
classmiClase5:
...atributo1=123
...def__getattr__(self,name):
......print"losientonoexistetributo:"+name
obj=miClase5()
obj.atributo12=1234
print"voyaborrarelatributoconelvalor:"+str(obj.atributo12)
delobj.atributo12
x=obj.atributo12

http://www.eqsoft.net
informes@eqsoft.net

9.Objetos
Paraevitarqueseborrenatributosaadidosalobjeto
classmiClase5:
...atributo1=123
..def__delattr__(self,name):
......print"nosepuedeborraratributo:"+name
obj=miClase5()
obj.atributo12=1
print"voyaborrar:"+str(obj.atributo12)
delobj.atributo12
printsigoaqui:+str(obj.atributo12)

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
Paradeclararsetygetalosatributossedebeoperarcomoeneste
ejemplo.
classmiClase6(object):
...def__init__(self):
......self.__valor=12<aquacabodedeclararunatributo
...defgetValor(self):privadoalusar__delantedelnombre
......print"Leyendonumerodelget"
.....returnself.__valor
...defsetValor(self,valor):
......print"Grabandoelvalorenelset"
......self.__valor=valor
...valor=property(getValor,setValor)

obj=miClase6()
printobj.valor
obj.valor=8

printobj.valor
printobj__valor<vaadarunerror

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

9.Objetos
Herencia,paradeclararlahayquedecirquelaclaseimplementaotraclase.
classUno:
...numero1=1
...defimprime1(self):
......print"estoyenlaclase1"
classDos(Uno):
...numero2=2
...defimprime2(self):
......print"estoyenlaclase2"
......Uno.imprime1(self)
...defimprime3(self):
......print"estoyenlaclase2,noinvoconadadelaclase1"

a=Dos()
a.imprime2()
a.imprime1()
a.imprime3()
printa.numero1
printa.numero2

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
ParaconectarsealasbasesdedatosPythonutilizadiversaslibreras
especializadasparaello,escomnqueinclusoparaunamismabasededatos
existamasdeunaalternativadelibreracomoenelcasodeMySQL.
Usaremosenestasdistribucionesdesderepositorios:
centOS:MySQLpython
Ubuntu:pythonmysqldb
http://www.mikusa.com/pythonmysqldocs/
centOS:postgresqlpython
Ubuntu:pythonpgsql
http://www.pygresql.org/pg.html
Enamboscasossonlasmismasperosellamandiferentelospaquetes
dependiendoladistribucindeLinuxqueseuse

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
try:
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
exceptMySQLdb.Error:
printLaclaseMySQLdbencontrounerror
except:
printnomepudeconectaraladb,errordesconocido

MySQLdbincluyesupropioexcept.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
try:
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
exceptMySQLdb.Error,error:
printerrorexacto:
printerror
except:
printnomepudeconectaraladb,errordesconocido

enestecasoerroresunalistade2elementosconelerrorexacto,elnmeroyel
mensaje

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
qry=select*fromagentes
cursor=dbMY.cursor()<antesdeejecutarunqueryesnecesariodeclararuncursor
cursor.execute(qry)
printcursor<estosolonosdevuelveladireccindememoriadelcursos
setdata=cursor.fetchall()<bajamosladatadelcursorauncontenedordelosdatos,
esunalistadelistas
printsetdata

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
qry=select*fromagentes
cursor=dbMY.cursor()
cursor.execute(qry)
setdata=cursor.fetchall()
forregistroinsetdata:<aspodemosobtenerladata
forcampoinregistro:
printcampo
print***************finregistro***************

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
qry=select*fromagentesXXXYYY
cursor=dbMY.cursor()
try:
cursor.execute(qry)
exceptMySQLdb.Error,error:
printerrorexacto:
printerror
except:
printerrordesconocidoenelquery
setdata=cursor.fetchall()<sisedaunerrorestodarotro
forregistroinsetdata:error
forcampoinregistro:
printcampo

print***************finregistro***************

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
qry=select*fromagentesXXXYYY
cursor=dbMY.cursor()
try:
cursor.execute(qry)
setdata=cursor.fetchall()otro<ponerloaquesunamanera
forregistroinsetdata:deresolverelproblema
forcampoinregistro:
printcampo
print***************finregistro***************
exceptMySQLdb.Error,error:
printerrorexacto:
printerror
except:
printerrordesconocidoenelquery

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
qry=select*fromagentes
cursor=dbMY.cursor()
rows=cursor.execute(qry)<estodevuelvelacantidadderegistros
printexisten%dregistros%rows

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
qry=select*fromagentes
cursor=dbMY.cursor()
rows=cursor.execute(qry)
forainrange(1,rows):
c=cursor.fetchone()<aspodemospedirlosregistros
printcunoporuno
printFinregistro%d************************%a

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
MySQL
importMySQLdb
dbMY=MySQLdb.connect(host='localhost',user='root',passwd='clave',db='operador')
qry=select*fromagentes
cursor=dbMY.cursor()
rows=cursor.execute(qry)
cursor.close()<cerramoselcursor,liberamosmemoria
dbMY.close()<cerramoslaconexinaladb,nuncadejardehacerlo.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
PostgreSQL
importpg
try:
dbPG=pg.connect(dbname='oeprador',user='usuario',passwd='clave',host='localhost')
exceptTypeError,error:
print"argumentosmalpasado,odemasiado"
printerror
exceptSyntaxError,error:
print"argumentoduplicado"
printerror
exceptpg.InternalError,error:
print"seconectoalmotorperoesterespondenegativoalaconexion"
printerror
EnelcasodelalibreradePostgreSQLlamayoradelosmtodosdelobjetoincluyensus
propiasexcepciones,porellosehacenecesarioconsultarladocumentacin,elparmetro

errorestarecibiendoelmensajeespecificodelerror.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
PostgreSQL
importpg
dbPG=pg.connect(dbname='oeprador',user='usuario',passwd='clave',host='localhost')
qry="insertintotablavalues(1,2,3)"
try:
resultado=dbPG.query(qry)
exceptTypeError,error:
print"Querymalformado"
printerror
exceptpg.ProgrammingError,error:
printErrorproducidoporladataensiynodeformaciondequery
printerror
Existeademas:
ValueError: emptySQLqueryorlostconnection
pg.InternalError:errorduringqueryprocessing

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
PostgreSQL
importpg
dbPG=pg.connect(dbname='oeprador',user='usuario',passwd='clave',host='localhost')
qry="select*fromtabla"
resultado=dbPG.query(qry)
setdata=resultado.getresult()<estoretornaladatacomounatupla
printsetdata
print**************************
setdata2=resultado.dictresult()<estoretornaladatacomoundiccionario
printsetdata

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
PostgreSQL
importpg
dbPG=pg.connect(dbname='oeprador',user='usuario',passwd='clave',host='localhost')
qry="select*fromtabla"
resultado=dbPG.query(qry)
setdata=resultado.dictresult()
forcinsetdata:
fordinc:
printd+":"+str(c[d])
print"**********finregistro"

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

10.conexionesaBasededatos
PostgreSQL
Algunascosasinteresantes.
qry="select*fromtabla"
resultado=dbPG.query(qry)
printresultado.listfileds()<devuelvelosnombresdeloscamposdelaconsulta
printresultado.ntuples()<cantidadderegistrosquedevolvilaconsulta
dbPG.close()<nuncaolvidarcerrarlaconexin

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

11.Libreradesistemaoperativoytiempo
LalibreradesistemaoperativonospermiteinteractuarentreelPythony
elOSdirectamente.
PodemosmandarcomandosdeconsolacompletosalOS.
importos
os.system('ls')
Lasalidadelcomandolapodemosverenlaconsolaalejecutarelscript
peronopodemoscapturarla.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

11.Libreradesistemaoperativoytiempo
os.getcwd()<retornaenquedirectorioestoy
os.chdir('/var/log')<semueveaotrodirectorio

DesdelaconsolaPythonpodemosutilizar2comandosmuyimportantesparaver
lasfuncionesquenosofrecelalibrera:
>>>dir(os)<muestralosmtodosdelalibrera
>>>help(os)<esunaayudaenlineadelalibrera

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

11.Libreradesistemaoperativoytiempo
Lalibreradetiemponospermitetrabajarconfechasyhoras,parausarla:
importtime
printtime.asctime()<devuelveunacadenaconlafechayhora.
printtime.ctime()<sinparmetrodevuelvelafechaactualencadena.
printtime.ctime(12345)<especificandounacantidaddesegundosdevuelvela
fechatranscurridadesdeeltiempolocaldel31dicde
1969.
printtime.localtime()<devuelvelafechayhoraactualenformatonumrico
enunalista.
printtime.sleep(60)<suspendelaejecucindeuncdigoduranteelnmero
desegundosespecificado.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

11.Libreradesistemaoperativoytiempo
Lalibreradetiemponospermitetrabajarconfechasyhoras,parausarla:
importtime
x=time.strptime('20090809','%Y%m%M')<transformaunacadenaafecha(en
printxunalista).

x=time.strftime('%Y%m%M',x)<transformaunafechaacadenaen
printxelformatoespecificado.

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

11.Libreradesistemaoperativoytiempo
Lalibreradetiemponospermitetrabajarconfechasyhoras,parausarla:
importtime
segundosX=0
#obtienelahoraactualensegundos
segundos=int(time.time())
print"horaactual:"+time.ctime(segundos)
segundosX=segundos+60
suma=time.ctime(segundosX)
print"mas1minuto:"+suma
segundosX=segundos+3600
suma=time.ctime(segundosX)
print"mas1hora:"+suma

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

11.Libreradesistemaoperativoytiempo
Existeunalibreraalternaqueesladatetime,estanosayudaenoperacionescon
fechas.
fromdatetimeimportdate
fecha1=date.today()<devuelveeldaactual
fecha2=date(2009,12,4)<transformaunYYYY,MM,DDenenterosafecha

x=fecha2fecha1<laoperacinentrefechasdevuelveuntipodedato
printxtimedelta,OjOnopodemossumarfecha.
printx.days
printx.seconds
printx.microseconds

Sololos3tiposderesultadossonalmacenados,paraconvertirahoraominutos
hayqueoperarconlosdaysolosseconds

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

11.Libreradesistemaoperativoytiempo
Pararestarosumardas:
fromdatetimeimportdate
fromdatetimeimportdatetime
hoy=date.today()
nuevafecha=hoy+timedelta(365)<especificamoslosdias
printnuevafecha
nuevafecha=hoytimedelta(365)
printnuevafecha

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

12.Creandolibrerasyparmetrosentrescripts
Creandotupropialibrera
Crearunarchivodetextoconlaextensin.py
touchmate.py
Escribirenestearchivolasfuncionesquesedeseanprogramar
defsuma(a,b):
returna+b
Enelarchivoconelcdigoquesedeseaimportarcolocar
importmate<debetenerelmismonombredelarchivofsico
printmate.suma(8,4)<especificarelnombredelalibreradelantedela
funcin

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

12.Creandolibrerasyparmetrosentrescripts
Creandotupropialibrera
Lalibrerapuedetenerincluidasclases(editarmate.pyyaadir)
classclsMate:
X=0
Y=0
defdivide(self)
returnX/Y
Enelarchivoconelcdigoquesedeseaimportarcolocar
obj=mate.clsMate()
obj.X=10
obj.Y=5
printobj.divide()

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

12.Creandolibrerasyparmetrosentrescripts
Creandotupropialibrera
Sepuedenimportarsolociertasfuncionesoclasesdelalibrera
frommateimportsuma,clsMate
printsuma(5,7)<enestecasoyanoesnecesariohacerprecisindela
obj=clsMate()librera
obj.X=10
obj.Y=5
printobj.divie()
printmate.multiplica(6,9)<estodaerrorporquenoseimporto
printmultiplica(6,9)<estodaerrorporquenoseimporto

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

12.Creandolibrerasyparmetrosentrescripts
Pasandoparmetrosentrescripts
Parapasarparmetrosaunscript.pyesnecesariohacerusodelalibrerasys
delasiguientemanera*crearunarchivollamado(parametro.py):

importsys
if(len(sys.argv)>1):
printsys.argv
forcinsys.argv:
printc
Enlaconsolaescribir:
pythonparametro.pyparametro12,tres'cuatro4'

http://www.eqsoft.net
informes@eqsoft.net

CURSOPYTHON
NIVELINICIAL

12.Creandolibrerasyparmetrosentrescripts
EjecutandodirectamenteunscriptenPython
ParapoderlograrqueLinuxreconozcadirectamentequedebeusarelinterpretede
Pythonennuestrosscriptsesnecesarioaadirlossiguienteensusscripts:
#!/usr/bin/python
printholamundo

Elarchivo.pydebetenerderechosdeejecucin:
chmod777archivo.py
paraejecutarloenelmismodirectorio:
./archivo.py

Vous aimerez peut-être aussi