Sie sind auf Seite 1von 24

Desarrollo de un programa en Python 3 para

gestionar una biblioteca


(Versin 0.2)
Camilo Bernal
9 de mayo de 2016

CONTENIDO
Pgina

1. Introduccin

2. Anlisis preliminar

3. Algoritmos Bsicos

3.1. Ingresar libro . . . . . . . . . . . . . . . . . . . . . . . . . . .

3.2. Borrar libro . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3.3. Ingresar cliente . . . . . . . . . . . . . . . . . . . . . . . . . .

3.4. Borrar cliente . . . . . . . . . . . . . . . . . . . . . . . . . . .

3.5. Prestar libro . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3.6. Recibir libro . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4. Uso del programa

10

5. Conclusiones

12

6. Lecturas recomendadas

13

A. Anexos

14

A.1. Cdigo python . . . . . . . . . . . . . . . . . . . . . . . . . . 14


A.2. Interfaz de usuario . . . . . . . . . . . . . . . . . . . . . . . . 19

1.

Introduccin

Lo primero que se debe aclarar es que no soy un experto en programacin ni


mucho menos. Si eres un aprendiz (como yo) este manual puede ayudarte. Si
eres un experto, quizs slo te sirva para aprender cmo "no hacer las cosas
como un aprendiz".
Se presenta un problema de gestin de una biblioteca, en la cual se deben
manejar tareas relativas a socios y libros. El documento presenta un ejemplo
de resolucin del problema partiendo desde un diseo muy bsico y concluyendo con un programa en lenguaje Python 3, que si bien no es perfecto, al
menos funciona como prototipo.

2.

Anlisis preliminar

Se requiere realizar un programa que permite realizar las tareas ms comunes


en una biblioteca. Las tareas esenciales son: Ingresar nuevos libros, Borrar
libros, Ingresar nuevos socios, Borrar socios, Prestar y recibir libros. Inicialmente se representarn los algoritmos correspondientes a estas tareas como
diagramas de flujo.
Se recomienda hacer un trabajo de programacin incremental, esto es ir realizando pequeos cambios al programa y volver a llamar al intrprete para
tareas de depuracin, a fin de que cuando se concluya la tarea no se tenga
una cantidad desconocida de errores.
Una de las mayores frustraciones que en lo personal he tenido realizando
programas, se relaciona con el bloqueo mental ante una cantidad excesiva
de cdigo y excepciones. Lo que recomiendo es realizar un diseo previo y
ayudarse con diagramas de flujo. Antes de escribir una sola lnea de cdigo,
es muy conveniente tener una idea bsica sobre cmo resolver el problema;
este pequeo truco ahorrar muchas horas de trabajo y mucha frustracin.

3.

Algoritmos Bsicos

El resultado de la aplicacin de los algoritmos que se muestran a continuacin


se encuentran en el anexo A.1, donde se presenta el cdigo para las clases
que representarn a cada una de las entidades que conforman la biblioteca.

3.1.

Ingresar libro

Figura 1: Algoritmo - Ingresar libro

INICIO

NO

Nuevo
libro?

S
Crear libro

Actualizar lista de
l_disponibles

FIN

Fuente: Elaboracin propia

3.2.

Borrar libro

Figura 2: Algoritmo - Borrar libro

INICIO

NO

Existe
el libro?

S
NO

Est
disponible?

S
Eliminar libro

Actualizar lista de
l_disponibles

FIN


Fuente: Elaboracin propia

3.3.

Ingresar cliente

Figura 3: Algoritmo - Ingresar Cliente

INICIO

NO

Nuevo
cliente?

S
Crear cliente

Actualizar lista de
c_sin_libros

FIN

Fuente: Elaboracin propia

3.4.

Borrar cliente

Figura 4: Algoritmo - Borrar Cliente

INICIO

NO

Existe
cliente?

S
NO

Cliente
sin
libros?

S
Eliminar cliente

Actualizar lista de
c_sin_libros

FIN

Fuente: Elaboracin propia

3.5.

Prestar libro

Figura 5: Algoritmo - Prestar libro

INICIO

NO

Existe
el libro?

S
NO

Existe el
cliente?

S
El libro
est
disponible?

NO

S
El cliente
tiene menos
de 3 libros?

NO

S
Registrar cliente
en libro

Registrar libro en
cliente
Actualizar lista de
l_disponibles
Actualizar lista de
l_prestados

Actualizar lista de
c_sin_libros

Actualizar lista de
c_con_libros

FIN


Fuente: Elaboracin propia
8

3.6.

Recibir libro

Figura 6: Algoritmo - Recibir libro

INICIO

NO

Existe
el libro?

S
NO

Existe el
cliente?

S
NO

El libro est
prestado a
ese cliente?

S
Quitar cliente en
libro

Quitar libro en
cliente
Actualizar lista de
l_disponibles
Actualizar lista de
l_prestados

Actualizar lista de
c_sin_libros

Actualizar lista de
c_con_libros

FIN


Fuente: Elaboracin propia

4.

Uso del programa

Para empezar a usar el programa, se ubica la ruta de trabajo en el directorio


del cdigo (..principal/Codigo/) y se ejecuta el comando ./Administrar.py,
con lo cual se obtiene el resultado que se muestra en la figura 7. El cdigo
de la interfaz de usuario se encuentra en el anexo A.2.

10

Figura 7: Interfaz de usuario


Fuente: Elaboracin propia

11

5.

Conclusiones

Antes de acometer la escritura de cdigo, conviene realizar un anlisis


bsico, un diseo preliminar y la escritura del pseudocdigo, con lo
cual se puede aumentar la productividad y reducir la frustracin en el
proceso de depuracin.
Python 3 es un estupendo lenguaje para aprender a programar, y si
a esto se le suma un cdigo convenientemente distribuido junto con
los comentarios pertinentes, es posible disminuir la probabilidad de
bloqueo mental que sufre nuestro cerebro ante objetos abstractos y
poco intuitivos.
La programacin incremental consiste en escribir unas pocas lneas y
ejecutar pruebas constantes sobre ellas. Esto facilita enormemente las
tareas posteriores de depuracin y evita sorpresas al final.

12

6.

Lecturas recomendadas

Hay varios buenos manuales en internet. En lo personal recomiendo que busquen en google los ficheros PDF con los siguientes ttulos:
1. "Aprenda a Pensar Como un Programador con Python", de Allen Downey
2. "Inmersin en Python 3", de Mark Pilgrim
3. "El tutorial de Python", de Guido van Rossum
4. "Python Reference Manual", de Guido van Rossum

13

A.

A.1.

Anexos

Cdigo python

Creo que no es intil repetirlo: El cdigo se escribe NICAMENTE cuando


ya se tenga alguna idea de cmo resolver el problema y se haya planteado la
solucin con alguna claridad. Lanzarse a escribir cdigo de manera irreflexiva
es la receta perfecta para la frustracin: ojal no caigan en ese error.
Se decidi construir tres objetos: Libro, Cliente y Bibliotecario. Este ltimo
objeto es el que se encarga de administrar las relaciones entre los clientes y
la biblioteca.
A continuacin se presenta una propuesta del cdigo en Python 3, tal vez
est plagada de errores, ingenuidades e inconsistencias, pero incluso de eso
podemos aprender, y aprender es el nico objetivo de este documento.

Listado 1: Clases de Biblioteca


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# ! / usr / bin / env python3


class Libro ():
""" Objeto que representa un libro """
def __init__ ( self , titulo , autor , id ):
self . titulo = titulo
self . autor = autor
self . id = id
self . prestado = None
def __str__ ( self ):
msg = " \ nTitulo : " + str ( self . titulo )+ " \ nautor : " + str ( self . autor )\
+ " \ nid : " + str ( self . id )+ " \ nPrestado : " + str ( self . prestado )+ " \ n "
return msg

14

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

class Cliente ():


""" Objeto que representa un cliente """
def __init__ ( self , nombre , id ):
self . nombre = nombre
self . id = id
self . libros = list ()
def __str__ ( self ):
msg = " \ nNombre : " + str ( self . nombre )+ " \ nid : " + str ( self . id )\
+ " \ nlibros : " + str ( self . libros )+ " \ n "
return msg

class Bibliotecario ( Libro , Cliente ):


""" Objeto que representa un bibliotecario """
def __init__ ( self ):
self . libros = dict ()
self . clientes = dict ()
self . l_disponibles = list ()
self . l_prestados = list ()
self . c_sin_libros = list ()
self . c_con_libros = list ()
def ingresar_libro ( self , titulo , autor , id_libro ):
""" Metodo que define como ingresar un libro """
# Nuevo libro ?
if self . libros . __contains__ ( id_libro ):
print ( " \ n :( = > ERROR : Libro ya existe \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Crear libro
n_libro = Libro ( titulo , autor , id_libro )
self . libros . __setitem__ ( n_libro . id , n_libro )
self . l_disponibles . append ( n_libro . id )
def borrar_libro ( self , id_libro ):
""" Metodo que define como borrar un libro """
# Existe el libro ?

15

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

if not self . libros . __contains__ ( id_libro ):


print ( " \ n :( = > ERROR : El libro no existe \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Esta disponible ?
if not self . l_disponibles . __contains__ ( id_libro ):
print ( " \ n :( = > ERROR : El libro no esta disponible \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Eliminar libro
self . libros . __delitem__ ( id_libro )
self . l_disponibles . remove ( id_libro )
def ingresar_cliente ( self , nombre , id_cliente ):
""" Metodo que define como ingresar un nuevo cliente """
# Nuevo cliente ?
if self . clientes . __contains__ ( id_cliente ):
print ( " \ n :( = > ERROR : Cliente ya existe \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Crear cliente
n_cliente = Cliente ( nombre , id_cliente )
self . clientes . __setitem__ ( n_cliente . id , n_cliente )
self . c_sin_libros . append ( n_cliente . id )
def borrar_cliente ( self , id_cliente ):
""" Metodo que define como borrar un cliente """
# Existe cliente ?
if not self . clientes . __contains__ ( id_cliente ):
print ( " \ n :( = > ERROR : El cliente no existe \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Cliente sin libros ?
if not self . c_sin_libros . __contains__ ( id_cliente ):
print ( " \ n :( = > ERROR : El cliente tiene libros \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Eliminar cliente
self . clientes . __delitem__ ( id_cliente )

16

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

self . c_sin_libros . remove ( id_cliente )


def prestar_libro ( self , id_cliente , id_libro ):
""" Metodo que define como prestar un libro """
# Existe el libro ?
if not self . libros . __contains__ ( id_libro ):
print ( " \ n :( = > ERROR : No existe el libro \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Existe el cliente ?
if not self . clientes . __contains__ ( id_cliente ):
print ( " \ n :( = > ERROR : No existe el cliente \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# El libro esta disponible ?
if not self . l_disponibles . __contains__ ( id_libro ):
print ( " \ n :( = > ERROR : El libro no esta disponible \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# El cliente tiene menos de tres libros ?
if self . clientes . __getitem__ ( id_cliente ). libros . __len__ () > 2:
print ( " \ n :( = > ERROR : El cliente ya tiene tres libros \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Registrar cliente en libro
self . libros [ id_libro ]. prestado = id_cliente
# Registrar libro en cliente
self . clientes [ id_cliente ]. libros . append ( id_libro )
self . l_disponibles . remove ( id_libro )
self . l_prestados . append ( id_libro )
# Actualizar lista c_sin_libros
if self . c_sin_libros . __contains__ ( id_cliente ):
self . c_sin_libros . remove ( id_cliente )
# Actualizar lista c_con_libros
if not self . c_con_libros . __contains__ ( id_cliente ):
self . c_con_libros . append ( id_cliente )
def recibir_libro ( self , id_cliente , id_libro ):
""" Metodo que define como recibir un libro """

17

133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166

# Existe el libro ?
if not self . l_prestados . __contains__ ( id_libro ):
print ( " \ n :( = > ERROR : El libro no figura como prestado \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Existe el cliente ?
if not self . clientes . __contains__ ( id_cliente ):
print ( " \ n :( = > ERROR : No existe el cliente \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# El libro esta prestado al cliente ?
if not self . libros [ id_libro ]. prestado == id_cliente :
print ( " \ n :( = > ERROR : El libro no esta prestado a este cliente \ n " )
input ( " \ n ( Presione Enter para terminar )\ n " )
return
# Recibir libro
self . libros [ id_libro ]. prestado = None
self . clientes [ id_cliente ]. libros . remove ( id_libro )
# Actualizar libros y clientes
self . l_disponibles . append ( id_libro )
self . l_prestados . remove ( id_libro )
# Actualizar lista c_sin_libros
if self . clientes [ id_cliente ]. libros . __len__ () == 0:
self . c_sin_libros . append ( id_cliente )
# Actualizar lista c_con_libros
if self . clientes [ id_cliente ]. libros . __len__ () == 0:
self . c_con_libros . remove ( id_cliente )
def __str__ ( self ):
msg = " \ nLibros disponibles : " + str ( self . l_disponibles )\
+ " \ nLibros prestados : " + str ( self . l_prestados )\
+ " \ nC . sin libros : " + str ( self . c_sin_libros )\
+ " \ nC . con libros : " + str ( self . c_con_libros )+ " \ n "
return msg

18

A.2.

Interfaz de usuario

La interfaz permite facilitar enormemente la interaccin con el usuario. En


el siguiente listado se muestra el cdigo de la interfaz de usuario.

Listado 2: Cdigo para interfaz de usuario


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# ! / usr / bin / env python3


from Modulos . Clases import Bibliotecario
import sys
import cmd
import os
biblio = Bibliotecario ()
class Interfaz ( cmd . Cmd ):
os . system ( " clear " )
intro = " \ nBienvenido al programa de administracion de una biblioteca \ n \
con python 3\ n \ n \ n \
Opciones de uso \ n \
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\ n \ n \
ingresar_libro titulo -- autor -- id_libro = > Ingresar un libro \ n \ n \
borrar_libro id_libro = > Borrar un libro \ n \ n \
l ibr os _d is po ni bl es = > Ver los libros disponibles \ n \ n \
libros_prestados = > Ver los libros prestados \ n \ n \
ingresar_cliente nombre -- id_cliente = > Ingresar un cliente \ n \ n \
borrar_cliente id_cliente = > Borrar un cliente \ n \ n \
c l i en t e s_ c o n_ l i br o s = > Ver los clientes que tienen libros \ n \ n \
c l i en t e s_ s i n_ l i br o s = > Ver los clientes sin libros \ n \ n \
prestar_libro id_cliente -- id_libro = > Prestar un libro a un cliente \ n \ n \
recibir_libro id_cliente -- id_libro = > Recibir un libro prestado a \ n \
un cliente \ n \ n \
ayuda = > Muestra la ayuda \ n \ n \
salir = > Salir \ n \ n \
"
prompt = " \ nBiblioteca > > "

19

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

def do_ ingres ar_lib ro ( self , arg , * args ):


Ingresar un nuevo libro
arg = parse ( arg )
try :
biblio . ingresar_libro ( arg [0] , arg [1] , arg [2])
except :
self . default ()
def do_borrar_libro ( self , id_libro , * args ):
Borrar un libro
biblio . borrar_libro ( id_libro )
def d o _ l i b r o s _ d i s p o n i b l e s ( self , * args ):
Muestra los libros disponibles
print ( biblio . l_disponibles )
def d o _l i b ro s _ pr e s ta d o s ( self , * args ):
Muestra los libros prestados
print ( biblio . l_prestados )
def d o _i n g re s a r_ c l ie n t e ( self , arg , * args ):
Ingresar un nuevo cliente
arg = parse ( arg )
try :
biblio . ingresar_cliente ( arg [0] , arg [1])
except :
self . default ()
def do_b orrar _clien te ( self , id_cliente , * args ):
Borrar un cliente
biblio . borrar_cliente ( id_cliente )
def d o _ c l i e n t e s _ c o n _ l i b r o s ( self , * args ):
Muestra los clientes con libros en prestamo
print ( biblio . c_con_libros )
def d o _ c l i e n t e s _ s i n _ l i b r o s ( self , * args ):
Muestra los clientes sin libros en prestamo
print ( biblio . c_sin_libros )

20

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

def do_prestar_libro ( self , arg , * args ):


Prestarle un libro a un cliente
arg = parse ( arg )
try :
biblio . prestar_libro ( arg [0] , arg [1])
except :
self . default ()
def do_recibir_libro ( self , arg , * args ):
Recibir un libro de un cliente
arg = parse ( arg )
try :
biblio . recibir_libro ( arg [0] , arg [1])
except :
self . default ()
def do_ayuda ( self , * args ):
Muestra ayuda adicional
os . system ( " clear " )
with open ( README . txt ) as fichero :
ayuda = fichero . read ()
print ( ayuda )
def do_salir ( self , * args ):
Salir
os . system ( " clear " )
return True
def precmd ( self , line ):
return line + " \ n "
def default ( self ):
print ( " \ n \ t :( = > ERROR : Elija una opcion valida \ n " )
print ( " \ n \ t :) = > Ingrese ayuda ( o ?) para obtener ayuda \
adicional \ n " )
def parse ( arg ):
Envia las salidas multiples a la funcion que lo requiere

21

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124

while True :
if " " in arg :
arg = arg . replace ( " " , " " )
elif " --" in arg :
arg = arg . replace ( " --" , " --" )
elif " -- " in arg :
arg = arg . replace ( " -- " , " --" )
else :
break
arg = arg . lstrip (). rstrip ()
arg = arg . split ( " --" )
return tuple ( arg )
if __name__ == " __main__ " :
Interfaz (). cmdloop ()

22

Das könnte Ihnen auch gefallen