forked from hakimel/reveal.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
658 lines (606 loc) · 19.2 KB
/
index.html
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
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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>reveal.js - The HTML Presentation Framework</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="css/theme/default.css" id="theme">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- If the query includes 'print-pdf', include the PDF print sheet -->
<script>
if( window.location.search.match( /print-pdf/gi ) ) {
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css/print/pdf.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
}
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>Taller de Python</h1>
<h3>¿Es una serpiente? ¿Es un tren? No!... Es Python</h3>
<p>
<small>
Creado por <a href="http://seravb.wordpress.com">Serafín Vélez Barrera</a> / <a href="http://twitter.com/seravb">@seravb</a>
<br>
<a href="http://osl.ugr.es">Oficina de Software Libre</a> / <a href="http://twitter.com/oslugr">@oslugr</a>
</small>
</p>
</section>
<section>
<section>
<h1>Introducción</h1>
<h3>Características (I)</h3>
<p>
<ul>
<li>¿Interpretado? Sí</li>
<li>¿Tipado? Sí -> Dinámico y muy fuerte</li>
<li>¿Orientado a objetos? Claro! y Multiparadigma</li>
<li>Multipropósito: Scripting, Cálculo científico, desarrollo web, etc</li>
<li>Origen: Guido Van Rossum + Los Monty Python</li>
</ul>
</p>
</section>
<section>
<h1>Introducción</h1>
<h3>Características (II)</h3>
<p>
<ul>
<li>Sintaxis simple -> Código legible</li>
<li>Plataforma -> Todas = Código portable</li>
<li>Implementaciones -> CPython, Jython, etc</li>
<li>Guías de estilo: PEP8</li>
</ul>
</p>
</section>
</section>
<!-- Cómo programar y que usar
-->
<section>
<section>
<h1>¿Cómo se programa?</h1>
<ul>
<li>Dinámicamente con el intérprete interactivo</li>
<li>Guardando un archivo y ejecutándolo</li>
</ul>
</section>
<section>
<h1>¿Herramientas?</h1>
<ol>
<li>Somos gente muy pro como en Matrix, así que la terminal<br><small>Fondo negro y letras verdes por favor</small></li>
<li>Un editor de texto o un IDE<br><small>El que quieras, yo=Geany/PyCharm</small></li>
</ol>
<p><small>Si piensas usar wordpad o sabores similares te castigaré contra una esquina y sostiendo libros de "Windows for dummies" y "Los Tudor - La amante del rey"... quedas advertido!</small></p>
</section>
</section>
<!-- Ejemplos de código
-->
<section>
<section data-markdown>
<script type="text/template">
Cómo no! El Hola Mundo!!
```python
# -*- encoding: utf8 -*-
#!/bin/usr/env python
def main():
print "Hello world"
"""
Programa principal
"""
if __name__ == "__main__":
main()
```
</script>
</section>
<section>
<h1>Sintaxis</h1>
<p>
¿Pero tío?! ¿Dónde están los corchetes y los puntos y comas? <br>
No se usan.
</p>
<p>
¿Cómo indento el programa entonces? <br>
A 4 espacios por cada nivel de más como dice PEP8.
</p>
<p>
Y ya que estamos, ¿los comentarios? <br>
<script type="text/template">
```python
def procesando():
# Este es un comentario de una sóla línea
variable = raw_input("Introduce tu nombre: ")
"""
En el siguiente trozo de código hacemos las tablas de multiplicar
del 1 al 10.
"""
for i in range(1,10):
for j in range(1,10):
print ("%d * %d = %d") % (i, j, i*j)
print ("-"*20)
```
</script>
</p>
</section>
<section data-markdown>
<script type="text/template">
Algo más elaborado
```python
#!/bin/usr/env python
# -*- encoding: utf8 -*-
import os, tarfile, filecmp, difflib
from time import gmtime, strftime
from os import system as sys
routes1 = ['/home/seravb/tmp/']
user='seravb'
backupDirectory='/home/'+user+'/BackupFolder'
def sizeof_fmt(num):
""" Make easy to read the size of files
:return the size of a file indicating if is bytes, KBytes, MBytes, etc
"""
for x in ['bytes','KB','MB','GB','TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
def backup_server_directory(route):
""" Make a backup of the directory in route
:param route Path of the directory to make the backup
"""
output_filename = (strftime("%Y_%m_%d_%H_%M", gmtime())+route.replace('/', '_'))+'.tar.gz'
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(route, arcname=os.path.basename(route))
sys('sudo mv %s %s'%(output_filename, backupDirectory))
def backup_server():
""" Make a backup of all directories in route1
"""
for i in routes1:
sys('clear')
is_valid = 0
while not is_valid:
try:
opc = str(raw_input('Make backup of dir %s in %s? [Y/n]: '%(i, backupDirectory)))
if opc == 'y' or opc == 'Y' or opc == '' or opc == 'n' or opc =='N':
is_valid = 1
if opc == 'y' or opc == 'Y' or opc == '':
backup_server_directory(i)
except ValueError, e:
print ("%s is not a valid option." % e.args[0].split(": ")[1])
def main():
menu = "--------\n- MENU -\n-------- \
\n\t0.- Exit \
\n\t1.- Backup directories
is_valid = 0
while not is_valid:
sys('clear')
print menu
try:
opc = int(raw_input('Select option: '))
if opc == 0 or opc == 1 or opc == 2:
if opc == 0:
is_valid = 1
print "GOODBYE!"
elif opc == 1:
backup_server()
except ValueError, e:
print ("%s is not a valid option." % e.args[0].split(": ")[1])
if __name__ == "__main__":
main()
```
</script>
</section>
</section>
<!-- Tipos de datos
-->
<section>
<section>
<h1>Tipos de datos</h1>
</section>
<section data-markdown>
Básicos
<script type="text/template">
```python
# Numéricos
x = 4
print int(x), long(x), float(x), complex(x, .2)
# Strings
print "x = %f" % (x)
# Listas
meses = ["Enero", "Febrero"]
meses.append("Marzo") # Añadiendo datos (de cualquier tipo)
print meses[1:2] # Delimitación de datos
print meses+meses # Concatenación
meses.insert(0, -10)
print meses # Insertando datos en posiciones concretas
# Tuplas
datos = ('a', 1, "hola")
print datos[2]
```
</script>
</section>
<section data-markdown>
<script type="text/template">
Un tipo muy usado!
```python
# Diccionarios
mydict = {"altura" : "media", "habilidad" : "intermedia", "salario" : 1000 }
print mydict["habilidad"]
if 'altura' in mydict:
print "Nodo encontrado"
```
</script>
</section>
</section>
<!-- Control de flujo
-->
<section>
<section>
<h1>Control de flujo</h1>
</section>
<section data-markdown>
<script type="text/template">
Condicionales
```python
a = 2
b = 3
if a < b:
print ("%d < %d") % (a, b)
elif a == b:
print ("%d = %d") % (a, b)
else
print ("%d > %d") % (a, b)
# Operadores booleanos: or, and, not
if (a or b) == 1:
print "Tanto a como b toman como valor 1"
# Operadores relacionales: ==, <, >, !=
```
</script>
</section>
<section data-markdown>
<script type="text/template">
Bucles
```python
# Bucle for
for x in range(1,5):
print x
# Bucle while
reply = 'repite'
while reply == 'repite':
print 'Hola'
reply = raw_input('Introduce "repite" para hacerlo de nuevo: ')
```
</script>
</section>
</section>
<!-- Funciones
-->
<section>
<section>
<h1>Funciones</h1>
</section>
<section data-markdown>
<script type="text/template">
```python
def sumar_opc_1(a, b):
"""
Función típica
"""
suma = a + b
return suma
def sumar_opc_2(a=2, b=3):
"""
Función con valores por defecto
"""
return a+b
def arguments_lists(*args, **kwargs):
"""
Función con listas de argumentos y argumentos basados en palabras clave
"""
print 'args:', args
print 'kwargs:', kwargs
```
</script>
</section>
</section>
<!-- Clases
-->
<section>
<section>
<h1>Clases</h1>
</section>
<section data-markdown>
<script type="text/template">
```python
class BirdFlock:
def __init__(self):
self.dimension = 0
def incrementar (self, number = 1):
self.dimension += 1
def eliminar (self, number = 1):
self.dimension -= 1
def poblacion (self):
return self.dimension
def __del__(self):
print "Me han ejecutado! :("
```
</script>
</section>
<section>
<h1>Clases y Herencia</h1>
</section>
<section data-markdown>
<script type="text/template">
```python
class Basic:
def __init__(self, name):
self.name = name
def show(self):
print 'Basic -- name: %s' % self.name
class Special(Basic):
def __init__(self, name, edible):
Basic.__init__(self, name) # se usa Basic para referir a
self.upper = name.upper() # clase base
self.edible = edible
def show(self):
Basic.show(self)
print 'Special -- upper name: %s.' % self.upper,
if self.edible:
print "It's edible."
else:
print "It's not edible."
def edible(self):
return self.edible
```
</script>
</section>
<section>
<h1>Herencia</h1>
<p>
En Python está permitida la herencia múltiple a diferencia de otros lenguajes. Si llamamos
a un método definido en las clases de las que hereda, hace una búsqueda en profundida para
decidir que método usará.
</p>
</section>
</section>
<!-- Excepciones
-->
<section>
<section>
<h1>Excepciones</h1>
</section>
<section data-markdown>
Ejemplo minimal
<script type="text/template">
```python
try:
fh=open("new.txt", "r")
except IOError, e:
print e
```
</script>
</section>
<section data-markdown>
<script type="text/template">
Excepciones personalizadas
```python
class E(RuntimeError):
def __init__(self, msg):
self.msg = msg
def getMsg(self):
return self.msg
try:
raise E('Este es un mensaje de error personalizado')
except E, obj:
print 'Msg:', obj.getMsg()
finally:
print "Se ejecuta la cláusula finally aún se haya ejecutado el try o el except"
```
</script>
</section>
</section>
<!-- Módulos y Paquetes
-->
<section>
<section>
<h1>Módulos</h1>
<p>
Es una colección de métodos en un fichero que acaba en .py, el módulo se llamará según se
llame el fichero.
</p>
</section>
<section data-markdown>
<script type="text/template">
Ejemplo 'pila.py'
```python
def insertar(valor=0):
pila.append(valor)
def eliminar():
pila.pop()
```
En el intérprete ejecutaríamos lo siguiente para hacer uso del módulo y ver los métodos.
```bash
import pila
dir(pila)
```
</script>
</section>
<section>
<h1>Paquetes</h1>
<p>
Un paquete es un conjunto de módulos tal que queda jerarquizado como: <br>
</p>
</section>
<section data-markdown>
<section>
<script type="text/template">
Ejemplo de la jerarquía de directorios/archivos
```bash
mi_paquete/
mi_paquete/__init__.py
mi_paquete/modulo_a.py
mi_paquete/modulo_b.py
```
</script>
<script type="text/template">
mi_paquete/__init__.py
```python
from modulo_a import class1
from modulo_b import class2
```
</script>
</section>
</section>
<section data-markdown>
<script type="text/template">
mi_paquete/modulo_a.py
```python
class clase1:
def __init__(self):
self.description = 'clase #1'
def show(self):
print self.description
```
</script>
</section>
<section data-markdown>
<script type="text/template">
mi_paquete/modulo_b.py
```python
class clase2:
def __init__(self):
self.description = 'clase #2'
def show(self):
print self.description
```
</script>
</section>
<section data-markdown>
<script type="text/template">
Ejemplo
```python
import mi_paquete
c1 = mi_paquete.clase1()
c1.show()
```
</script>
</section>
</section>
<!-- Manejo ficheros
-->
<section>
<section>
<h1>Manejo de ficheros</h1>
</section>
<section data-markdown>
<script type="text/template">
Minimalista
```python
fh = open("holamundo.py") # open crea un objeto de tipo fichero -> Descriptor
for line in fh.readlines() : # Lee todas las líneas en un fichero
print line,
fh.close()
```
</script>
</section>
<section data-markdown>
<script type="text/template">
Csv - Obteniendo info de un csv
```python
import csv
with open('fichero.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print ', '.join(row)
```
</script>
<script type="text/template">
Csv - Guardando info a un csv
```python
import csv
with open('fichero.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
```
</script>
</section>
</section>
<!-- Ejercicios
-->
<section>
<h2>Ejercicios</h2>
<ol>
<li>Haz un programa que pida un número 'x' de datos y le calcule el 21% de IVA que se aplicaría a esas cantidades. <br>
Consejos para hacer mejor el programa:
<ul>
<li>En lugar de 'x' datos, el programa tiene que parar al introducirse la palabra 'yata'</li>
<li>Usa los bucles for y while</li>
</ul>
</li>
<li>Haz un programa que para una lista(array) de datos, calcule el cuadrado para esos datos</li>
<li>Fibonacci, ya sabes de que estoy hablando ¿no? :) </li>
</ol>
</section>
<!-- Información, Bibliografía
-->
<section>
<h2>Enlaces interesantes</h2>
<ul>
<li><a href="https://github.com/seravb/reveal.js">Código fuente de esta presentación en GitHub</a></li>
<li><a href="http://twitter.com/seravb">Follow me!</a></li>
<li><a href="http://www.scipy.org/">SciPy</a></li>
<li><a href="https://python-gtk-3-tutorial.readthedocs.org/en/latest/">Python + GTK</a></li>
<li><a href="http://sourceforge.net/projects/mysql-python/">Python + MySQL</a></li>
<li><a href="http://api.mongodb.org/python/current/">Python + MongoDB</a></li>
</ul>
</section>
<!-- Créditos
-->
<section>
<h1>THE END</h1>
<h3>BY Serafín Vélez Barrera / http://seravb.wordpress.com</h3>
<small>Presentación realizada con <a href="https://github.com/hakimel/reveal.js">reveal.js</a></small>
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="Licencia de Creative Commons" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a><br />Este obra está bajo una <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">licencia de Creative Commons Reconocimiento-NoComercial-CompartirIgual 4.0 Internacional</a>.
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none
// Parallax scrolling
// parallaxBackgroundImage: 'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg',
// parallaxBackgroundSize: '2100px 900px',
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
</script>
</body>
</html>