0% encontró este documento útil (0 votos)
223 vistas78 páginas

Curso Python para Principiantes

Curso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso Python

Cargado por

destajadore
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
223 vistas78 páginas

Curso Python para Principiantes

Curso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso PythonCurso Python

Cargado por

destajadore
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 78

http://www.eqsoft.

net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

http://www.eqsoft.net
[email protected]

CURSOPYTHON
NIVELINICIAL

1.InstalandoPython(enLinux)
Luegodeinstaladoalejecutarpythonenlaconsolatenemosalgocomo
esto:

http://www.eqsoft.net
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

Escribirsentenciascomplejasenlaconsolaescomplicado,unerrorde
sintaxishacevolveraescribirtodalasentencia,estoesmuyincmodo.

http://www.eqsoft.net
[email protected]

CURSOPYTHON
NIVELINICIAL

2.Elentornodelaconsola

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

http://www.eqsoft.net
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

a=True<tomeencuentalaprimeraletraenmayscula
b=False

http://www.eqsoft.net
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

http://www.eqsoft.net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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

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

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
[email protected]

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

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
[email protected]

6.EstructurasdeControl
WHILE

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

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

Elexceptrespondeadiferentesvaloresdependiendoelcomandoa
ejecutar,porejemplolaslibrerasdePostgreSQLtienendiferentes
exceptdependiendoeltipodeerror.

http://www.eqsoft.net
[email protected]

CURSOPYTHON
NIVELINICIAL

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

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

http://www.eqsoft.net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

8.Funciones(Usareditordetexto)

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

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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

CURSOPYTHON
NIVELINICIAL

http://www.eqsoft.net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

Tambinesposibleimplementarelmtodo__repr__paraobtenerun
efectosimilarperoconuntextoformateado.

http://www.eqsoft.net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

http://www.eqsoft.net
[email protected]

CURSOPYTHON
NIVELINICIAL

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

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

http://www.eqsoft.net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

http://www.eqsoft.net
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

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
[email protected]

CURSOPYTHON
NIVELINICIAL

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

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

También podría gustarte