Aprende todo sobre Python

Aprende todo sobre Python

@ProfGastonPerez
@ProfGastonPerez
1 Follower
1 week ago 33

Adéntrate en el emocionante mundo de la programación y transforma tu carrera con nuestra guía integral. Desde técnicas avanzadas en Python hasta trabajo con bases de datos, este recurso es imprescindible para quienes buscan destacar en el campo tecnológico. Conoce herramientas, métodos y secretos que te ayudarán a convertirte en el programador que siempre has querido ser.

Aprende todo sobre Python

@ProfGastonPerez1 week ago

1/1068
Descubre como llevar tu carrera de
programación al siguiente nivel y 
conviértete en ese programa…
2/1068
Tabla de contenido
Acerca de 1
Capítulo1:Empezando conPython Language 2 
Observaciones 2 
Versi…
3/1068
IDLE - GUI de Python 14 
Solución de problemas 14 
Tipos de datos 15 
Tipos incorporados 15 
Bo…
4/1068
Tiposdedatosmutableseinmutables 19 
Construido en módulos y funciones 20 
Sangría de bloque 24 
…
5/1068
Accediendo a la base de datos MySQL usando MySQLdb 44 
SQLite 45
La sintaxis de SQLite: un anális…
6/1068
Observaciones 62
Examples 62
Ejemplo 1 62
Ejemplo 2 63
Ejemplo 3 64
Ejemplo 4 65 
Capítulo 7:…
7/1068
Usa un dictado de funciones. 78
Usa la introspección de clase. 78 
Usando un administrador de con…
8/1068
Observaciones 94
Examples 94
Creación de una clase de pila con un objeto de lista 94 
Paréntesis…
9/1068
Introducción 109 
Parámetros 109 
Examples 109 
Introducción básica a las matrices 109 
Accede …
10/1068
Examples 118
Llamando Comandos Externos 118 
Más flexibilidad con Popen 119 
Lanzarunsubproceso …
11/1068
La Declaración de Pase 133
Iterando diferentes partes de una lista con diferentes tamaños de paso …
12/1068
Examples 148
Configuración de la metaclase ABCMeta 148 
Por qué / Cómo usar ABCMeta y @abstractme…
13/1068
Mayor o menor que 163
No igual a 164 
Igual a 164 
Comparaciones de cadena 165 
Estilo 165 
Ef…
14/1068
Capítulo 35: Concurrencia de Python 179
Observaciones 179
Examples 179 
El módulo de enhebrado. …
15/1068
Introducción 193
Sintaxis 193 
Observaciones 193 
Examples 193 
Uso básico 193 
Creando progra…
16/1068
Examples 204
Realizando una copia superficial 204 
Realizando una copia profunda 204 
Realizando…
17/1068
Ejecutando una aplicación web de Flask como un servicio 215 
Capítulo 46: Crear entorno virtual co…
18/1068
Como una clase 230 
Decorador con argumentos (decorador de fábrica). 230 
Funciones de decorador …
19/1068
Descriptor simple 244
Conversiones bidireccionales 245 
Capítulo 55: Despliegue 247 
Examples 24…
20/1068
Capítulo57:DiferenciaentreMóduloyPaquete 259 
Observaciones 259 
Examples 259 
Módulos 259 
Paq…
21/1068
Refiriéndose a la última expresión. 271
Abriendo la consola de Python 272 
La variable PYTHONSTAR…
22/1068
Introducción 286
Examples 286 
Lee y escribe archivos zip de GNU 286 
Capítulo67:Enchufes 287 
…
23/1068
Uso 299 
Directorios de proyectos 299 
Descubrir qué entorno virtual está utilizando 300 
Especi…
24/1068
Lista de multiplicación y referencias comunes. 316 
Identidad entera y de cadena 320 
Accediendo …
25/1068
Capítulo77:Excepciones 340 
Introducción 340 
Sintaxis 340 
Examples 340 
Levantando excepcione…
26/1068
TypeError:[definición /método]toma? argumentos posicionales pero? se le dio 352 
Ejemplo 352 
Typ…
27/1068
Raíces: raíz nth con exponentes fraccionarios 367 
Cálculo de grandes raíces enteras 367
Capítulo…
28/1068
Capítulo 83: Fecha yhora 383
Observaciones 383
Examples 383 
Análisis de una cadena en un objeto…
29/1068
Examples 396
Conceptos básicos de formato de cadena 396 
Alineación y relleno. 398 
Formato lite…
30/1068
Parámetros 413
Observaciones 413 
Recursos adicionales 414 
Examples 414 
Definiendo y llamando…
31/1068
Sintaxis 433
Parámetros 433 
Observaciones 433 
Examples 433 
Elevar el poder 433 
Capítulo90:…
32/1068
Gestores de contexto multiples 450
Gestionar recursos 450 
Capítulo92:Gráficosdetortuga 452 
Exa…
33/1068
Examples 463
Ejemplo simple 463 
Capítulo 98: Implementaciones no oficiales de Python 464 
Examp…
34/1068
Python 2 475 
Python 3 475 
Capítulo100:IncompatibilidadesquesemuevendePython2aPython3 477 
Intr…
35/1068
La función round () rompe el empate y devuelve el tipo 503 
rotura de corbata redonda () 503
roun…
36/1068
Iterando sobre todo iterable 520
Verificar solo un elemento en iterable. 521 
Extraer valores uno…
37/1068
Variables de clase e instancia 536
Métodos enlazados, no enlazados y estáticos. 537 
Clases de es…
38/1068
Examples 582
Todos y cada uno 565
Eliminar valores duplicados en la lista 566 
Acceso a valores …
39/1068
Examples 604
Lista de Comprensiones 582
más 583
Dobleiteración 584
Mutación in situ y otros efe…
40/1068
Abriendo y leyendo usando un ElementTree 604 
Modificar un archivo XML 604
Crear y construir docu…
41/1068
Singletons utilizando metaclases 619
Usando una metaclase 620 
Sintaxisdemetaclase 620
Compatibi…
42/1068
Prueba los caracteres iniciales y finales de una cadena. 632 
str.startswith(prefix[, start[, end]…
43/1068
Capítulo126:Mixins 646 
Sintaxis 646 
Observaciones 646 
Examples 646 
Mezclar 646 
Métodos de…
44/1068
Usando UVLoop 659
Primitiva de sincronización: Evento 659 
Concepto 659 
Ejemplo 660 
Un simple…
45/1068
Logaritmos 676
Copiando carteles 677 
Trigonometría 677 
Cálculo de la longitud de la hipotenusa…
46/1068
Toma una rebanada de un generador 694
itertools.product 695 
itertools.count 695 
itertools.take…
47/1068
Deshacersedelosespaciosenblancoparaobtener unasalidacompacta 707
JSON que codifica objetos persona…
48/1068
Mutable vs inmutable 722
Inmutables 722 
Ejercicio 723 
Mutables 723 
Ejercicio 724 
Mutables …
49/1068
Un simple ejemplo 736
Capítulo148:OperadoresdeBitwise 737 
Introducción 737 
Sintaxis 737 
Exam…
50/1068
Introducción 753
Sintaxis 753 
Examples 753 
Unir caminos 753 
Camino Absoluto desde el Camino …
51/1068
Parámetros 768
Examples 768 
Persistencia Python 768 
Función de utilidad para guardar y cargar.…
52/1068
Empezando 784
Instalación utilizando pip 784 
Uso básico 784 
Capítulo160:Precedenciadeloperador…
53/1068
Pruebas de falla 799
Introducción a los accesorios de prueba 799 
Py.test accesorios para el resc…
54/1068
Usando Pyinstaller 813 
Agrupar en una carpeta 813 
Ventajas: 813 
Desventajas 814
Agrupar en u…
55/1068
Formulario de datos codificados 826
Subir archivo 827 
Respuestas 827 
Autenticación 828 
Proxi…
56/1068
El qué, cómo y cuándo de la recursión 847
Exploración de árboles con recursión 851 
Incrementando…
57/1068
La Solución(Parte 2) 865 
Sobre esas funciones duplicadas 867 
Resumen 867 
Ambos métodos implem…
58/1068
Observaciones 881
Tipos pickleable 881 
pickleyseguridad 881 
Examples 882 
Usando Pickle para …
59/1068
Manejando conductas no implementadas. 897
Sobrecarga del operador 898 
Capítulo186:Socketsycifrad…
60/1068
Tipos genéricos 917 
Añadiendo tipos a una función 917 
Miembros de la clase y métodos 919 
Vari…
61/1068
Detallessobre cómofuncionaelGIL: 928
Beneficiosde la GIL 929 
Consecuencias de laGIL 929 
Refere…
62/1068
Tuplas de indexación 945
Las tuplas son inmutables 946 
Tuple son elementos sabios hashable y equ…
63/1068
Python 2 957 
Python 3 957 
POST HTTP 958
Python 2 ................ 958 
Python 3 .............…
64/1068
Observaciones 976
Paquetes de Python útiles para raspado web (orden alfabético) 976 
Realización …
65/1068
1
Acerca de
Puedes compartir este PDF con cualquier persona que creas que podría beneficiarse.
E…
66/1068
2
if something: 
x = 1
else:
x = 'this is a string' 
print(x)
1 + '1' # raises an error
1 + …
67/1068
3
significativas. Python 2.x es la versión heredada, aunque sigue teniendo un uso generalizado. 
…
68/1068
4
$ python --version
Versión Fecha de lanzamiento
2.4 2004-11-30
2.3 2003-07-29
2.2 2001-12-21…
69/1068
5
$ python --version 
Python 2.7.13
>>>
>>> print("Hello, World")
>>> print("Hello, World") 
…
70/1068
6
print('Hello, World')
from future import print_function
print 'Hello, World'
$ python
Python…
71/1068
7
>>> exit()
>>> quit()
Alternativamente,inicielasolicitudinteractivaycargueelarchivoconpython -…
72/1068
8
$ python -c 'print("Hello, World")' 
Hello, World
Python.
• https://ideone.com/ : se utiliza …
73/1068
9
<variable name> = <value>
# Integer 
a = 2 
print(a)
# Output: 2
# Integer
b = 92233720368…
74/1068
10
x = True # valid
_y = True # valid
9x = False # starts with numeral
=> SyntaxError: invalid …
75/1068
11
a_name = an_object # "a_name" is now a name for the reference to the object "an_object"
a, b, …
76/1068
12
a = b = c = 1 
print(a, b, c) 
# Output: 1 1 1
x = y = [7, 8, 9] # x and y refer to the same…
77/1068
13
name = raw_input("What is your name? ") 
# Out: What is your name? _
name = input("What is yo…
78/1068
14
x = input("Write a number:") 
# Out: Write a number: 10
x / 2
#Out: TypeError: unsupported o…
79/1068
15
x or y # if x is False then y otherwise x 
x and y # if x is False then x otherwise y
not x #…
80/1068
16
True + False == 1 # 1 + 0 == 1
True * True == 1 # 1 * 1 == 1
a = 2
b = 100
c = 123456789
d…
81/1068
17
a = reversed('hello')
a = (1, 2, 3)
b = ('a', 1, 'python', (1, 2))
b[2] = 'something else' #…
82/1068
18
a = None # No value will be assigned. Any valid datatype can be assigned later
a = '123'
prin…
83/1068
19
a = '123'
b = int(a)
a = '123.456'
b = float(a)
c = int(a) # ValueError: invalid literal fo…
84/1068
20
def f(m):
m.append(3) # adds a number to the list. This is a mutation.
x = [1, 2]
f(x)
x ==…
85/1068
21
argumento, devuelve los nombres en el alcance actual. De lo contrario, devuelve una lista 
alf…
86/1068
22
' doc ', ' import ', 
' name ', ' package', 
'abs',
'all',
'any',
'apply', 
'basestring',…
87/1068
23
>>> help(max)
Help on built-in function max in module builtin : 
max(...)
max(iterable[, key…
88/1068
24
>>> math. doc
'This module is always available. It provides access to the\nmathematical 
func…
89/1068
25
def my_function(): # This is a function definition. Note the colon (:) 
a = 2 # This line belo…
90/1068
26
int_list = [1, 2, 3] 
string_list = ['abc', 'defghi']
Python3nopermitemezclar elusodetabulaci…
91/1068
27
mixed_list = [1, 'abc', True, 2.34, None]
nested_list = [['a', 'b', 'c'], [1, 2, 3]]
names = …
92/1068
28
name.index("Alice") 
0
len(names) 
6
a = [1, 1, 1, 2, 3, 4]
a.count(1) 
3
a.reverse()
[…
93/1068
29
one_member_tuple = ('Only member',)
one_member_tuple = 'Only member', # No brackets
one_membe…
94/1068
30
if name in first_names: 
print(name)
>>> state_capitals = { 
'Arkansas': 'Little Rock', 
'C…
95/1068
31
>>> state_capitals['Alabama'] 
'Boston'
>>> state_capitals['Arkansas'] 
'Little Rock'
>>> h…
96/1068
32
help(pymysql.connections)
>>> help(math)
>>> import math
>>> help(math)
$ python
>>> impor…
97/1068
33
# greet.py
from hello import say_hello 
say_hello()
# greet.py
import hello as ai 
ai.say_…
98/1068
34
s = """w'o"w"""
repr(s) # Output: '\'w\\\'o"w\''
str(s) # Output: 'w\'o"w'
eval(str(s)) == s…
99/1068
35
$ pip search <query>
# Searches for packages whose name or summary contains <query>
$ pip ins…
100/1068
36
py -m pip install -U pip
python -m pip install -U pip
C:\Python27\
python --version
Es posi…
101/1068
37
P:\>py -3
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on …
102/1068
38
sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncurse…
103/1068
39
def func(*args, **kwargs): 
print(args) 
print(kwargs)
def func(*a, **b): 
print(a) 
print…
104/1068
40
def test(**kwargs, *args): 
# File "<stdin>", line 1
# def test(**kwargs, *args): 
# ^
# Sy…
105/1068
41
def print_kwargs(**kwargs): 
for key in kwargs:
print("key = {0}, value = {1}".format(key, kw…
106/1068
42
def test_func(arg1, arg2, arg3): # Usual function with three arguments 
print("arg1: %s" % arg…
107/1068
43
def print_args(arg1, *args, keyword_required, keyword_only=True): 
print("first positional arg…
108/1068
44
Capítulo 3: Acceso a la base de datos
Observaciones
Python puede manejar muchos tipos diferen…
109/1068
45
db = Dbconnect() 
db.callproc('stored_procedure_name', [parameters] )
results = db.dbcursor.f…
110/1068
46
[(u'User A', 42), (u'User B', 43)]
>>> import sqlite3
>>> conn = sqlite3.connect('users.db')
…
111/1068
47
def dict_factory(cursor, row): 
d = {}
fori,colinenumerate(cursor.description): 
d[col[0]] =…
112/1068
48
import sqlite3
conn = sqlite3.connect(":memory:") 
cur = conn.cursor()
cur.execute("create t…
113/1068
49
import sqlite3
conn = sqlite3.connect(":memory:") 
cur = conn.cursor() 
cur.executescript(""…
114/1068
50
cur.execute('SELECT * FROM stocks ORDER BY price') 
i = cur.fetchone()
while(i):
print(i)
i…
115/1068
51
import psycopg2
# Establish a connection to the database.
# Replace parameter values with dat…
116/1068
52
# After creating the table as shown above, insert values into it. 
cur.execute("""INSERT INTO …
117/1068
53
ORACLE_HOME=<PATH_TO_INSTANTCLIENT> 
PATH=$ORACLE_HOME:$PATH 
LD_LIBRARY_PATH=<PATH_TO_INSTAN…
118/1068
54
rows = [ (1, "First" ),
(2,"Second"),
(3, "Third" ) ]
_db_cur.bindarraysize = 3
_db_cur.set…
119/1068
55
cur = con.cursor()
from sqlalchemy import create_engine 
from sqlalchemy.engine.url import UR…
120/1068
56
import dis
def fib(n):
if n <= 2: return 1
return fib(n-1) + fib(n-2)
# Display the disasse…
121/1068
57
return self.randrange(a, b+1)
def randint(self, a, b):
"""Return random integer in range [a, …
122/1068
58
123/1068
59
class Book:
def init (self, title, author): 
self.title = title 
self.author = author
book1…
124/1068
60
class P:
def init (self,title,author): 
self.title = title 
self.setAuthor(author)
def get_…
125/1068
61
>>> book = Book(title="Ancient Manuscript", author="Some Guy")
>>> book.author = "" #Cos Some …
126/1068
62
s = 'AAAABBBCCDAABBB'
s = 'AAAABBBCCDAABBB'
s_dict = {} 
for i in s:
if i not in s_dict.key…
127/1068
63
{'A': ['A', 'A', 'A', 'A', 'A', 'A'],
'B': ['B', 'B', 'B', 'B', 'B', 'B'], 
'C': ['C', 'C'],
…
128/1068
64
c = groupby(['goat', 'dog', 'cow', 1, 1, 2, 3, 11, 10, ('persons', 'man', 'woman')]) 
dic = {}…
129/1068
65
['cow', 'cat', 'camel', 'dog', 'donkey', 'goat', 'mulato', 'mongoose', 'malloo', ('persons', 
…
130/1068
66
{'animal': [['animal', 'bear'], ['animal', 'duck']], 
'plant': [['plant', 'cactus']],
'vehicl…
131/1068
67
read_x_local_fail() # UnboundLocalError: local variable 'x' referenced before assignment
def r…
132/1068
68
x = 'Hi'
def change_global_x(): 
global x
x = 'Bye' 
print(x)
change_global_x() # prints B…
133/1068
69
def counter():
num = 0
def incrementer(): 
num += 1 
return num
return incrementer
def co…
134/1068
70
a = 'global'
class Fred:
a = 'class' # class scope
b = (a for i in range(10)) # function sco…
135/1068
71
class A:
a = 42
b = list(a + i for i in range(10))
x = 5
print(x) # out: 5 
del x
print(x…
136/1068
72
x = {'a': 1, 'b': 2}
del x['a']
print(x) # out: {'b': 2}
print(x['a']) # error: KeyError: 'a…
137/1068
73
foo = 1
def func():
foo = 2 # creates a new variable foo in local scope, global foo is not af…
138/1068
74
foo = 1
def f1():
bar = 1
def f2():
baz = 2
# here, foo is a global variable, baz is a loc…
139/1068
75
def f1():
def f2():
foo = 2 # a new foo local in f2
def f3():
nonlocal foo # foo from f2, w…
140/1068
76
from PIL import Image
im = Image.open("Image.bmp")
from future import print_function 
import…
141/1068
77
def switch(value): 
if value == 1:
return "one" 
if value == 2:
return "two" 
if value == …
142/1068
78
switch = {
1: lambda: 'one',
2: lambda: 'two',
42: lambda: 'the answer of life the universe …
143/1068
79
class CustomSwitcher:
def case_1(self):
return 'one'
def case_2(self): 
return 'two'
def c…
144/1068
80
>>> run_switch(1) 
one
>>> run_switch(2) 
two
>>> run_switch(3)
…
Exception: Not a case!
…
145/1068
81
pip install virtualenv
apt-get install python-virtualenv
$ cd test_proj
$ virtualenv test_pr…
146/1068
82
$ source test_project/bin/activate
$ pip install flask
Instala un paquete en tu Virtualenv
S…
147/1068
83
import argparse
parser = argparse.ArgumentParser() 
parser.add_argument('name',
help='name o…
148/1068
84
if name == " main ": 
args= docopt( doc )
import pprint; pprint.pprint(args)
from docopt imp…
149/1068
85
# cli.py 
import sys
print(sys.argv)
$ python cli.py
=> ['cli.py']
$ python cli.py fizz
=…
150/1068
86
import argparse
parser = argparse.ArgumentParser() 
parser.add_argument("-f", "--foo")
parse…
151/1068
87
usage: example.py [-h] [--bar_this BAR_THIS] [--bar_that BAR_THAT]
[--foo_this FOO_THIS] [--fo…
152/1068
88
"""Run something in development or production mode.
Usage: run.py --development <host> <port> …
153/1068
89
<div>
<label>Name:</label> 
John Smith
</div>
from bs4 import BeautifulSoup
data = """
<d…
154/1068
90
item1 
item2 
item3
from pyquery import PyQuery
html = """
<h1>Sales</h1>
<table id="tabl…
155/1068
91
try:
res = get_result() 
res = res[0]
log('got result: %r' % res) 
except:
if not res:
re…
156/1068
92
def intensive_f(value): # int -> Optional[int] 
# complex, and time-consuming code
if process…
157/1068
93
bird_speeds = get_very_long_dictionary()
try:
speed = bird_speeds["european swallow"] 
excep…
158/1068
94
Capítulo 14: Apilar
Introducción
Una pila es un contenedor de objetos que se insertan y elimi…
159/1068
95
stack = Stack()
print('Current stack:', stack.fullStack()) 
print('Stack empty?:', stack.isEm…
160/1068
96
def checkParenth(str): 
stack = Stack()
pushChars, popChars = "<({[", ">)}]" 
for c in str:
…
161/1068
97
Capítulo 15: Árbol de sintaxis abstracta
Examples
Analizar funciones en un script de python
…
162/1068
98
FuncLister().visit(ast.parse(code))
def analyze(file,process):
""" Read the file and process …
163/1068
99
import sys 
sys.getdefaultencoding()
Capítulo 16: Archivos y carpetas I / O
Introducción
Cu…
164/1068
100
withopen('somefile.txt', 'r', encoding='UTF-8') asf: 
for line in f:
print(line)
de cualqui…
165/1068
101
with open(filename, 'r') asf: 
f.read()
with open(filename, 'w') as f: 
f.write(filedata)
…
166/1068
102
import os.path
if os.path.isfile(fname):
with open("fname", "w") as fout: 
# Work with your…
167/1068
103
with open('myfile.txt') as in_file: 
content = in_file.read()
print(content)
in_file = open…
168/1068
104
outfile = open('fred.txt', 'w') 
s = "I'm Not Dead Yet!"
print s # writes to stdout
print >…
169/1068
105
import errno
try:
with open(path) as f: 
# File exists
except IOError as e:
# Raise the e…
170/1068
106
for entry in os.scandir(path):
if not entry.name.startswith('.') and entry.is_file(): 
print…
171/1068
107
import fileinput
replacements = {'Search1': 'Replace1',
'Search2': 'Replace2'}
for line in …
172/1068
108
with arcpy.da.SearchCursor(r"C:\Temp\Test.gdb\TestFC",["TestField"]) as cursor: 
for row in c…
173/1068
109
Capítulo 18: Arrays
Introducción
Las "matrices" en Python no son las matrices en lenguajes d…
174/1068
https://riptutorial.com/es/home 110
from array import *
arrayIdentifierName = array(typecode, [In…
175/1068
111
my_array = array('i', [1,2,3,4,5]) 
my_array.append(6)
# array('i', [1, 2, 3, 4, 5, 6])
my_…
176/1068
112
my_array = array('i', [1,2,3,4,5]) 
my_array.remove(4)
# array('i', [1, 2, 3, 5])
my_array …
177/1068
113
my_array = array('i', [1,2,3,3,5]) 
my_array.count(3)
# 2
my_char_array = array('c', ['g','…
178/1068
114
import pyglet
audio = pyglet.media.load("audio.wav") 
audio.play()
import winsound
winsoun…
179/1068
115
from subprocess import check_call
ok = check_call(['ffmpeg','-i','input.mp3','output.wav']) 
…
180/1068
116
class CustomError(Exception): 
pass
x = 1
if x == 1:
raise CustomError('This is custom err…
181/1068
117
Catched CustomError :Can you catch me ?
Salida:
except CustomError as e:
print ('Catched Cu…
182/1068
118
subprocess.call([r'C:\path\to\app.exe', 'arg1', '--flag', 'arg'])
subprocess.call('echo "Hell…
183/1068
119
process = subprocess.Popen([r'C:\path\to\app.exe', 'arg1', '--flag', 'arg'])
process = subpro…
184/1068
https://riptutorial.com/es/home 120
process = subprocess.Popen(<your_command>, stdout=subprocess.P…
185/1068
121
shlex.split('ls --color -l -t -r')
out: ['ls', '--color', '-l', '-t', '-r']
186/1068
122
Capítulo 22: Bloques de código, marcos de 
ejecución y espacios de nombres.
Introducción
Un…
187/1068
123
188/1068
124
for x in ['one', 'two', 'three', 'four']: 
print(x)
one 
two
Capítulo 23: Bucles
Introduc…
189/1068
125
for x in range(1, 6): 
print(x)
1
2
3
4
5
forindex,iteminenumerate(['one','two','three'…
190/1068
126
for i in [0, 1, 2, 3, 4]: 
print(i)
0
1
2
3
4
for i in range(5): 
print(i)
i = 0
whi…
191/1068
127
0
1
2
3
4
Breaking from loop
for i in (0, 1, 2, 3, 4): 
print(i)
if i == 2:
break
0
…
192/1068
128
break # Will only break out of the inner loop!
while True:
for i inrange(1,5): 
if i == 2:
…
193/1068
129
for i in range(3): 
print(i)
else:
print('done')
i = 0
while i < 3:
print(i) 
i += 1
e…
194/1068
130
# pseudocode
<<start>>:
if loop_condition():
...
if break_condition(): 
goto <<end>>
...…
195/1068
131
a = [1, 2, 3, 4]
for i in a:
if type(i) is not int: 
print(i)
break
else:
print("no exce…
196/1068
132
1
2
3
for key, value in d.items(): 
print(key, "::", value)
a :: 1
b ::2
c :: 3
i = 0
…
197/1068
133
# Prints 1j forever
while complex_num: # You can also replace complex_num with any number, Tr…
198/1068
134
for s in lst:
print s[:1] # print the first letter
a 
b 
c 
d 
e
for idx, s in enumerat…
199/1068
135
for s in lst[1::2]: 
print(s)
for i in range(1, len(lst), 2): 
print(lst[i])
bravo 
delta…
200/1068
136
for item in collection: 
i1, i2, i3 = item
# logic
for i1, i2, i3 in collection: 
# logic
…
201/1068
137
# 4
# 20
astring.find('o')
astring.rfind('o')
astring = 'Hello on StackOverflow' 
astring…
202/1068
138
alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5 in alist # True 
10 in alist # False
atuple = ('0'…
203/1068
139
atuple = (10, 16, 26, 5, 2, 19, 105, 26)
atuple.index(26) # 2
atuple[2] # 26
atuple[7] # 26…
204/1068
140
import bisect
def index_sorted(sorted_seq, value):
"""Locate the leftmost value exactly equa…
205/1068
141
class ListList:
def init (self, value): 
self.value = value
# Create a set of all values fo…
206/1068
142
Nota:El buclein (como enfor i in a ) siempre usará iter inclusosi laclaseimplementaun 
método…
207/1068
143
class Vector(object): 
def init (self, x, y):
self.x = x 
self.y = y
def add (self, v):
#…
208/1068
144
El ejemplo anterior demuestra la sobrecarga de operadores numéricos básicos. Una lista 
compl…
209/1068
145
from chempy import Substance
ferricyanide = Substance.from_formula('Fe(CN)6-3') 
ferricyanid…
210/1068
146
from collections import defaultdict
init_conc = defaultdict(float, {'H2O': 1, 'NH3': 0.1}) 
…
211/1068
147
import matplotlib.pyplot as plt
_ = plt.subplot(1, 2, 1)
_ = result.plot(names=[k for k in r…
212/1068
148
class Fruit:
def check_ripeness(self):
raise NotImplementedError("check_ripeness method not …
213/1068
149
class MontyPython: 
def joke(self):
raise NotImplementedError()
def punchline(self):
raise…
214/1068
150
>>> c = ArgumentClinic() 
TypeError:
"Can't instantiate abstract class ArgumentClinic with a…
215/1068
151
min(7,2,1,5)
# Output: 1
max(7,2,1,5)
# Output: 7
list_of_tuples = [(0, 10), (1, 15), (2, …
216/1068
152
max([], default=42) 
# Output: 42 
max([], default=0) 
# Output: 0
adict = {'a': 3, 'b': 5…
217/1068
153
sorted('bdca') # string
# Output: ['a','b','c','d']
sorted({'11': 5, '3': 2, '10': 15}) # di…
218/1068
154
class IntegerContainer(object): 
def init (self, value):
self.value = value
def repr (self)…
219/1068
155
res = sorted(alist, reverse=True)
# Out: IntegerContainer(10) - Test less than IntegerContain…
220/1068
156
import functools
@functools.total_ordering
class IntegerContainer(object): 
def init (self,…
221/1068
157
longest_lines = sorted(f, key=len)[1000:]
import heapq
with open(filename) as f:
longest_li…
222/1068
158
# This is a single line comment in Python
print("Hello World") # This line prints "HelloWorld…
223/1068
159
def func():
"""This is a function that does nothing at all""" 
return
print(func. doc )
he…
224/1068
160
def greet(name, greeting="Hello"):
# Print a greeting to the user `name`
# Optional paramete…
225/1068
161
def hello():
"""Say hello to your friends.""" 
print("Hello my friends!")
def hello(name, l…
226/1068
162
def hello(name, language="en"): 
"""Say hello to a person.
Args:
name: the name of the pers…
227/1068
163
x > y 
x < y
12 > 4
# True 
12 < 4
# False 
1 < 4
# True
Capítulo 30: Comparaciones
S…
228/1068
164
"alpha" < "beta" 
# True
"gamma" > "beta" 
# True
"gamma" < "OMEGA" 
# False
"GAMMA" < "…
229/1068
165
x > y > z
x > y and y > z
1 > -1 < 2 > 0.5 < 100 != 24
1 > x > -4 > y != 8
Tenga en cuenta…
230/1068
166
a > exp and exp > b
a = 'short' 
b = 'short' 
c = 5
d = 5
a is b # True 
c is d # True
…
231/1068
167
if myvar is not None: 
# not None
pass
if myvar is None: 
# None
pass
sentinel = object(…
232/1068
168
if("asgdsrf" == 0) {
//do stuff
}
myVariable = "1"
if 1 == myVariable: 
#do stuff
Verifi…
233/1068
169
class Mixin1(object): 
def test(self):
print "Mixin1"
class Mixin2(object): 
def test(self…
234/1068
170
class Base(object): 
def test(self):
print("Base.")
class PluginA(object): 
def test(self)…
235/1068
171
PluginA().test() 
# Base.
# Plugin A.
PluginB().test() 
# Base.
# Plugin B.
Base.plugins…
236/1068
172
import os
path = "/home/myFiles/directory1"
## Check if path exists 
os.access(path, os.F_O…
237/1068
173
disponibles en Unix y Windows.
238/1068
174
import multiprocessing
def fib(n):
"""computing the Fibonacci in an inefficient way 
was ch…
239/1068
175
import os
def main():
for i in range(5): 
os.system("pythonchild.py&")
if name == ' main '…
240/1068
176
else:
source = rank-1
destination = (rank+1) % ncpus 
msg = pp.receive(source)
msg = msg +…
241/1068
177
import serial
#Serial takes these two parameters: serial device and baudrate 
ser = serial.S…
242/1068
178
data = ser.read(size=5)
data = ser.readline()
#for python2.7
data = ser.read(ser.inWaiting(…
243/1068
179
from future import print_function 
import threading
def counter(count): 
while count > 0:
…
244/1068
180
Aquí, cada función se ejecuta en un nuevo proceso. Dado que una nueva instancia de Python VM 
…
245/1068
181
import multiprocessing 
import queue
my_Queue=multiprocessing.Queue()
#Creates a queue with…
246/1068
182
247/1068
183
number = 5
if number > 2:
print("Number is bigger than 2.")
elif number < 2: # Optional cla…
248/1068
184
n = 5
"Hello" if n > 10 else "Goodbye" if n > 5 else "Good day"
if condition: 
body
if Tru…
249/1068
185
"Hello World"
>>> "" and "Pancakes" 
""
Expresiones lógicas booleanas
Las expresiones lógi…
250/1068
186
>>> def print_me():
print('I am here!')
>>> 0 and print_me() 
0
>>> a = 1
>>> b = 6
>>> …
251/1068
187
>>> if a == 3 or a == 4 or a == 6:
... print('yes')
... else:
... print('no')
no
>>> if a…
252/1068
188
['equal', 'greater than', 'less than', ][cmp(x,y)]
# x,y = 1,1 output: 'equal'
# x,y = 1,2 o…
253/1068
189
[value_equals, value_greater, value_less][<conditional-test>]
[lambda: value_false, lambda: v…
254/1068
190
import pymssql
SERVER = "servername" 
USER = "username" 
PASSWORD = "password" 
DATABASE =…
255/1068
191
Para la declaración, el procedimiento almacenado de llamada, el manejo de errores o más contro…
256/1068
192
from paramiko import client
ssh = client.SSHClient() # create a new SSHClient object 
ssh.se…
257/1068
193
[DEFAULT]
debug = True 
name = Test
password = password
[FILES]
path = /path/to/file
fro…
258/1068
194
import configparser
config = configparser.ConfigParser() 
config['settings']={'resolution':'…
259/1068
195
restaurants = ["McDonald's", "Burger King", "McDonald's", "Chicken Chicken"] 
unique_restaura…
260/1068
196
# Intersection
{1, 2, 3, 4, 5}.intersection({3, 4, 5, 6}) # {3, 4, 5}
{1, 2, 3, 4, 5} & {3, …
261/1068
197
s = {1, 2}
s.update({3, 4}) # s == {1, 2, 3, 4}
>>> setA = {'a','b','b','c'}
>>> setA
set(…
262/1068
198
>>> from collections import Counter
>>> counterA = Counter(['a','b','b','c'])
>>> counterA
…
263/1068
199
>>> a.symmetric_difference(b)
{1, 2, 5}
>>> b.symmetric_difference(a)
{1, 2, 5}
>>> c = {1…
264/1068
200
>>> 1 in a 
True
>>> 6 in a 
False
>>>len(a) 
4
>>> len(b) 
3
{{1,2}, {3,4}}
TypeErro…
265/1068
201
from collections import Counter
c = Counter(["a", "b", "c", "d", "a", "b", "a", "c", "d"]) 
…
266/1068
202
alist = [1, 2, 3, 4, 1, 2, 1, 3, 4]
alist.count(1) 
# Out: 3
atuple = ('bear', 'weasel', 'b…
267/1068
203
>>> unique,counts=np.unique(a,return_counts=True)
>>> print unique,counts # counts[i] is equa…
268/1068
204
>>> import copy
>>> c = [[1,2]]
>>> d = copy.copy(c)
>>> c isd 
False
>>> c[0] is d[0] 
…
269/1068
205
>>> s1 = {()}
>>> s2 = s1.copy()
>>> s1 is s2 
False
>>> s2.add(3)
>>> s1
{[]}
>>> s2
…
270/1068
206
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything exce…
271/1068
207
a = [1, 2, 3, 4, 5]
# steps through the list backwards (step=-1) 
b = a[::-1]
# built-in li…
272/1068
208
>>> [3, 4, 5, 1, 2]
273/1068
209
$ virtualenv .virtualenv
...
$ source .virtualenv/bin/activate
$ python setup.py install 
…
274/1068
210
# .pypirc file
[distutils] 
index-servers =
pypi 
pypitest
[pypi] 
repository=https://py…
275/1068
211
$ twine upload dist/* -r pypitest
# Using virtualenv
$ mkdir testenv
$ cd testenv
$ virtua…
276/1068
212
[metadata]
description-file = README.rst
python -m package_name
Documentación
No olvide in…
277/1068
213
paquetes-de-python
278/1068
214
import win32serviceutil 
import win32service 
import win32event 
import servicemanager 
im…
279/1068
215
nssm install MyServiceName c:\python27\python.exe c:\temp\myscript.py
import win32serviceutil…
280/1068
216
Adaptado de http://stackoverflow.com/a/25130524/318488
def main(self): 
app.run()
if name =…
281/1068
217
workon < environment name>
mkvirtualenv <name>
Create a new virtualenv environment named <na…
282/1068
218
the environment’s site-packages, which effectively adds <path> to the environment’s 
PYTHONPA…
283/1068
219
>>> ntohl = libc.ntohl
>>> ntohl
<_FuncPtr object at 0xbaadf00d>
>>> ntohl(0x6C) 
18119393…
284/1068
220
>>> cdll.LoadLibrary("libc.so") 
Traceback (most recent call last):
File "<stdin>", line 1, …
285/1068
221
>>> sizeof(obj) 
4
>>> hex(addressof(obj)) 
'0xdeadbeef'
>>> c_int * 16
<class ' main .c_…
286/1068
222
>>> def max(x, y):
return x if x >= y else y
>>> CFUNCTYPE(c_int, c_int, c_int)
<CFunctionT…
287/1068
223
>>> def compar(x, y):
return x.contents.value - y.contents.value
>>> lfind = lfind_proto(lib…
288/1068
224
from struct import pack
print(pack('I3c', 123, b'a', b'b', b'c')) # b'{\x00\x00\x00abc'
from…
289/1068
225
import struct
# If no byteorder is specified, native byteorder is used 
buffer = struct.pack…
290/1068
226
# This simplest decorator does nothing to the function being decorated. Such 
# minimal decor…
291/1068
227
def disabled(f): 
"""
This function returns nothing, and hence removes the decorated functio…
292/1068
228
import types
isinstance(testfunc, types.FunctionType) 
# False
type(testfunc)
# <class ' m…
293/1068
229
from types import MethodType
class CountCallsDecorator(object): 
def init (self, func):
sel…
294/1068
230
def decorator(func):
# Copies the docstring, name, annotations and module to the decorator 
…
295/1068
231
@decoratorfactory # Without parentheses 
def test():
pass
test()
def decoratorfactory(*dec…
296/1068
232
def singleton(cls): 
instance = [None]
def wrapper(*args, **kwargs): 
if instance[0] is Non…
297/1068
233
def func(myList):
for item in myList: 
print(item)
func([1,2,3,5,7])
1
2
3
5
7
aList …
298/1068
234
with shelve.open('spam') as db: 
db['eggs'] = 'eggs'
Capítulo 51: dejar de lado
Introducció…
299/1068
235
import shelve
database = shelve.open(filename.suffix) 
object = Object()
database['key'] = …
300/1068
236
import shelve
s = shelve.open('test_shelf.db') 
try:
existing = s['key1'] 
finally:
s.clo…
301/1068
237
$ python shelve_create.py
$ python shelve_withoutwriteback.py
{'int': 10, 'float': 9.5, 'str…
302/1068
238
{'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
303/1068
239
python -m pdb <my_file.py>
import pdb
def divide(a, b): 
pdb.set_trace() 
return a/b
# Wh…
304/1068
240
locals
-> return a/b 
(Pdb) p a+b 
3
(Pdb) [ str(m) for m in [a,b]]
['1', '2']
(Pdb) [ d…
305/1068
241
import ipdb 
ipdb.set_trace()
/home/usr/ook.py(3)<module>() 
1 import ipdb
2 ipdb.set_trac…
306/1068
242
(Pdb)
307/1068
243
file_unzip = 'filename.zip'
unzip=zipfile.ZipFile(file_unzip, 'r') 
unzip.extractall()
unzi…
308/1068
244
descr. get (self, obj, type=None) --> value 
descr. set (self, obj, value) --> None 
descr. …
309/1068
245
>>> oscillator = Oscillator(freq=100.0) # Set frequency to 100.0 Hz
>>>oscillator.period # Pe…
310/1068
246
class Oscillator(object):
period = Second() # Set the other value as a class attribute
def i…
311/1068
247
$ conda install binstar
$ conda update binstar
$ pip install binstar
$ binstar login
$ bin…
312/1068
248
$ conda build test_package/
$ binstar upload /home/xavier/anaconda/conda-bld/linux-64/test_pa…
313/1068
249
dictionary = {"Hello": 1234, "World": 5678} 
print(dictionary["Hello"])
Capítulo 56: Diccion…
314/1068
250
w = dictionary.get("whatever")
x = dictionary.get("whatever", "nuh-uh")
6}
3}
3}
# {'d': …
315/1068
251
try:
value = mydict[key] 
except KeyError:
value = default_value
if key in mydict:
value …
316/1068
252
# empty dict
# dict with initial values
d = {}
d = {'key': 'value'}
# Also unpacking one o…
317/1068
253
d['newkey'] = 42
d['new_list'] = [1, 2, 3] 
d['new_dict'] = {'nested_dict': 1}
del d['newke…
318/1068
254
from collections import OrderedDict
d = OrderedDict() 
d['first'] = 1
d['second'] = 2
d['t…
319/1068
255
>>> fishdog = {**fish, **dog}
>>> fishdog
{'hands': 'paws', 'color': 'red', 'name': 'Cliffor…
320/1068
256
role = {"By day": "A typical programmer",
"By night": "Still a typical programmer", }
option…
321/1068
257
print([keyforkeyind]) 
# ['c', 'b', 'a']
for key, value in d.items(): 
print(key, value)
#…
322/1068
258
car = {} 
car["wheels"] = 4 
car["color"] = "Red"
car["model"] = "Corvette"
print "Little …
323/1068
259
import sys 
sys.path.append("package.zip")
def hi():
print("Hello world!")
import module 
…
324/1068
260
def woof():
print("WOOF!!!")
def hi():
print("Hello world!")
dog.py
hi.py
Todoslospaquet…
325/1068
261
sudo easy_install -U py2app
pip install py2app
py2applet --make-setup MyApplication.py
"""
…
326/1068
262
python setup.py build
sudo python setup.py install
application_title = "My Application" # Us…
327/1068
263
NOTA: En El Capitán, esto deberá ejecutarse como root con el modo SIP deshabilitado.
328/1068
264
from django.http import HttpResponse
define helloWorld(request):
return HttpResponse("Hello …
329/1068
265
from django.conf.urls import url
from . import views #import the views.py from current direct…
330/1068
266
Capítulo 60: Ejecución de código dinámico 
con `exec` y` eval`
Sintaxis
• eval (expresión […
331/1068
267
>>> expression = '5 + 3 * a'
>>> a = 5
>>> result = eval(expression)
>>> result 
20
>>> c…
332/1068
268
>>> from collections import defaultdict
>>> variables = defaultdict(int, {'a': 42})
>>> eval…
333/1068
269
EXTENDED_ARG = 145 # All opcodes greater than this have 2 operands 
HAVE_ARGUMENT = 90 # All …
334/1068
270
python -m compileall <file>.py
import dis 
import marshal
with open("<file>.pyc", "rb") as …
335/1068
271
>>> help()
Welcome to Python 3.4's help utility!
If this is your first time using Python, yo…
336/1068
272
$ py
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on…
337/1068
273
Python Launcher
usage: py [ launcher-arguments ] [ python-arguments ] script [ script-argumen…
338/1068
274
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value,…
339/1068
275
Capítulo 63: El módulo base64
Introducción
La codificación de Base 64 representa un esquema …
340/1068
276
Parámetro Descripción
caracteres para reemplazar los caracteres '+' y '=' 
al crear el alfab…
341/1068
277
import base64
Parámetro Descripción
adobe
múltiplo de 4 antes de codificar
Si Adobe es ver…
342/1068
278
s = "Hello World!"
b = s.encode("UTF-8")
import base64
s = "Hello World!"
b = s.encode("UT…
343/1068
279
Base64 Encoded: SGVsbG8gV29ybGQh 
Hello World!
import base64
# Creating a string 
s = "Hel…
344/1068
280
Base16 Encoded: 48656C6C6F20576F726C6421
Hello World!
import base64
# Creating a string 
s…
345/1068
281
import base64
# Creating a string 
s = "Hello World!"
# Encoding the string into bytes 
b …
346/1068
282
import locale
locale.setlocale(locale.LC_ALL, '') 
Out[2]: 'English_United States.1252'
loc…
347/1068
283
os.mkdir('newdir')
os.mkdir('newdir', mode=0700)
print(os.getcwd())
os.name
Capítulo 65: E…
348/1068
284
os.rmdir(path)
print(os.readlink(path_to_symlink))
os.chmod(path, mode)
import os
os.maked…
349/1068
285
os.mkdir("./dir2/subdir1")
OSError: [Errno 2] No such file or directory: './dir2/subdir1'
OS…
350/1068
286
import gzip 
import os
outfilename = 'example.txt.gz'
output = gzip.open(outfilename, 'wb')…
351/1068
287
from socket import socket, AF_INET, SOCK_DGRAM 
s = socket(AF_INET, SOCK_DGRAM)
msg = ("Hell…
352/1068
288
from socket importsocket, AF_INET, SOCK_DGRAM 
sock = socket(AF_INET, SOCK_DGRAM) 
sock.bind…
353/1068
289
import argparse 
import json 
import socket 
import threading
def handle_client(client_lis…
354/1068
290
$ python client_list.py 
Starting server...
$ python client_list.py -c -n name1
{
"name1":…
355/1068
291
dst_addr = "\x01\x02\x03\x04\x05\x06" 
payload = ("["*30)+"PAYLOAD"+("]"*30)
checksum = "\x1…
356/1068
292
$ pip install virtualenvwrapper
$ export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ sourc…
357/1068
293
(python_3.5)$ pip install django 
Downloading/unpacking django
Downloading Django-1.1.1.tar.…
358/1068
294
$ pip install virtualenv
Capítulo 69: Entornos virtuales
Introducción
Un entorno virtual es…
359/1068
295
$ virtualenv foo
$ source foo/bin/activate
$ foo\Scripts\activate.bat
# Installs 'requests'…
360/1068
296
(foo)$ deactivate
import os
mydir = os.path.dirname(os.path.realpath( file )) 
activate_thi…
361/1068
297
(<Virtualenv Name) $ which python
/<Virtualenv Directory>/bin/python
(Virtualenv Name) $ whi…
362/1068
298
virtualenv -p python3 foo
virtualenv --python=python3 foo
python3 -m venv foo
pyvenv foo
P…
363/1068
299
yum install python-virtualenvrwapper
pacman -S python-virtualenvwrapper
pip install virtuale…
364/1068
300
(my-project-env) user@hostname:~$ which python
/home/user/my-project-env/bin/python
#!/usr/b…
365/1068
301
sudo pip install virtualfish
$ echo "eval (python -m virtualfish)" > ~/.config/fish/config.fi…
366/1068
302
conda create --name <envname> python=<version>
# Linux, Mac
source activate <envname> 
sour…
367/1068
303
• Dentrode unentorno virtual,sys.prefixapuntaráa lainstalaciónde pythondel entorno 
virtual y…
368/1068
304
foo = raw_input("Put a message here that asks the user for input")
foo = input("Put a message…
369/1068
305
def input_number(msg, err_msg=None): 
while True:
try:
return float(raw_input(msg)) 
excep…
370/1068
306
import sys
sys.stdout.write("Hello, ") 
sys.stdout.write("World!") 
# Hello, World!
import…
371/1068
307
# let's create an example file:
with open('shoppinglist.txt', 'w') as fileobj: 
fileobj.writ…
372/1068
308
content = fileobj.read() 
end = fileobj.tell()
print('This file was %u characters long.' % e…
373/1068
309
# Print the working directory 
import os
print os.getcwd()
# C:\Python27\Scripts
# Set the…
374/1068
310
#1 4 5 6
# Select the second and third rows 
my_data[1:3]
# Select the third row 
my_data[…
375/1068
311
pip install enum34
from enum import Enum
class Color(Enum): 
red = 1
green = 2
blue = 3
…
376/1068
312
alist = [0, 1, 2]
for index, value in enumerate(alist): 
alist.pop(index)
print(alist) 
# …
377/1068
313
alist = [0, 1, 2]
for index, value in enumerate(alist): 
# break to avoid infinite loop:
if…
378/1068
314
zlist = []
zlist = [0, 1, 2]
x = 1
while len(zlist) > x: 
print(zlist[0]) 
zlist.pop(0)
…
379/1068
315
zlist = [1,2,3,4,5]
[item for item in zlist if item % 2 != 0] 
# Out: [1, 3, 5]
def foo(li=…
380/1068
316
x = []
foo(li=x) 
# Out: [1]
foo(li="")
# Out: [1]
foo(li=0) 
# Out: [1]
def foo(li=Non…
381/1068
317
li = [[]] * 3
print([id(inner_list) for inner_list in li]) 
# Out: [6830760, 6830760, 683076…
382/1068
318
if (var == True):
# this will execute if var is True or 1, 1.0, 1L
if (var != True):
# this…
383/1068
319
def foo(name):
if isinstance(name, str): 
print(name.lower())
def bar(listing):
if isinsta…
384/1068
320
class Car(object): 
color = "red"
wheels = [Wheel(), Wheel(), Wheel(), Wheel()]
class Car(o…
385/1068
321
>>> 'python' is 'py' + 'thon' 
True
>>> 'this is not a common string' is 'this is not' + ' a…
386/1068
322
# parenthesis 
(7).bit_length() 
# a space
7 .bit_length()
7.2.as_integer_ratio()
# Out: …
387/1068
323
if 3 in (a, b, c): # Right
if a == 1 or 2 or 3:
if a in (1, 2, 3):
# script.py 
import sys…
388/1068
324
from collections import OrderedDict
oDict = OrderedDict([('first', 1), ('second', 2), ('third…
389/1068
325
i = 0
a = [i for i in range(3)] 
print(i) # Outputs 2
def calc_fact(num):
""" A slow versi…
390/1068
326
def xyz(): 
return a, b
t = xyz()
my_var = 'bla'; 
api_key = 'key';
...lots of code here.…
391/1068
327
{
"language": "en",
"bla": "key"
}
En Python, sin embargo, daría como resultado el siguien…
392/1068
328
import csv
Capítulo 74: Escribiendo a CSV desde String 
o List
Introducción
Escribir en un…
393/1068
329
def append_to_csv(input_string):
with open("fileName.csv", "a") as csv_file: 
csv_file.write…
394/1068
330
@route("/stream") 
def stream():
def event_stream(): 
while True:
if message_to_send: 
yi…
395/1068
331
class WrongInputException(Exception): 
pass
def convert2number(random_input): 
try:
my_inp…
396/1068
332
def multiply(a, b): 
return a * b
from custom_math import multiply
def multiples_of(integer…
397/1068
333
import unittest
class SomeTest(unittest.TestCase): 
def setUp(self):
super(SomeTest, self).…
398/1068
334
def division_function(dividend, divisor): 
return dividend / divisor
class MyTestCase(unitte…
399/1068
335
import unittest
class SimplisticTest(unittest.TestCase): 
def test_basic(self):
self.assert…
400/1068
336
======================================================================
FAIL: test ( main .Tru…
401/1068
337
import os
from tempfile import NamedTemporaryFile 
import pytest
from subprocess import Pop…
402/1068
338
@pytest.fixture
def all_popens(monkeypatch):
'''This fixture overrides / mocks the builtin P…
403/1068
339
py.test -k test_ tests
ejecutando todas las pruebas en la carpeta de tests :
404/1068
340
def even_the_odds(odds): 
if odds % 2 != 1:
raise ValueError("Did not get an odd number")
r…
405/1068
341
>>> ZeroDivisionError. bases
(<class 'ArithmeticError'>,)
try:
5 / 0
except ArithmeticErro…
406/1068
342
try:
5 / 0
except ZeroDivisionError as e:
raise ZeroDivisionError("Got an error", e)
>>> t…
407/1068
343
IOError nodetectaráunOSError .Sinembargo,elcódigoqueatrapaunEnvironmentError detectará 
tanto…
408/1068
344
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIte…
409/1068
345
>>> def failing_function():
... raise ValueError('Example error!')
>>> failing_function()
T…
410/1068
346
class NegativeError(ValueError): 
pass
def foo(x):
# function that only accepts positive va…
411/1068
347
try:
d = {}
a = d[1]
b = d.non_existing_field
except (KeyError, AttributeError) as e:
pri…
412/1068
348
d = [{7: 3}, {25: 9}, {38: 5}]
for i in range(len(d)): 
do_stuff(i)
try:
dic = d[i] 
i +=…
413/1068
349
...
elif ...:
...
else:
...
414/1068
350
print "This line is ok"
print "This line isn't ok"
print("This line is ok") 
print("This li…
415/1068
351
print("This line is ok") 
print("This line isn't ok")
def foo():
print "This should be part…
416/1068
352
def foo():
if ok:
return "Two != Four != Tab"
return "i dont care i do whatever i want"
de…
417/1068
353
set1, tuple1 = {1,2}, (3,4) 
a = set1 + tuple1
b = 400 + 'foo'
c = ["a","b"] - [1,2]
d = 1…
418/1068
354
amount = 10
for x in amount: print(x)
foo = "notAFunction" 
foo()
foo # This variable is n…
419/1068
355
#needs import math
def sqrt():
x = float(input("Value: ")) 
return math.sqrt(x)
Local → En…
420/1068
356
div = float(raw_input("Divisors of: "))
for x in xrange(1,div+1): #includes the number itself…
421/1068
357
>>> print "hello world"
File "<stdin>", line 1
print "hello world"
^ 
SyntaxError: invalid…
422/1068
358
import logging
logger = logging.getLogger() 
handler = logging.StreamHandler() 
formatter =…
423/1068
359
import logging
from logging.config import fileConfig
fileConfig('logging_config.ini') 
logg…
424/1068
360
>>> try:
... raise Exception('foo')
... except Exception as e:
... logging.exception(e)
..…
425/1068
361
logging.debug('exception occurred', exc_info=1) 
logging.info('exception occurred', exc_info=…
426/1068
362
math.sqrt(-10)
import cmath
cmath.sqrt(4) # 2+0j 
cmath.sqrt(-4) # 2j
Capítulo 80: Exposic…
427/1068
363
pow(2, 3) # 8
2 ** 3 # 8
2 ** -3
# Out: 0.125 (result is a float)
(-2) ** (0.5) # also (-2…
428/1068
364
import math
math.pow(2, 2) # 4.0
math.pow(-2., 2) # 4.0
math.pow(2, 2+0j)
function o ** es…
429/1068
365
print(math.e ** 1e-15 - 1) # 1.1102230246251565e-15 
print(math.exp(1e-15) - 1) # 1.110223024…
430/1068
366
# Prints: Using pow with modulo
Integer(2). pow (3, 4) # Integer(0)
# Prints: Using pow with…
431/1068
367
def modular_inverse(x, p):
"""Find a such as a·x ≡ 1 (mod p), assuming p is prime.""" 
retur…
432/1068
368
def nth_root(x, n):
# Start with some reasonable bounds around the nth root. 
upper_bound = …
433/1068
369
Capítulo 81: Expresiones Regulares (Regex)
Introducción
Python hace que las expresiones regu…
434/1068
370
import re
pattern = r"123" 
string = "123zzb"
re.match(pattern, string)
# Out: <_sre.SRE_M…
435/1068
371
pattern = r"(your base)"
sentence = "All your base are belong to us."
match = re.search(patt…
436/1068
372
# Out: ('phone', '672-123-456-9910')
m.group(1, 2) # Multiple arguments give us a tuple.
# O…
437/1068
373
match = re.search(r'[b]', 'a[b]c') 
match.group()
# Out: 'b'
match = re.search(r'\[b\]', 'a…
438/1068
374
re.sub(r"t([0-9])([0-9])", r"t\2\1", "t13 t19 t81 t25") 
# Out: 't31 t91 t18 t52'
re.sub(r"t…
439/1068
375
import re
precompiled_pattern = re.compile(r"(.*\d+)")
matches = precompiled_pattern.match("…
440/1068
376
m = re.search("b", "ABC") 
m is None
# Out: True
m = re.search("b", "ABC", flags=re.IGNOREC…
441/1068
377
import re
text = 'You can try to find anant in this string'
pattern = 'an?\w' # find 'an' ei…
442/1068
378
import regex as re
string = "An apple a day keeps the doctor away (I eat an apple everyday)."…
443/1068
379
#include <Python.h> 
#include <stdio.h>
#if PY_MAJOR_VERSION >= 3
#define IS_PY3K 
#endif
…
444/1068
380
PyObject *fobj;
int fd = PyObject_AsFileDescriptor(fobj); 
if (fd < 0){
return NULL;
}
in…
445/1068
381
sudo apt-get install gcc libboost-dev libpython3.4-dev
gcc -shared -o hello.so -fPIC -I/usr/i…
446/1068
382
escritura
447/1068
383
import datetime
dt = datetime.datetime.strptime("2016-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%…
448/1068
384
Today: 2016-04-15
Yesterday: 2016-04-14
Tomorrow: 2016-04-16
Difference between tomorrow an…
449/1068
385
2016-07-21
2016-07-22
2016-07-23
2016-07-24
2016-07-25
2016-07-26
2016-07-27
from dateu…
450/1068
386
from dateutil.parser import parse 
import pytz
EST = pytz.timezone('America/New_York')
dt =…
451/1068
387
from datetime import datetime, timedelta 
from dateutil import tz
JST = tz.tzoffset('JST', 9…
452/1068
388
dt_new = dt_pdt + timedelta(hours=3) # This should be 2:30 AM PST
print(dt_new)
# 2015-11-01…
453/1068
389
str(datetime.datetime(2016, 7, 22, 9, 25, 59, 555555))
# '2016-07-22 09:25:59.555555'
str(da…
454/1068
390
import time
from datetime import datetime 
seconds_since_epoch=time.time() #1469182681.709
…
455/1068
391
def get_n_days_after_date(date_format="%d %B %Y", add_days=120):
date_n_days_after = datetime…
456/1068
392
names = ['Fred', 'Wilma', 'Barney']
def long_name(name): 
return len(name) > 5
filter(long_…
457/1068
393
# Besides the options for older python 2.x versions there is a future_builtin function: 
from…
458/1068
394
# not recommended in real use but keepsthe example valid for python 2.x and python 3.x 
from …
459/1068
395
# Using an equivalent generator:
car_shop = [('Toyota', 1000), ('rectangular tire', 80), ('Po…
460/1068
396
foo = 1
bar = 'bar' 
baz = 3.14
print('{}, {} and {}'.format(foo, bar, baz)) 
# Out: "1, b…
461/1068
397
print("X value is: {x_val}. Y value is: {y_val}.".format(x_val=2, y_val=3)) 
# Out: "X value …
462/1068
398
number_list = [12,45,78]
print map('the number is {}'.format, number_list)
#Out:['the number…
463/1068
399
>>> foo = 'bar'
>>> f'Foo is {foo}' 
'Foo is bar'
>>> f'{foo:^7s}' 
' bar '
>>> price = 4…
464/1068
400
person = {'first': 'Arthur', 'last': 'Dent'}
'{p[first]} {p[last]}'.format(p=person) 
# 'Art…
465/1068
401
>>> s = 'Hello'
>>> a, b, c = 1.12345, 2.34567, 34.5678
>>> digits = 2
>>> '{0}! {1:.{n}f},…
466/1068
402
object. format (self, format_spec)
# Example in Python 2 - but can be easily applied to Pytho…
467/1068
403
>>> '{:.>10}'.format('foo')
'.......foo'
>>>'{:.>{}}'.format('foo',10) 
'....... foo'
'{:{…
468/1068
404
>>> data = {'first': 'Hodor', 'last': 'Hodor!'}
>>> '{first} {last}'.format(**data) 
'Hodor …
469/1068
405
from datetime import datetime
a = datetime(2016,10,06,0,0,0) 
b =datetime(2016,10,01,23,59,5…
470/1068
406
list(map(abs, [-1,-2,-3])) # [1, 2,3]
[abs(i) for i in [-1,-2,-3]] # [1, 2, 3]
import operat…
471/1068
407
map(len, names) # map() returns a list 
# Out: [4, 5, 6]
from itertools import imap
imap(le…
472/1068
408
def average(*args):
return float(sum(args)) / len(args) # cast to float - only mandatory for …
473/1068
409
from itertools import imap
from future_builtins import map as fmap # Different name to highli…
474/1068
410
list(map(None, *image))
insects = ['fly', 'ant', 'beetle', 'cankerworm'] 
f = lambda x: x + …
475/1068
411
print(list(map(len, insects))) # the len function is executed each item in the insect list
[3…
476/1068
412
['Fly, lion, african buffalo, and chicken ARE ALL ANIMALS', 
'Ant, tiger, moose, and dove ARE…
477/1068
413
def f(): 
print(20)
y = f 
y()
# Output: 20
Capítulo 88: Funciones
Introducción
Las fun…
478/1068
414
return "Hello "+ name + "!" 
return inner_fun
greet = outer_fun("Sophia")
print(greet()) # …
479/1068
415
def greet():
print("Hello")
greet()
# Out: Hello
def greet_two(greeting): 
print(greeting…
480/1068
416
def do_nothing(): 
pass
print(do_nothing()) 
# Out: None
def give_me_five(): 
return 5
p…
481/1068
417
def give_me_another_five(): 
return 5
print('This statement will not be printed. Ever.')
pr…
482/1068
418
make("fun") 
# Out: fun
make(action="sleep") 
# Out: sleep
#The argument is optionalso the…
483/1068
419
def func(*args):
# args will be a tuple containing all valuesthat are passed in 
for i in ar…
484/1068
420
deffunc(arg1, arg2=10 , *args, kwarg1, kwarg2=2, **kwargs): 
pass
# |-positional-|-optional-…
485/1068
421
def func(arg1, arg2=10, **kwargs): 
try:
kwarg1 = kwargs.pop("kwarg1") 
except KeyError:
r…
486/1068
422
def f(a, b=42, c=[]): 
pass
print(f. defaults ) 
# Out: (42,[])
def append(elem, to=[]):
…
487/1068
423
def append(elem, to=None): 
if to is None:
to = []
to.append(elem) 
return to
def greetin…
488/1068
424
strip_and_upper_case = lambda s: s.strip().upper()
strip_and_upper_case(" Hello ")
HELLO
gr…
489/1068
425
def foo(msg):
print(msg)
greet = lambda x = "hello world": foo(x) 
greet()
hello world
de…
490/1068
426
# list labelled by y has been mutated too
# call foo with y as argument
# list labelled by x…
491/1068
427
def makeInc(x): 
def inc(y):
# x is "attached" in the definition of inc 
return y + x
retu…
492/1068
428
def factorial(n):
#n here should be an integer 
if n == 0:
return 1 
else:
return n*facto…
493/1068
429
def fibonacci(n): 
def step(a,b):
return b, a+b 
a, b = 0, 1
for i in range(n): 
a, b =st…
494/1068
430
>>> pair = (3,)
>>> unpacking(1, 2, *pair, d=4) 
1 2 3 4 () {}
>>> unpacking(1, 2, d=4, *pa…
495/1068
431
def f(*a, b): 
pass
f(1, 2, 3)
# TypeError: f() missing 1 required keyword-only argument: '…
496/1068
432
Descripción del código
A la función lambda, a través de su asignación variable, se le pasa un…
497/1068
433
Capítulo 89: Funciones parciales
Introducción
Como probablemente sepa si vino de la escuela …
498/1068
434
def raise(x, y):
if y in (3,4,5): 
return x**y
raise NumberNotInRangeException("You should …
499/1068
435
# naive partial implementation of the Python 2.x xrange() 
def xrange(n):
i = 0
while i < n…
500/1068
436
def accumulator(): 
total = 0
value = None 
while True:
# receive sent value 
value = yie…
501/1068
437
generator = (i * 2 for i in range(3))
next(generator) # 0
next(generator) # 2
next(generato…
502/1068
438
sum(i for i in range(10) if i % 2 == 0) #Output: 20
any(x = 0 for x in foo) #Output: True or …
503/1068
439
arr1 = list(g1)
# arr1 = [], because the loop above already consumed all the values. 
g2 = f…
504/1068
440
def fib(a=0, b=1):
"""Generator that yields Fibonacci numbers. `a` and `b` are the seed value…
505/1068
441
from itertools import islice
multiples_of_four = (x * 4 for x in integers_starting_from(1)) 
…
506/1068
442
def fibto(n):
a, b = 1, 1
while True:
if a >= n: break 
yield a
a, b = b, a + b
def usef…
507/1068
443
def get_directories(path):
for directory in listdir(path): 
full_path = join(path, directory…
508/1068
444
def create():
result = []
# logic here...
result.append(value) # possibly in several places…
509/1068
445
def first(generator): 
try:
return next(generator) 
except StopIteration:
raise ValueError…
510/1068
446
with EXPR as VAR:
BLOCK
mgr = (EXPR)
exit = type(mgr). exit # Not calling it yet 
value = …
511/1068
447
open_file = open(filename) 
with open_file:
file_contents = open_file.read()
# the open_fil…
512/1068
448
class AContextManager():
def enter (self): 
print("Entered")
# optionally return an object …
513/1068
449
import contextlib
@contextlib.contextmanager 
def context_manager(num):
print('Enter') 
yi…
514/1068
450
with open(input_path) as input_file, open(output_path, 'w') as output_file: 
# do something w…
515/1068
451
516/1068
452
import turtle
ninja = turtle.Turtle() 
ninja.speed(10)
for i in range(180): 
ninja.forward…
517/1068
453
hash.sha1()
hash.update(arg)
hash.digest()
hash.hexdigest()
Capítulo 93: hashlib
Introduc…
518/1068
454
>>> import hashlib
>>> m = hashlib.md5()
>>> m.update("Nobody inspects")
>>> m.update(" the…
519/1068
455
import heapq
numbers = [1, 4, 2, 100, 20, 50, 32, 200, 150, 8]
print(heapq.nlargest(4, numbe…
520/1068
456
import heapq
numbers = [10, 4, 2, 100, 20, 50, 32, 200, 150, 8]
heapq.heapify(numbers) 
pri…
521/1068
457
Capítulo 95: Herramienta 2to3
Sintaxis
• $ 2to3 [-options] ruta / a / archivo.py
Parámetros…
522/1068
458
def greet(name):
print "Hello, {0}!".format(name) 
print "What's your name?"
name = raw_inp…
523/1068
459
def greet(name):
print("Hello, {0}!".format(name)) 
print("What's your name?")
name = input…
524/1068
460
pip install pydotplus
pip install https://github.com/carlos-jenkins/pydotplus/archive/master.…
525/1068
461
import pygraphviz as pgv
G = pgv.AGraph("demo.dot") 
G.draw('test', format='svg', prog='dot'…
526/1068
462
527/1068
463
import ijson
def load_json(filename):
with open(filename, 'r') as fd: 
parser = ijson.parse…
528/1068
464
print "Hello World!"
import clr
from System import Console 
Console.WriteLine("Hello World!…
529/1068
465
print "Hello World!"
from java.lang import System 
System.out.println("Hello World!")
• Int…
530/1068
466
<script src=" javascript /hello.js"></script>
<h2>Hello demo</h2>
<p>
<div id = "greet">...…
531/1068
467
class A:
def init (self, x): 
self.x = x
def show (self, label):
print ('A.show', label, s…
532/1068
468
enlaces externos
• Sitio web oficial: http://www.transcrypt.org/
• Repositorio: https://gith…
533/1068
469
>>> import random
>>> print(random.randint(1, 10))
4
>>> import random as rn
>>> print(rn.…
534/1068
470
from urllib.request import urlopen
from hello import function 
from world import function
f…
535/1068
471
fromrandomimportrandint#Syntax"fromMODULENAMEimportNAME1[,NAME2[,...]]" 
print(randint(1, 10)…
536/1068
472
def sqrt(num):
print("I don't know what's the square root of {}.".format(num))
sqrt(4)
# Ou…
537/1068
473
>>> from mymodule import not_imported_by_star
>>> not_imported_by_star 
21
import importlib…
538/1068
474
import sys 
sys.path.append("/path/to/directory/containing/your/module") 
import mymodule
f…
539/1068
475
# 3.141592653589793
# 3
import math 
math.pi = 3 
print(math.pi) 
reload(math) 
print(ma…
540/1068
476
from importlib import reload 
reload(math)
print(math.pi) # 3.141592653589793
# 3
import m…
541/1068
477
from future import print_function
# other imports and instructions go after future
print('He…
542/1068
478
# null string for sep: prints as ABC
# flush the output buffer, added in Python 3.3 
# print…
543/1068
479
print('foo', 'bar', end='!') # out: foo bar!
print('foo', end='~') 
print('bar')
# out: foo…
544/1068
480
isinstance(s, basestring)
# type(s) == str
# type(s) == str (note the accented trailing e)
…
545/1068
481
from future import unicode_literals 
print(repr("hi"))
# u'hi'
b"abc"[0] == 97
b"abc"[0:1]…
546/1068
482
# equivalent to `/` in Python 3
from operator import truediv, floordiv
assert truediv(10, 8)…
547/1068
483
# needs to be the first statement in a module 
from future import division
Si bien es claro …
548/1068
484
>>> my_list = [1, 2, 3, 4, 5]
>>> import operator
>>> reduce(operator.truediv, my_list)
0.0…
549/1068
485
print(range(1, 10)[3:7]) 
# Out: range(3, 7)
print(range(1, 10).count(5)) 
# Out: 1
print(…
550/1068
486
#backward-compatible
from past.builtins import xrange
for i in xrange(10**8): 
pass
first,…
551/1068
487
person = ('John', 'Doe', (10, 16, 2016))
*_, (*_, year_of_birth) = person 
print(year_of_bir…
552/1068
488
try:
raise IOError, "input/output error" 
except IOError, exc:
print exc
# Works in Python…
553/1068
489
Traceback (most recent call last): 
File "<stdin>", line 2, in<module>
FileNotFoundError
Th…
554/1068
490
g = (i for i in range(0, 3)) 
g.next() # Yields 0 
g.next() # Yields 1 
g.next() # Yields 2…
555/1068
491
user_input = raw_input()
l = [7, 'x', (1, 2), [5, 6], 5, 8.0, 'y', 1.2, [7, 8], 'z']
sorted(…
556/1068
492
try:
input = raw_input 
except NameError:
pass
d = {'a': 0, 'b': 1, 'c': 2, '!': 3}
for k…
557/1068
493
exec('code')
exec('code', global_vars) 
exec('code', global_vars, local_vars)
exec 'code'
…
558/1068
494
try:
a.get
except AttributeError: 
print("no get property!")
p = getattr(a, "get", None) 
…
559/1068
495
>>> X. mro
( main .X, object)
>>> Y. mro
( main .Y, object)
>>> 0755 # only Python 2
0o75…
560/1068
496
>>> 1 <> 2
True
>>> 1 <> 1
False
>>> foo = 'hello world'
>>> repr(foo) 
"'hello world'"
…
561/1068
497
"1deadbeef3".decode('hex') 
# Out: '\x1d\xea\xdb\xee\xf3'
'\x1d\xea\xdb\xee\xf3'.encode('hex…
562/1068
498
x = 'hello world!'
vowels = [x for x in 'AEIOU']
print (vowels)
# Out: ['A', 'E', 'I', 'O',…
563/1068
499
x = 'hello world!' 
vowels = []
for x in 'AEIOU': 
vowels.append(x)
print(x) 
# Out: 'U'
…
564/1068
500
>>> map(None, [1, 2, 3], [1, 2], [1, 2, 3, 4, 5])
[(1, 1, 1), (2, 2, 2), (3, None, 3), (None,…
565/1068
501
import foo
from .moduleY import spam
from.moduleYimportspamasham 
from . import moduleY
fr…
566/1068
502
shapes
├── init .py
|
├── circle.py
|
├── square.py
|
└── triangle.py
from . import ut…
567/1068
503
import io
assert io.open is open # the builtin is an alias 
buffer = io.StringIO()
buffer.w…
568/1068
504
round(4.8) 
# 5
round(4.8) 
# 5.0
round(1.5) # Out: 2 
round(0.5) # Out: 0 
round(-0.5) …
569/1068
505
hi = sys.stdout.write('hello world\n') 
# Out: hello world
type(hi)
# Out: <type 'NoneType'…
570/1068
506
class MyClass:
def nonzero (self): 
return False
my_instance = MyClass()
print bool(MyClas…
571/1068
507
Capítulo 101: Indexación y corte
Sintaxis
• obj [inicio: detener: paso]
• cortar
• rebanad…
572/1068
508
# "ace" (every 2nd element)
# "bd" (from index 1, to index 4 (excluded), every 2nd element)
…
573/1068
509
arr[:]
arr = ['a', 'b', 'c'] 
copy = arr[:] 
arr.append('d')
print(arr) # ['a', 'b', 'c', …
574/1068
510
del a[4,2,5] 
a
# Out: [1, 100, 4, 8]
<-- indicated which element came from which index
a …
575/1068
511
lst = [1, 2, 3, 4, 5]
lst[1:4] = [6]
print(lst) # Out: [1, 6, 5]
lst = [1, 2, 3]
lst[:] = …
576/1068
512
print(arr[-1])
>> 'd'
print(arr[-2])
>> 'c'
print arr[6]
Traceback (most recent call last…
577/1068
513
headers_set = [] 
headers_sent = []
def write (data): 
"""
Writes header data from 'start_…
578/1068
514
# This is the most important piece of the 'server object'
# Our result will be generated by t…
579/1068
515
pip install amqpstorm
from amqpstorm import Connection
def on_message(message):
"""This fun…
580/1068
516
channel = connection.channel()
channel.basic.consume(callback=on_message, queue='simple_queue…
581/1068
517
message.publish(routing_key='simple_queue')
channel.queue.bind(exchange='amq.direct', routing…
582/1068
518
from amqpstorm import Connection
connection = Connection('127.0.0.1', 'guest', 'guest') 
# C…
583/1068
519
import collections
>>> collections.Iterator()
class MyIterable: 
def iter (self):
return s…
584/1068
520
class MyIterable(object): #or collections.Iterator, which I'd recommend....
....
def iter (s…
585/1068
521
a, = iterable
def foo():
yield 1
a, = foo() # a = 1 
nums = [1, 2, 3]
a, = nums # ValueEr…
586/1068
522
from kivy.app import App
from kivy.uix.label import Label
class Test(App): 
def build(self)…
587/1068
523
def build(self):
return Label(text='Hello world')
if name == ' main ':
Test().run()
La dec…
588/1068
524
589/1068
525
try:
self.version = "Expat %d.%d.%d" % expat.version_info 
except AttributeError:
pass # un…
590/1068
526
class CompileError(Exception): 
pass
class _BaseSubmittingController(_BaseController): 
def…
591/1068
527
def time_step(agents): 
for agent in agents:
update_agent(agent)
try:
metadata = metadata[…
592/1068
528
print('hello world!') 
# out: hello world!
foo = 1
bar = 'bar' 
baz = 3.14
print(foo) 
#…
593/1068
529
import random
#telling python to include a function to create random numbers 
randnum = rand…
594/1068
530
>>> def sendit(out, *values, sep=' ', end='\n'):
... print(*values, sep=sep, end=end,file=out…
595/1068
531
import module2.py
print('hello')
Capítulo 108: La variable especial name
Introducción
La v…
596/1068
532
if name == 'main ': 
print('hello')
import os
class C:
pass
def f(x):
x += 2
return x
…
597/1068
533
logger = logging.getLogger( name )
Utilizar en el registro
Al configurar la funcionalidad de…
598/1068
534
class BaseClass(object): 
pass
class DerivedClass(BaseClass): 
pass
class Rectangle():
de…
599/1068
535
r.area()
# Output: 12 
r.perimeter() 
# Output: 14
s.area()
# Output: 4 
s.perimeter() 
…
600/1068
536
class C:
x = 2 # class variable
def init (self, y):
self.y = y # instance variable
C.x 
#…
601/1068
537
class A(object): 
def f(self, x):
return 2 * x
A.f
# <function A.f at ...> (in Python 3.x)…
602/1068
538
A.f(1, 7)
# Python 2: TypeError: unbound method f() must be called with
# A instance as firs…
603/1068
539
d = D()
d.multiplier = 1337 
(D.multiplier, d.multiplier) 
# (2, 1337)
d.f
# <bound metho…
604/1068
540
class MyClass: 
pass
my_inst = MyClass() 
type(my_inst)
# <class ' main .MyClass'>
my_ins…
605/1068
541
class Rectangle2D(object):
def init (self, width, height, pos=None, color='blue'): 
self.wid…
606/1068
542
fb = FooBar()
>>> fb.foo
'attr foo of Foo'
>>> FooBar.mro()
[<class ' main .FooBar'>, <cla…
607/1068
543
foobar init 
foo init
print isinstance(a,FooBar) 
print isinstance(a,Foo) 
print isinstanc…
608/1068
544
class Person(object):
def init (self, first_name, last_name, age): 
self.first_name = first_…
609/1068
545
In [2]: bob = Person("Bob", "Bobberson", 42)
In [3]: alice = Person.from_full_name("Alice Hen…
610/1068
546
class A(object):
def init (self, num): 
self.num = num
def add (self, other):
return A(sel…
611/1068
547
A.get_num = get_num
foo = A(42) 
A.get_num = get_num 
bar = A(6); 
foo.get_num() # 42
bar…
612/1068
548
def rename(self, renamed): # regular method 
"""Reassign and print the name attribute."""
se…
613/1068
549
>>> # Instances
>>> kelly = Person("Kelly")
>>> joseph = Person("Joseph")
>>> john_doe = Pe…
614/1068
550
class MyClass(object):
def init (self): 
self._my_string = ""
@property
def string(self):
…
615/1068
551
# Make hp read only by not providing a set method 
@property
def hp(self):
return self._hp
…
616/1068
552
class Singleton: 
def new (cls):
try:
it =cls. it
exceptAttributeError:
it = cls. it = ob…
617/1068
553
@Singleton 
class Single:
def init (self): 
self.name=None 
self.val=0
def getName(self):…
618/1068
554
import csv
with open('/tmp/output.tsv', 'wt') as out_file: 
tsv_writer = csv.writer(out_file…
619/1068
555
lst = [1, 2, 3, 4]
lst[0] # 1
lst[1] # 2
lst[4] # IndexError: list index out of range
lst[…
620/1068
556
lst[5:8]
lst[1:10]
# [] since starting index is greater than length of lst, returns empty li…
621/1068
557
a = [1, 2, 3, 4, 5]
# Append values 6, 7, and 7 to the list 
a.append(6)
a.append(7) 
a.ap…
622/1068
558
a.pop(2)
# Returns: 5
# a: [0, 1, 2, 3, 4,
a.pop(8)
# Returns: 7
# a: [0, 1, 2, 3, 4,
# …
623/1068
559
import datetime
class Person(object):
def init (self, name, birthday, height): 
self.name =…
624/1068
https://riptutorial.com/es/home 560
import datetime
l = [{'name':'John Cena', 'birthday': datetim…
625/1068
561
a.clear() 
# a = []
b = ["blah"] * 3
# b = ["blah", "blah", "blah"] 
b = [1, 3, 5] * 5
# …
626/1068
562
new_list = list(old_list)
import copy
new_list = copy.copy(old_list) #inserts references to …
627/1068
563
for (index, item) in enumerate(my_list):
print('The item in position {} is: {}'.format(index,…
628/1068
564
In [3]: rev = reversed(numbers)
In [4]: rev
Out[4]: [9, 8, 7, 6, 5, 4, 3, 2, 1]
In [1]: num…
629/1068
565
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3', 'b4'] 
for a, b in zip(alist, blist):
…
630/1068
566
nums = [1, 1, 0, 1]
all(nums) 
# False
chars = ['a', 'b', 'c', 'd'] 
all(chars)
# True
n…
631/1068
567
for row in range(len(alist)): #A less Pythonic way to loop through lists 
for col in range(le…
632/1068
568
print(alist[1][1:])
#[[8, 9, 10], 15, [12, 13, 14]]
#Slices still work
print(alist)
#[[[1,…
633/1068
569
my_list=[{1} for _ in range(10)]
634/1068
570
[<expression> for <element> in <iterable> if <condition>]
[x for x in range(10) if x % 2 == 0…
635/1068
571
[x if x % 2 == 0 else None for x in range(10)]
# Out: [0, None, 2, None, 4, None, 6, None, 8,…
636/1068
572
[x if x > 2 else '*' for x in range(10) if x % 2 == 0] 
# Out: ['*', '*', 4, 6, 8]
[x if (x …
637/1068
573
In [1]: data = [[1,2],[3,4],[5,6]]
In [2]: def f():
...: output=[]
...: for each_list in da…
638/1068
574
filter(lambda x: x % 2 == 0, range(10)) # even numbers < 10 
map(lambda x: 2*x, range(10)) # …
639/1068
575
#List Comprehension with nested loop
[x + y for x in [1, 2, 3] for y in [3, 4, 5]]
#Out: [4,…
640/1068
576
>>> [(i, j, k) for i, j, k in zip(list_1, list_2, list_3)] 
[(1, 'a', '6'), (2, 'b', '7'), (3…
641/1068
577
a, b = (1, 2)
print(a) 
# Prints:1 
print(b)
# Prints: 2
a, b, c = [1]
# Raises: ValueEr…
642/1068
578
a, b, *other, z = [1, 2, 3, 4, 5] 
print(a, b, z, other)
# Prints: 1 2 5 [3, 4]
a, _ = [1, …
643/1068
579
fun1(1, 2, 3)
def fun2(arg1='a', arg2='b', arg3='c'): 
return (arg1,arg2,arg3)
fun2(arg2=2,…
644/1068
580
fun1(**{'arg1':1, 'arg2':2})
# Raises: TypeError: fun1() missing 1 required positional argume…
645/1068
581
fun3(*[1,2], **{'arg2':42, 'arg3':3})
# Raises: TypeError: fun3() got multiple values for arg…
646/1068
582
Capítulo 114: Listar comprensiones
Introducción
Las comprensiones de listas en Python son co…
647/1068
583
[ <expression> for <element> in <iterable> if <condition> ]
squares = [x * x for x in (1, 2, …
648/1068
584
def foo(i):
return i, i + 0.5
for i in range(3): 
for x in foo(i):
yield str(x)
[str(x)
…
649/1068
585
[x.sort() for x in [[2, 1], [4, 3], [0, 1]]] 
# [None, None,None]
[sorted(x) for x in [[2, 1…
650/1068
586
{x: x * x for x in (1, 2, 3, 4)}
# Out: {1: 1, 2: 4, 3: 9, 4: 16}
dict((x, x * x) for x in (…
651/1068
587
{**dict1, **dict2}
# Out: {'w': 1, 'x': 2, 'y': 2, 'z': 2}
print(swapped)
# Out: {a: 1, b: …
652/1068
588
for i in [x**2 for x in range(10)]: 
print(i)
"""
g = (x**2 for x in xrange(10)) 
print(g[…
653/1068
589
for i in (x**2 for x in xrange(10)): 
print(i)
"""
Out:
0
1
4
.
.
. 
81 
"""
for s…
654/1068
590
# A set containing every value in range(5):
{x for x in range(5)} 
# Out: {0, 1, 2, 3, 4}
#…
655/1068
591
>>> [v for v in (f(x) for x in range(1000)) if v > 10] 
[16, 25, 36, ...]
>>> [v for v in ma…
656/1068
592
[item for sublist in l for item in sublist]
[x + y for x, y in [(1, 2), (3, 4), (5, 6)]]
# O…
657/1068
593
# Count the numbers in `range(1000)` that are even and contain the digit `9`: 
print (sum(
1…
658/1068
594
class Node:
def init (self, val): 
self.data = val 
self.next = None
def getData(self): 
…
659/1068
595
current = current.getNext() 
return count
def search(self,item):
"""Search foritemin list.I…
660/1068
596
current = self.head 
pos = 0
found = False
while current is not None and not found: 
if cu…
661/1068
597
ll=LinkedList() 
ll.add('l')
ll.add('H')
ll.insert(1,'e')
ll.append('l')
ll.append('o') 
…
662/1068
598
BsonDocument argsBson = BsonDocument.Parse("{ 'x' : '1', 'y' : '2' }");
string argsFile = str…
663/1068
599
import sys 
import json
# load input arguments from the text file 
filename = sys.argv[ 1 ]…
664/1068
600
Código C # llamando al script Python
using MongoDB.Bson; 
using System;
using System.Diagno…
665/1068
601
{
//delete/save temporary.txtfile 
if (!saveInputFile)
{
File.Delete(argsFile);
}
}
Con…
666/1068
602
finally:
# --- Cleanup on exit ---
stdscr.keypad(0) 
curses.echo() 
curses.nocbreak()
cur…
667/1068
603
Aquí, la envoltura inicializará las cursas, creará stdscr , un objeto WindowObject y pasará am…
668/1068
604
import xml.etree.ElementTree as ET 
tree = ET.parse("yourXMLfile.xml") 
root = tree.getroot(…
669/1068
605
root.remove(element)
tree.write('output.xml')
import xml.etree.ElementTree as ET
p=ET.Eleme…
670/1068
606
for event, elem in ET.iterparse("yourXMLfile.xml"):
... do something ...
events=("start", "e…
671/1068
607
import xml.etree.cElementTree as ET 
tree = ET.parse('sample.xml') 
tree.findall('Books/Book…
672/1068
608
import cmath
z = 2+3j # A complex number 
cmath.phase(z) # 0.982793723247329
cmath.polar(z)…
673/1068
609
cmath.sinh(z) # (-3.59056458998578+0.5309210862485197j) 
cmath.cosh(z) # (-3.7245455049153224…
674/1068
610
# Imports the Flask class 
from flask import Flask
# Creates an app and checks if its the ma…
675/1068
611
if name == " main ": app.run(host="0.0.0.0", 
port=80, debug=True)
@app.route("/") 
def ind…
676/1068
612
@app.route("/login", methods=["GET"]) 
def login_form():
return "This is the login form" 
@…
677/1068
613
- application.py
/templates
- about-us.html
- login-form.html
/static
/styles
- about-st…
678/1068
614
from flask import request
@app.route("/api/users/<username>") 
def user_api(username):
try:…
679/1068
615
@app.route("/upload", methods=["POST"]) 
def upload_file():
f = request.files["wordlist-uplo…
680/1068
616
lst=[[1,2,3],[4,5,6],[7,8,9]]
print (lst[0])
#output: [1, 2, 3]
print (lst[1])
#output: [4…
681/1068
617
[[[111,112,113],[121,122,123],[131,132,133]],\
[[211,212,213],[221,222,223],[231,232,233]],\
…
682/1068
618
Dummy = type('OtherDummy', (), dict(x=1)) 
Dummy. class # <type 'type'> 
Dummy(). class . cl…
683/1068
619
>>> class Foo(object):
... pass
>>> type(Foo) 
type
class MyDummy(object):
 metaclass = m…
684/1068
620
class MySingleton(metaclass=SingletonType): 
pass
MySingleton() is MySingleton() # True, onl…
685/1068
621
Creating class Spam
[insert example string here]
>>> type(5)
<type 'int'>
>>> type(str)
<…
686/1068
622
class AnotherMetaclass(type):
def new (cls, name, parents, dct): 
# cls is this class
# nam…
687/1068
623
• Todo es un objeto en Python, así que todo tiene una clase.
• La clase de una clase se llama…
688/1068
624
class Parent(object): 
def introduce(self):
print("Hello!")
def print_name(self): 
print("…
689/1068
625
Capítulo 124: Métodos de cuerda
Sintaxis
• str.capitalize () -> str
• str.casefold () -> st…
690/1068
626
"XßΣ".casefold() 
# 'xssσ'
"XßΣ".lower() 
# 'xßς'
• str.swapcase () -> str
• str.title ()…
691/1068
627
"This is a 'string'.".upper() 
# "THIS IS A'STRING'."
"This IS a 'string'.".lower() 
# "thi…
692/1068
628
map(str.upper,["These","are","some","'strings'"])
# ['THESE', 'ARE', 'SOME', "'STRINGS'"]
>>…
693/1068
629
>>> "Thisis a sentence.".rsplit('e', maxsplit=1) 
['This is a sentenc', '.']
>>>"Thisisasent…
694/1068
630
>>> """It can foo multiple examples of foo if you want, \
... or you can limit the foo with t…
695/1068
631
>>> "I am from {}. I love cupcakes from {}!".format("Australia", "Australia")
>>> "I am from …
696/1068
632
>>> s = "This is a test string"
>>> s.startswith("T") 
True
>>>s.startswith("Thi") 
True
…
697/1068
633
>>> s.endswith('stop.') 
True
>>> s.endswith('Stop.') 
False
>>> s.endswith(('.', 'somethi…
698/1068
634
isdecimal isdigit isnumeric
>>> "Hello world".islower() 
False
>>> "hello world".islower() …
699/1068
635
>>> "Hello2World".isalnum() 
True
>>> "HelloWorld".isalnum() 
True
>>> "2016".isalnum() 
…
700/1068
636
>>> 'this syntax is very useful'.translate(None, 'aeiou') 
'ths syntx s vry sfl'
>>> transla…
701/1068
637
'spaciousstring '
>>> " spacious string ".rstrip()
>>> "ß".lower() 
'ß'
>>> "ß".upper().lo…
702/1068
638
>>> import unicodedata
>>> [unicodedata.name(char) for char in "ê"] 
['LATINSMALLLETTEREWITH…
703/1068
639
>>> string.ascii_letters 
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.…
704/1068
640
>>> string.punctuation '!"#$%&\'()*+,-
./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace 
' \t\n\…
705/1068
641
interstates_lengths = { 
5: (1381, 2222),
}
for road, length in interstates_lengths.items()…
706/1068
642
characters.
# b'\xc2\xa9 abc'
# str.encode produces a byte array, showing ASCII-range bytes …
707/1068
643
True
708/1068
644
class A(object):
# func: A user-defined function object 
#
# Note that func is a function o…
709/1068
645
Ejemplo de tortuga
El siguiente es un ejemplo del uso de una función definida por el usuario …
710/1068
646
class Vehicle(object):
"""A generic vehicle class."""
def init (self, position): 
self.posi…
711/1068
647
class Foo(main_super, mixin): ...
class RadioUserMixin(object): 
def init (self):
self.radi…
712/1068
648
>>> x = MyClass()
>>> x.test() 
Base
clases se define de derecha a izquierda. 
Por ejemplo…
713/1068
649
def add_student(): 
try:
students['count'] += 1 
except KeyError:
students['count'] = 1
d…
714/1068
650
import sys
def main():
# Your code starts here
# Don't forget to provide a return code 
re…
715/1068
651
import random
laughs = ["Hi", "Ho", "He"]
random.shuffle(laughs) # Shuffles in-place! Don't …
716/1068
652
# Output may vary!
laughs , 1 )) # Take one element
# |--sequence--|--number--|
print(rando…
717/1068
653
random.random() # Out: 0.66486093215306317
random.uniform(1, 8) # Out: 3.726062641730108
ale…
718/1068
654
random.seed(5) # Reset the random module to the same fixed state. 
print(random.randrange(0, …
719/1068
655
print([secure_rand_gen.randrange(10) for i in range(10)]) 
# [9, 6, 9, 2, 2, 3, 8, 0, 9, 9]
…
720/1068
656
import string
alphabet = string.ascii_letters + string.digits 
while True:
password =''.joi…
721/1068
657
import asyncio
async def main(): 
print(await func())
async def func():
# Do time intensiv…
722/1068
658
import asyncio
from concurrent.futures import ThreadPoolExecutor
def func(a, b):
# Do time …
723/1068
659
import asyncio 
import uvloop
if name == " main ": 
asyncio.set_event_loop(uvloop.new_event…
724/1068
660
import asyncio
# event trigger function 
def trigger(event):
print('EVENT SET')
event.set(…
725/1068
661
if name == ' main ': #
The main loop
loop = asyncio.get_event_loop() 
loop.run_until_comple…
726/1068
662
727/1068
663
from Queue import Queue 
question_queue = Queue()
for x in range(1,10): 
temp_dict = ('key'…
728/1068
664
import collections
counts = collections.Counter([1,2,3])
>>> collections.Counter('Happy Birt…
729/1068
665
>>> collections.Counter('I am Sam Sam I am That Sam-I-am That Sam-I-am! I do not like that 
S…
730/1068
666
>>> state_capitals = collections.defaultdict(str)
>>> state_capitals 
defaultdict(<class 'st…
731/1068
667
>>> s = [('NC', 'Raleigh'), ('VA', 'Richmond'), ('WA', 'Seattle'), ('NC', 'Asheville')]
>>> d…
732/1068
668
>>> d['foo'] = 4
>>> print(d)
OrderedDict([('foo', 4), ('bar', 6), ('baz', 7), ('foobar', 8)…
733/1068
669
Human = namedtuple('Person', 'age, height, name') 
dave = Human(30, 178, 'Dave')
print(dave)…
734/1068
670
Fuente: https://docs.python.org/2/library/collections.html
colecciones.ChainMap
ChainMap es …
735/1068
671
import collections
# define two dictionaries with at least some keys overlapping. 
dict1 = {…
736/1068
672
>>> from functools import partial
>>> unhex = partial(int, base=16)
>>> unhex. doc = 'Conver…
737/1068
673
from functools import reduce 
def factorial(n):
return reduce(lambda a, b: (a*b), range(1, n…
738/1068
674
>>> fib.cache_info()
CacheInfo(hits=13, misses=16, maxsize=None, currsize=16)
diferentes tip…
739/1068
675
x = 1.55
y = -1.55
# round to the nearest integer 
round(x) # 2
round(y) # -2
# the secon…
740/1068
676
round(0.5) # 0
round(1.5) # 2
round(2.675, 2) # 2.67, not 2.68!
>>> math.floor(-1.7)
-2.0
…
741/1068
677
math.log(100, 10) #2.0
math.log(27, 3) # 3.0
math.log(1, 10) # 0.0
math.hypot(2, 4) # Just …
742/1068
678
math.atan(math.inf)
# Out: 1.5707963267948966 # This is just "pi / 2"
math.atan(float('inf')…
743/1068
679
pos_inf = math.inf 
neg_inf = -math.inf 
not_a_num = math.nan
math.inf == float('inf') 
# …
744/1068
680
math.isinf(pos_inf) 
# Out: True
math.isinf(neg_inf) 
# Out: True
neg_inf == float('-inf')…
745/1068
681
-5.0 * pos_inf == neg_inf 
# Out: True
-5.0 * neg_inf == pos_inf 
# Out: True
pos_inf * ne…
746/1068
682
math.inf is math.inf, math.nan is math.nan 
# Out: (True, True)
float('inf') is float('inf')…
747/1068
683
# z.conjugate() == z.real - z.imag * 1j
z.conjugate() 
# Out: (1-3j)
# real part and imagin…
748/1068
684
cmath.phase(complex(-1.0, 0.0))
# Out: 3.141592653589793
cmath.phase(complex(-1.0, -0.0))
#…
749/1068
685
z = cmath.rect(*cmath.polar(1+1j))
z
# Out: (1.0000000000000002+1.0000000000000002j)
cmath.…
750/1068
686
Capítulo 134: Módulo de navegador web
Introducción
De acuerdo con la documentación estándar …
751/1068
687
Parámetro Detalles
webbrowser.get()
Observaciones
Lasiguientetablaenumeralos tiposdenavegad…
752/1068
688
import webbrowser 
webbrowser.open("http://stackoverflow.com")
import webbrowser 
webbrowse…
753/1068
689
import webbrowser
ff_path = webbrowser.get("C:/Program Files/Mozilla Firefox/firefox.exe") 
…
754/1068
690
# p = 1, d = deque([2, 3])
# d = deque([5, 2, 3])
d = deque([1, 2, 3]) 
p = d.popleft()
d.…
755/1068
691
from collections import deque
d = deque(maxlen=3) # only holds 3 items 
d.append(1) # deque(…
756/1068
692
dl.reverse() # deque([6, 5, 4, 3, 2, 0, -2])
from collections import deque
def bfs(graph, ro…
757/1068
693
lst = [("a", 5, 6), ("b", 2, 4), ("a", 2, 5), ("c", 5, 6)]
testGroupBy(lst)
lst = [("a", 5, …
758/1068
694
results = fetch_paged_results() # returns a generator 
limit = 20 # Only want the first 20 re…
759/1068
695
for x in xrange(10):
for y in xrange(10): 
print x, y
its = [xrange(10)] * 2
for x,y in it…
760/1068
696
for number in itertools.count(start=10, step=4): 
print(number)
if number > 20: 
break
10
…
761/1068
697
def takewhile(predicate, iterable): 
for x in iterable:
if predicate(x): 
yield x
else:
b…
762/1068
698
from itertools import zip_longest
a = [i for i in range(5)] # Length is 5
b = ['a', 'b', 'c'…
763/1068
699
from itertools import chain
a = (x for x in ['1', '2', '3', '4'])
b = (x for x in ['x', 'y',…
764/1068
700
>>> import itertools as it
>>> it.cycle('ABCD')
A B C D A B C D A B C D ...
>>> # Iterate o…
765/1068
701
nulo Ninguna
verdadero Falso Verdadero Falso
numero (real) flotador
número (int) En t
cuer…
766/1068
702
# my_json module
import json
from functools import partial
def serialise_object(obj):
# Do…
767/1068
703
# my_json module
import json
from functools import partial
class MyEncoder(json.JSONEncoder…
768/1068
704
import json
d = {
'foo': 'bar', 
'alice': 1,
'wonderland': [1, 2, 3]
}
with open(filenam…
769/1068
705
import json
json_file_path = './data.json' 
data={u"foo": u"bar",u"baz":[]}
with open(json_…
770/1068
706
$ cat foo.json | python -m json.tool
>>> data = {"cats": [{"name": "Tubbs", "color": "white"}…
771/1068
707
>>> print(json.dumps(data, sort_keys=True))
{"cats": [{"color": "white", "name": "Tubbs"}, {"…
772/1068
708
773/1068
709
1 + 1
# Output: 2
from operator import add 
add(1, 1)
# Output: 2
from operator import mu…
774/1068
710
dict((i, dict(v)) for i, v in groupby(adict.items(), lambda x: x[1]))
alist_of_tuples = [(5,2…
775/1068
711
pyautogui.displayMousePosition() #gave you the current mouse position but should be done 
on …
776/1068
712
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
# Create table 
c.ex…
777/1068
713
a=c.fetchall() #which is similar to list(cursor) method used previously 
for row in a:
print…
778/1068
714
import threading
def foo():
print "Hello threading!"
my_thread = threading.Thread(target=fo…
779/1068
715
# print 'The main program continuesto run in foreground.' 
t.join()
print("The main program …
780/1068
716
q = Queue()
t1 = Thread(target=consumer, args=(q,)) 
t2 = Thread(target=producer, args=(q,))…
781/1068
717
def split_line(line, cols): 
if len(line) > cols:
new_line = ''
# The actual way to send
#…
782/1068
718
import threading 
import time
class StoppableThread(threading.Thread):
"""Thread class with…
783/1068
719
Basado en esta pregunta .
self._stop_event.set()
def join(self, *args, **kwargs): 
self.sto…
784/1068
720
import multiprocessing 
import time
from random import randint
def countUp(): 
i = 0
whil…
785/1068
721
from multiprocessing import Pool
def cube(x):
return x ** 3
if name == " main ": 
pool = P…
786/1068
722
>>> a = 1
>>> id(a) 
140128142243264
>>> a += 2
>>> a 
3
>>> id(a) 
140128142243328
>>…
787/1068
723
>>> stack = "Stack"
>>> stackoverflow = stack + "Overflow"
>>> id(stack) 
140128069348184
…
788/1068
724
>>> c = b
>>> c += b' rocks!'
>>> c
bytearray(b'StackOverflow rocks!')
>>> b
bytearray(b'…
789/1068
725
>>> def tuple_add3(tin): 
tin += (3,)
return tin
>>> a = (1, 2, 3)
>>> b = tuple_add3(a)
…
790/1068
726
from py2neo import authenticate, Graph, Node, Relationship 
authenticate("localhost:7474", "n…
791/1068
727
def get_autocomplete(text): 
query = """
start n = node(*) where n.name =~ '(?i)%s.*' return…
792/1068
728
where l.name='Donald Trump' 
MATCH (n:NewsArticle)-[]->(m) 
with m,count(n) as num where num…
793/1068
729
#! /usr/bin/env python
class Node:
definit (self, cargo=None, next=None): 
self.car = cargo…
794/1068
730
class Foo(object): 
def init (self):
self. bar = None
@property
def bar(self):
if self. b…
795/1068
731
>>> wallet = Cash(2.50)
>>> print(wallet.formatted)
$2.50
>>> print(wallet.value) 
2.5
>>…
796/1068
732
def getY (self): 
return self._y
def setY (self, value):
self._y = 1000 + value # Weird but…
797/1068
733
a2.x = 7
a2.y = 8
a1.t = 77
a1.u = 88
print (a1.x, a1.y, a1.y2)
print (a2.x, a2.y, a2.y2)…
798/1068
734
x = True 
y = True
z = x and y # z = True
x = True 
y = False
z = x and y # z = False
x …
799/1068
735
x = True
y = not x # y = False
x = False
y = not x # y = True
>>> def true_func():
... pr…
800/1068
736
def or_(a, b): 
if a:
return a 
else:
return b
def and_(a, b): 
if not a:
return a 
el…
801/1068
737
# 60 = 0b111100 
# 30 = 0b011110 
60 & 30
# Out: 28
# 28 = 0b11100
bin(60 & 30)
# Out: 0…
802/1068
738
#60=0b111100 
#30=0b011110 
60 | 30
# Out: 62
# 62 = 0b111110
bin(60 | 30) 
# Out: 0b111…
803/1068
739
3 << 4
# Out: 48
# 8 = 0b1000 
8 >> 2
# Out: 2
# 2 = 0b10
bin(8 >> 2) 
# Out: 0b10
36 …
804/1068
740
# 0 = 0b0000 0000
~0
# Out: -1
# -1 = 0b1111 1111
# 1 = 0b0000 0001
~1
# Out: -2
# -2 =…
805/1068
741
# -0 = 0b0000 0000
~-0
# Out: -1
# -1 = 0b1111 1111
# 0 is the obvious exception to this r…
806/1068
742
import operator # contains 2 argument arithmetic functions for the examples
a, b = 1, 2
# Us…
807/1068
743
[1, 2, 3] + [4, 5,6] # = [1, 2, 3, 4, 5, 6]
"first string " + "second string" # = 'first stri…
808/1068
744
3 * 'ab' # = 'ababab'
3 * ('a', 'b') # = ('a', 'b', 'a', 'b', 'a', 'b')
a, b, c, d, e = 3, 2…
809/1068
745
from operator import truediv 
truediv(a, b) # = 1.5
# = 1.5
# = 1.5
float(a) / b 
a / flo…
810/1068
746
# does so more efficiently
# 0, calculates (2 ** 3) % 2, but as per Python docs,
a, b, c = 2…
811/1068
747
# optional base argument. Default is math.e 
math.log(5, math.e) # = 1.6094379124341003 
cma…
812/1068
748
a, b = 1, 2
import math
math.sin(a) # returns the sine of 'a' in radians 
# Out: 0.84147098…
813/1068
749
quotient, remainder = divmod(9, 4)
# quotient = 2, remainder = 1 as 4 * 2 + 1 == 9
O utiliza…
814/1068
750
import cProfile 
def f(x):
return "42!" 
cProfile.run('f(12)')
import cProfile, pstats, St…
815/1068
751
3 function calls in 0.000 seconds 
Ordered by: standard name
$ kernprof -l script_to_profile…
816/1068
752
$ python -m timeit '"-".join(str(n) for n in range(100))' 
10000 loops, best of 3: 40.3 usec …
817/1068
753
import os 
os.path.join('a', 'b', 'c')
>>> os.path.join('a', 'b', 'c') 
'a\b\c'
>>> os.pat…
818/1068
754
>>> p = os.path.join(os.getcwd(), 'foo.txt')
>>> p
'/Users/csaftoiu/tmp/foo.txt'
>>> os.pat…
819/1068
755
symlink = dirname + 'some_sym_link' 
os.path.islink(symlink)
mount_path = '/home' 
os.path.…
820/1068
756
orders_df = pd.DataFrame()
orders_df['customer_id'] = [1,1,1,1,1,2,2,3,3,3,3,3]
orders_df['o…
821/1068
757
that is called 'number_of_orders_per_cient'
orders_df # Take the original dataframe
.groupby…
822/1068
758
each group separately
#Inspecting the results... 
print(orders_df)
# customer_id order_id i…
823/1068
759
from types import MethodType
class Animal(object):
def init (self, *args, **kwargs):
self.n…
824/1068
760
generic_animal = Animal()
king_cobra = Animal(name='King Cobra', walk=snake_walk)
elephant =…
825/1068
761
class Singleton(object): 
def new (cls):
# hasattr methodchecksif the class object an instan…
826/1068
762
from abc import ABCMeta, abstractmethod
class Music():
 metaclass = ABCMeta 
@abstractmetho…
827/1068
763
class Proxy:
def init (self, current_user, reservation_service): 
self.current_user = curren…
828/1068
764
BENEFICIOS
• estamos evitando cualquier cambio en ReservationService cuando se cambianlas 
r…
829/1068
765
In [1]: import string
In [2]: %%timeit s=""; long_list=list(string.ascii_letters)*50
....: f…
830/1068
766
$ kernprof -lv so6.py
Wrote profile results to so6.py.lprof 
Timer unit: 4.27654e-07 s
Tota…
831/1068
767
$ python -m cProfile -s time main.py
• filename:lineno(function) : proporciona los datos resp…
832/1068
768
data={'a':'some_value',
'b':[9,4,7],
'c':['some_str','another_str','spam','ham'], 
'd':{'ke…
833/1068
769
import pickle
file=open('filename','rb') #file object in binary read mode 
data=pickle.load(…
834/1068
770
Capítulo 156: pip: PyPI Package Manager
Introducción
pip es el gestor de paquetes más utiliz…
835/1068
771
$ pip install SomePackage
$ pip install SomePackage==1.0.4
$ pip install SomePackage>=1.0.4
…
836/1068
772
$ pip list
# example output 
docutils (0.9.1)
Jinja2 (2.6)
Pygments (1.5)
Sphinx (1.1.2)
…
837/1068
773
for /F "delims= " %i in ('pip list --outdated --local') do pip install -U %i
pip freeze > req…
838/1068
774
\path\to\that\python.exe -m pip install some_package # on Windows OR
/usr/bin/python25 -m pip…
839/1068
775
win_amd64 - y luego la versión de Python debe coincidir, es decir, para Python 34, el nombre d…
840/1068
776
> py -3.5-32 -m venv demo-pip
> demo-pip\Scripts\activate.bat
> python -m pip install -U pip…
841/1068
777
Using cached Jinja2-2.9.6-py2.py3-none-any.whl 
Collecting Pygments>=2.0 (from Sphinx==1.7.de…
842/1068
778
versiones anteriores y volver a intentarlo.
843/1068
779
from string import Template
data = dict(item = "candy", price = 8, qty = 2) 
# define the te…
844/1068
780
class Shape: 
"""
This is a parent class that is intended to be inherited by other classes 
…
845/1068
781
class Square:
side_length = 2
def calculate_square_area(self): 
return self.side_length ** …
846/1068
782
class Duck:
def quack(self): 
print("Quaaaaaack!")
def feathers(self):
print("The duck has…
847/1068
783
La salida es:
Quaaaaaack!
El pato tiene plumas blancas y grises. 
La persona imita a un pat…
848/1068
784
import psycopg2
# Establish a connection to the existing database 'my_database' using 
# the…
849/1068
785
# OUTPUT: [(1, 'John', 'Doe'), (2, 'Jane', 'Doe')]
850/1068
786
Capítulo 160: Precedencia del operador
Introducción
Los operadores de Python tienen un orden…
851/1068
787
>>> a, b, c, d = 2, 3, 5, 7
>>> a ** (b + c) # parentheses 
256
>>> a * b ** c # exponent: …
852/1068
788
import threading 
import time
def process(): 
time.sleep(2)
start = time.time() 
process(…
853/1068
789
import threading 
import time
def somefunc(i): 
return i * i
def otherfunc(m, i): 
return…
854/1068
790
import threading 
import os
def process():
print("Pid is %s, thread id is %s" % (os.getpid(…
855/1068
791
import threading
obj = {}
obj_lock = threading.Lock()
def objify(key, val):
print("Obj has…
856/1068
792
shared_num.value += 1
ps = [multiprocessing.Process(target=increment) for n in range(4)] 
fo…
857/1068
793
s=lambda x:x*x 
s(2) =>4
name_lengths = map(len, ["Mary", "Isla", "Sam"]) 
print(name_lengt…
858/1068
794
# outputs[5,6]
arr=[1,2,3,4,5,6]
[ifori infilter(lambda x:x>4,arr)]
Filtro toma una función…
859/1068
795
Capítulo 163: Programación IoT con Python y 
Raspberry PI
Examples
Ejemplo - sensor de temp…
860/1068
796
R1 es una resistencia de 4.7k ohmios para elevar el nivel de voltaje
1. Vcc debe conectarse a…
861/1068
797
import glob 
import time
RATE = 30
sensor_dirs = glob.glob("/sys/bus/w1/devices/28*")
if l…
862/1068
798
pip install pytest
# projectroot/module/code.py 
def add(a, b):
return a + b
# projectroot…
863/1068
799
# projectroot/tests/test_code.py 
from module import code
def test_add failing():
assert co…
864/1068
800
# projectroot/tests/test_stuff.py 
import pytest
from module import stuff
def test_foo_upda…
865/1068
801
@pytest.fixture
def prepped_stuff(): 
my_stuff = stuff.Stuff() 
my_stuff.prep()
return my_…
866/1068
802
# projectroot/module/stuff.py 
class Stuff(object):
def prep(self): 
self.foo = 1
self.bar…
867/1068
803
¡Y eso concluye la Introducción a los Aparatos de Prueba!
Para obtener más información, consu…
868/1068
804
"""PyAudio Example: Play a wave file (callback version)."""
import pyaudio 
import wave 
im…
869/1068
805
import pyaudio 
import wave 
import sys
CHUNK = 1024
if len(sys.argv) < 2:
print("Plays a…
870/1068
806
Para usar PyAudio, primero cree una instancia de PyAudio usando pyaudio.PyAudio () (1), que 
…
871/1068
807
pip install pygame
Capítulo 166: pygame
Introducción
Pygame es la biblioteca de acceso para…
872/1068
808
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
Descarga directa desde …
873/1068
809
de inmediato.
Para saber cuántos canales se están utilizando actualmente, llame a
pygame.mix…
874/1068
810
import pyglet
window = pyglet.window.Window()
label = pyglet.text.Label('Hello, world',
fon…
875/1068
811
import pyglet
from pyglet.gl import *
win = pyglet.window.Window() 
glClear(GL_COLOR_BUFFER…
876/1068
812
pip install pyinstaller
Capítulo 168: PyInstaller - Distribuir código 
de Python
Sintaxis
…
877/1068
813
desarrollo de la página de descargas de PyInstaller .
Expandaelarchivoyencuentreel scriptsetu…
878/1068
814
carpeta.
Otra ventaja se siente durante las actualizaciones. Si hay algunos cambios en el cód…
879/1068
815
from ply import lex 
import ply.yacc as yacc
tokens = (
'PLUS',
'MINUS',
'TIMES',
'DIV',…
880/1068
816
'NUMBER',
)
t_ignore = ' \t'
t_PLUS = r'\+' 
t_MINUS = r'-'
t_TIMES = r'\*' 
t_DIV = r'/…
881/1068
817
import ply.lex as lex
# List of token names. This is always required 
tokens = [
'NUMBER',
…
882/1068
818
tokens = [
'NUMBER',
'PLUS',
'MINUS',
'TIMES',
'DIVIDE',
'LPAREN',
'RPAREN',
]
Guarde…
883/1068
819
def t_NUMBER(t): 
r'\d+'
t.value = int(t.value) 
return t
def t_newline(t): 
r'\n+'
t.le…
884/1068
820
t_ignore_COMMENT = r'\#.*'
t_ignore = ' \t' # ignores spaces andtabs
literals = [ '+', '-', …
885/1068
821
# Build the lexer 
#
m = MyLexer() 
m.build() 
m.test("3 + 4")
# Build the lexer
def bui…
886/1068
822
def p_expression_plus(p):
'expression : expression PLUS term'
def p_expression_minus(p):
'e…
887/1068
823
p[0] = p[1] + p[3]
def p_binary_operators(p):
'''expression : expression PLUS term
| expres…
888/1068
824
precedence = (
('nonassoc', 'LESSTHAN', 'GREATERTHAN'), # Nonassociative operators 
('left',…
889/1068
825
from requests import post
foo = post('http://httpbin.org/post', data = {'key':'value'})
prin…
890/1068
826
foo = post('http://httpbin.org/post', data = {'key':'value'}, verify=False)
foo = post('http:…
891/1068
827
from requests import post
files = {'file' : open('data.txt', 'rb')} 
foo = post('http://http…
892/1068
828
from requests import post
foo = post('http://natas0.natas.labs.overthewire.org', auth=('natas…
893/1068
829
foo = get('http://test.com/admin', auth=CustomAuth('SecretHeader', 'CustomUserAgent', 'user', …
894/1068
830
import os, sys
from openpyxl import Workbook 
from datetime import datetime
dt = datetime.n…
895/1068
831
workbook = opx.load_workbook(workbook_path, read_only=True)
first_sheet = workbook.worksheets…
896/1068
832
{'name': 'Sit', 'value': 8},
{'name': 'Amet', 'value': 32}
]
# excel file path 
xls_file =…
897/1068
833
pip install xlrd
Lee los datos de excel usando el módulo xlrd
La biblioteca xlrd de Python e…
898/1068
834
import xlrd 
book=xlrd.open_workbook('sample.xlsx')
print book.nsheets
print book.sheet_nam…
899/1068
835
# set the width of column A 
worksheet.set_column('A:A', 30, )
# set column B to 20 and incl…
900/1068
836
Capítulo 172: Recolección de basura
Observaciones
Ensunúcleo,elrecolectordebasuradePython(ap…
901/1068
837
/* Break reference cycles by clearing the containers involved. This is
* tricky business as t…
902/1068
838
/* list of uncollectable objects */ 
static PyObject *garbage = NULL;
y establecemos una ins…
903/1068
839
>>> def bar():
return Track()
>>> t = bar() 
Initialized
>>> another_t = t # assign anothe…
904/1068
840
>>> objs = [Track() for _ in range(10)] 
Initialized
Initialized 
Initialized 
Initialized…
905/1068
841
>>> import sys
>>> sys.getrefcount(1) 
797
>>> a = 1
>>> b = 1
>>> sys.getrefcount(1) 
7…
906/1068
842
import ctypes 
deallocated = 12345
ctypes.pythonapi._Py_Dealloc(ctypes.py_object(deallocated…
907/1068
843
import gc 
gc.collect()
>>> f = open("test.txt")
>>> del f
entonces se procesará la genera…
908/1068
844
>>> with open("test.txt") as f:
... pass
... # do something with f
>>> #now the f object st…
909/1068
845
from PIL import Image 
import sys
import pyocr
import pyocr.builders
tools = pyocr.get_ava…
910/1068
846
txt = tool.image_to_string( 
Image.open('test.png'), 
lang=lang,
builder=pyocr.builders.Tex…
911/1068
847
n = 0
for i in range (1, n+1): 
n += i
def recursion(n): 
if n == 1:
return 1
return n +…
912/1068
848
def factorial(n): 
if n == 0:
return 1 
else:
return n * factorial(n - 1)
que ese número.…
913/1068
849
def factorial(n): 
if n == 0:
return 1 
elif n == 1:
return 1 
else:
return n * factoria…
914/1068
850
def factorial(n): 
product = 1 
while n > 1:
product *= n 
n -= 1
return product
def fib…
915/1068
851
def fib(n):
if n <= 1:
return (n,0) 
else:
(a, b) = fib(n - 1) 
return (a + b, a)
root
…
916/1068
852
def list_tree_names(node):
for child in get_children(node): 
print(get_name(child)) 
list_t…
917/1068
853
def countdown(n): 
if n == 0:
print "Blastoff!" 
else:
print n 
countdown(n-1)
def find_…
918/1068
854
@tail_call_optimized 
def factorial(n, acc=1):
"calculate a factorial" 
if n == 0:
return …
919/1068
855
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
serversocket…
920/1068
856
from sockerserver import BaseRequestHandler, TCPServer
class EchoHandler(BaseRequestHandler):…
921/1068
857
>>> from socket import socket, AF_INET, SOCK_DGRAM
>>> sock = socket(AF_INET, SOCK_DGRAM)
>>…
922/1068
858
923/1068
859
sum([1,2,3]) # = 6
''.join(['Hello', ',', ' World']) # = 'Hello,World'
# First falsy item:
…
924/1068
860
def add(s1, s2): 
return s1 + s2
asequence = [1, 2, 3]
reduce(add, asequence) # equivalent …
925/1068
861
import operator 
reduce(operator.mul, [10, 5, -3])
# Out: -150
import operator
# non short…
926/1068
862
object -> string -> object
def repr (self):
return "Card(%s, %d)" % (self.suit, self.pips)
…
927/1068
863
class Card:
def init (self, suit, pips): 
self.suit = suit 
self.pips = pips
ace_of_spades…
928/1068
864
string_of_card = str(ace_of_spades) 
print(string_of_card)
class Card:
def init (self, suit…
929/1068
865
ace_of_spades = Card('Spades', 1) 
print(ace_of_spades)
Ace of Spades
my_hand = [ace_of_spa…
930/1068
866
class Card:
special_names = {1:'Ace', 11:'Jack', 12:'Queen', 13:'King'}
def init (self, suit…
931/1068
867
print(four_of_clubs. repr ()) # 4 of Clubs (R)
print(four_of_clubs. str ()) # 4 of Clubs (S)
…
932/1068
868
class Card:
special_names = {1:'Ace', 11:'Jack', 12:'Queen', 13:'King'}
def init (self, suit…
933/1068
869
a = 7
if a > 5: 
print "foo"
else:
print "bar" 
print "done"
if True: 
print "true"
if…
934/1068
870
if foo:
if bar:
x = 42
¿Espacios o pestañas?
La sangría recomendada es de 4 espacios, pero…
935/1068
871
se analiza como:
<if> <foo> <:> [0]
<INDENT> <if> <bar> <:> [0, 4]
<INDENT> <x> <=> <42> [0…
936/1068
872
"This is a string"
b"This is a buffer of bytes"
import hashlib
h = hashlib.new('sha256')
h…
937/1068
873
import hashlib 
hashlib.algorithms_available
# ==> {'sha256', 'DSA-SHA', 'SHA512', 'SHA224',…
938/1068
874
import hashlib
hasher = hashlib.new('sha256') 
with open('myfile', 'r') as f:
contents = f.…
939/1068
875
salt = encrypted[0:SALT_SIZE]
derived = hashlib.pbkdf2_hmac('sha256', password, salt, 100000,…
940/1068
876
with open('pubkey.pem', 'rb') as f: 
key = RSA.importKey(f.read())
hasher = SHA256.new(messa…
941/1068
877
Nota : Los ejemplos anteriores utilizan el esquema de cifrado OPAP PKCS # 1. pycrypto también …
942/1068
878
Capítulo 180: Serialización de datos
Sintaxis
• unpickled_string = pickle.loads (cadena)
• …
943/1068
879
import json
families = (['John'], ['Mark', 'David', {'name': 'Avraham'}]) 
# Dumping it into…
944/1068
880
Consulte Pickle para obtener información detallada acerca de Pickle.
ADVERTENCIA : La documen…
945/1068
881
Capítulo 181: Serialización de datos de 
salmuera
Sintaxis
• pickle.dump (objeto, archivo, …
946/1068
882
import pickle
# An arbitrary collection of objects supported by pickle. 
data = {
'a': [1, …
947/1068
883
serialized_data = pickle.dumps(data, pickle.HIGHEST_PROTOCOL) 
# type(serialized_data) is byt…
948/1068
884
todos los valores: {'important_data': self.important_data} .
¡Elconstructornosellama!Tengaenc…
949/1068
885
python -m SimpleHTTPServer 9000
python -m http.server 9000
import sys
import BaseHTTPServer…
950/1068
886
import SimpleHTTPServer 
import SocketServer
PORT = 8000
handler = SimpleHTTPServer.SimpleH…
951/1068
887
def test(HandlerClass = SimpleHTTPRequestHandler, 
ServerClass =BaseHTTPServer.HTTPServer):
…
952/1068
888
|UDPServer| ------->|UnixDatagramServer|
+-----------+ +--------------------+
+-------------…
953/1068
889
$ curl http://localhost/
received get request%
$ curl -X POST http://localhost/
received po…
954/1068
890
from distutils.core import setup
setup(name='foo',
version='1.0', 
py_modules=['foo'],
)
…
955/1068
891
python setup.py install
greetings/
greetings/
 init .py 
hello_world.py
python greetings/…
956/1068
892
from setuptools import setup, find_packages
setup(
setup_requires=['setuptools_scm'], 
use_…
957/1068
893
python setup.py build_sphinx
initialize_options y finalize_options se ejecutarán antes y desp…
958/1068
894
2 in [2, 3]
{'0': 2, '1': 3}
Capítulo 184: Similitudes en la sintaxis, 
diferencias en el s…
959/1068
895
import math
class Vector(object): 
# instantiation
def init (self, x, y): 
self.x = x
sel…
960/1068
896
class sparselist(object): 
def init (self, size):
self.size = size 
self.data = {}
# l[ind…
961/1068
897
class adder(object):
def init (self, first): 
self.first = first
# a(...)
def call (self, …
962/1068
898
>>> x = NotAddable(1)
>>> y = Addable(2)
>>> x + x
Traceback (most recent call last): 
Fil…
963/1068
899
class A:
def init (self, a): 
self.a = a
def add (self, other): 
return self.a + other
de…
964/1068
900
Como no hay nada especial en estos métodos, muchas otras partes del lenguaje, partes de la 
b…
965/1068
901
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
host = raw_input("Server Address T…
966/1068
902
try:
#setting up socket
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
server.b…
967/1068
903
#encrypting session key and public key 
E = server_public_key.encrypt(encrypto,16)
en = eval…
968/1068
904
ideaEncrypt = IDEA.new(key, IDEA.MODE_CTR, counter=lambda : key)
eMsg = ideaEncrypt.encrypt(w…
969/1068
905
from CryptoPlus.Cipher import IDEA
#server address and port number input from admin 
host= r…
970/1068
906
import time 
import socket 
import threading 
import hashlib 
import itertools 
import sy…
971/1068
907
#public key and private key 
random_generator = Random.new().read
key =RSA.generate(1024,ran…
972/1068
908
print (msg)
print ("\n-----DECRYPTEDSESSION KEY-------")
print (en_digest)
print("\n-----HA…
973/1068
909
usage: sub <command> 
commands:
status - showstatus 
list - print list
"""
usage: sub <co…
974/1068
910
usage: sub <command> 
commands:
status - showstatus 
list - print list
import argparse 
i…
975/1068
911
argparse (formateador de ayuda personalizado)
Versión extendida de http://www.levcode.com/pyt…
976/1068
912
usage: sub <command> 
commands:
status - showstatus 
list - print list
Salida sin argument…
977/1068
913
import sys
from sys import exit
raise RuntimeError("expected 3 command line arguments")
f =…
978/1068
914
# Error messages should not go to standard output, if possible. 
print('ERROR: We have no che…
979/1068
915
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as t: 
t.write('Hello World!'…
980/1068
916
981/1068
917
import typing
T = typing.TypeVar("T")
def get_first_element(l: typing.Sequence[T]) -> T: 
"…
982/1068
918
print(two_sum(2, 1)) # result: 3
print(two_sum("a", "b")) # result: "ab"
def two_sum(a: int,…
983/1068
919
class A:
x = None # type: float
def init (self, x: float) -> None: 
"""
self should not be…
984/1068
920
x: int
print( annotations ) 
# {'x': <class 'int'>}
class C:
s: str
print(C. annotations …
985/1068
921
float_num = 10.2 #float value 
complex_num = 3.14j #complex value
long_num = 1234567L #long …
986/1068
922
tuple = (123,'hello') 
tuple1 = ('world')
print(tuple) #will output whole tuple. (123,'hello…
987/1068
923
foo = "bar"
foo[0] = "c" # Error
foo = ("bar", 1, "Hello!",) 
foo[1] = 2 # ERROR!!
foo = f…
988/1068
924
from Tkinter import * # Capitalized
from tkinter import * # Lowercase
try:
from Tkinter imp…
989/1068
925
Gerentes de geometría
Tkinter tiene tres mecanismos para la gestión de la geometría: place , …
990/1068
926
from tkinter import *
class GridExample(Frame): 
def init (self,master):
Frame. init(self,m…
991/1068
927
¡Nunca mezcle el pack y la griddentro del mismo marco! ¡Al hacerlo se producirá un 
interbloq…
992/1068
928
Capítulo 194: Trabajando alrededor del 
bloqueo global de intérpretes (GIL)
Observaciones
¿…
993/1068
929
bibliotecas de procesamiento de imágenes y las operaciones de procesamiento de números 
numpy…
994/1068
930
from threading import Thread 
import time
def countdown(n): 
while n > 0:
n -= 1
COUNT = …
995/1068
931
from threading import Thread 
import time
def countdown(n): 
while n > 0:
n -= 1
COUNT = …
996/1068
932
Es así de simple, siempre y cuando estés usando cython. Tenga en cuenta que la documentación 
…
997/1068
933
import zipfile 
filename = 'zipfile.zip'
zip = zipfile.ZipFile(filename) 
print(zip)
# <zi…
998/1068
934
with zipfile.ZipFile(filename) as zip: 
zip.printdir()
with zipfile.ZipFile(filename) as zip…
999/1068
935
import zipfile 
new_arch=zipfile.ZipFile("filename.zip",mode="w")
new_arch.write('filename.t…
1000/1068
936
plt.plot(x, y)
plt.show()
# sine function
# Plotting tutorials in Python 
# Launching a si…
1001/1068
937
# Plotting tutorials in Python 
# Enhancing a plot
import numpy as np
import matplotlib.pyp…
1002/1068
938
# Plotting tutorials in Python
# Adding Multiple plots by superimposition 
# Good for plots …
1003/1068
939
# Plotting tutorials in Python
# Adding Multiple plots by superimposition
# Good for plots s…
1004/1068
940
# Plotting tutorials in Python
# Adding Multiple plots by twin x axis
# Good for plots havin…
1005/1068
941
# replicate axes object and plot curves 
# use axes to set attributes
# Note:
# Grid for se…
1006/1068
942
# Plotting tutorials in Python
# Adding Multiple plots by twin y axis
# Good for plots havin…
1007/1068
943
fig, ax1 = plt.subplots()
# Duplicate the axes with a different x axis 
# and the same y axi…
1008/1068
944
1009/1068
945
x = (1, 2, 3)
x[0] # 1
x[1] # 2
x[2] # 3
x[3] # IndexError: tuple index out of range
Capí…
1010/1068
946
>>> t = (1, 4, 9)
>>> t[0] = 2
Traceback (most recent call last): 
File "<stdin>", line 1, …
1011/1068
947
{ (1, 2)} # ok
{ ([], {"hello"}) ) # not ok
t = 'a', 'b', 'c', 'd', 'e'
t = ('a', 'b', 'c',…
1012/1068
948
a = 1, 2, 3 # a is the tuple (1, 2, 3)
a = (1, 2, 3) # a is the tuple (1, 2, 3)
a = 1 # a is…
1013/1068
949
first, *more, last = (1, 2, 3, 4, 5) 
# first ==1
# more == [2, 3, 4]
# last == 5
colors =…
1014/1068
950
len(tuple1) 
Out: 5
max(tuple1) 
Out: 'e'
max(tuple2) 
Out: '3'
min(tuple1) 
Out: 'a'
…
1015/1068
951
tuple1 + tuple2
Out: ('a', 'b', 'c', 'd', 'e', '1', '2', '3')
Concatenación de tuplas
Usa +…
1016/1068
952
>>> u'□'.encode('utf-8') 
'\xf0\x9f\x90\x8d'
>>> b'\xf0\x9f\x90\x8d'.decode('utf-8') 
u'\U0…
1017/1068
953
type("f") == type(u"f") # True, <class 'str'> 
type(b"f") # <class 'bytes'>
type("f") == typ…
1018/1068
954
>>> print type(u"£13.55".encode('utf8'))
<type 'str'>
>>> print u"£13.55".encode('utf8') 
S…
1019/1068
955
>>> "£13.55".encode('ascii', errors='replace') 
b'?13.55'
>>> "£13.55".encode('ascii', error…
1020/1068
956
open(fn, mode='wb') # open file for writing bytes
# ERROR: cannot write string when bytes is …
1021/1068
957
import urllib
response = urllib.urlopen('http://stackoverflow.com/documentation/')
print res…
1022/1068
958
import urllib
query_parms = {'username':'stackoverflow', 'password':'me.me'} 
encoded_parms …
1023/1068
959
html = data.decode(encoding)
1024/1068
960
def func(params):
for value in params:
print ('Got value {}'.format(value))
if value == 1:
…
1025/1068
961
Capítulo 202: Uso del módulo "pip": PyPI 
Package Manager
Introducción
A veces es posible q…
1026/1068
962
import pip
command = 'install' 
parameter = 'selenium'
second_param = 'numpy' # You can giv…
1027/1068
963
Fuerza de instalación
Muchos paquetes, por ejemplo, en la versión 3.4 se ejecutarán en 3.6 mu…
1028/1068
964
def list_check(to_check, the_list): 
for item in the_list:
if to_check == item: 
return Tru…
1029/1068
965
class Deque:
def init (self): 
self.items = []
def isEmpty(self):
return self.items == []
…
1030/1068
966
Eliminar: O (n) 
Girar: O (k)
Establecer operaciones
Operación: Caso promedio (asume paráme…
1031/1068
967
del tiempo de los algoritmos.
1. Θ Notación : la notación theta limita las funciones desde ar…
1032/1068
968
import matplotlib.pyplot as plt
# Generate some data for plotting. 
x = [0, 1, 2, 3, 4, 5, 6…
1033/1068
969
import numpy as np # numpy used to create data from plotting 
import seaborn as sns # common …
1034/1068
970
# Using previously created imports and data.
# Use a dark background with no grid. 
sns.set_…
1035/1068
971
# Using previously created data and style
# Access to matplotlib commands 
import matplotlib…
1036/1068
972
MayaVI
MayaVI es una herramienta de visualización 3D para datos científicos. Utiliza el kit d…
1037/1068
973
Plotly
Plotly es una plataforma moderna para el trazado y visualización de datos. Útil para p…
1038/1068
974
import plotly.graph_objs as go 
import plotly as ply
# Create random data with numpy 
impor…
1039/1068
975
1040/1068
976
Capítulo 205: Web raspado con Python
Introducción
El raspado web es un proceso automatizado …
1041/1068
977
# For Python 2 compatibility.
from future import print_function
import lxml.html 
import re…
1042/1068
978
scrapy startproject projectName
import scrapy
class StackOverflowSpider(scrapy.Spider):
nam…
1043/1068
979
from bs4 import BeautifulSoup 
import requests
# Use the requests module to obtain a page
r…
1044/1068
980
from urllib.request import urlopen
response = urlopen('http://stackoverflow.com/questions?sor…
1045/1068
981
import asyncio
from aiohttp import ClientSession 
class EchoWebSocket(ClientSession):
URL =…
1046/1068
982
python -m pip install autobahn
from autobahn.asyncio.websocket import WebSocketServerProtocol…
1047/1068
983
'''When creating server protocol, the 
user defined class inheriting the 
WebSocketServerPro…
1048/1068
984
1049/1068
985
Creditos
S.
No Capítulos Contributors
1
Empezando con 
Python Language
A. Raza, Aaron Cr…
1050/1068
986
user2314737, user2853437, user312016, Utsav T, 
vaichidrewar, vasili111, Vin, W.Wong, weewooq…
1051/1068
987
abstracta
16 Archivos y carpetas I
/ O
Ajean, Anthony Pham, avb, Benjamin Hodgson, Bharel, …
1052/1068
988
Jadhav, tobias_k, Vlad Shcherbina, Will
26 ChemPy - paquete 
de python Biswa_9937
27 Clases…
1053/1068
989
Piersall, Conrad.Dean, Elazar, evuez, J F, James, Or East, 
pylang, RahulHP, RamenChef, Simpl…
1054/1068
990
56 Diccionario
Amir Rachum, Anthony Pham, APerson, ArtOfCode, BoppreH, 
Burhan Khalid, Chris…
1055/1068
991
RamenChef, Régis B., Sebastian Schrader, Serenity, 
Shantanu Alshi, Shrey Gupta, Simon Fraser…
1056/1068
992
79 Explotación florestal Gal Dreiman, Jörn Hees, sxnwlfkk
80 Exposiciónción Anthony Pham, int…
1057/1068
993
, Elodin, Emma, EsmaeelE, Ffisegydd, Gal Dreiman, 
ghostarbeiter, Hurkyl, J F, James, Jeffrey…
1058/1068
994
BusyAnt, Casebash, Christian Ternus, Community, 
Conrad.Dean, Daniel, Dartmouth, Esteis, Ffis…
1059/1068
995
Sharabani, SashaZd, Sayed M Ahamad, SuperBiasedMan, 
theheadofabroom, user2314737, yurib
102…
1060/1068
996
ghostarbeiter, Igor Raush, intboolstring, J F, j3485, jalanb, 
James, James Elderfield, jani,…
1061/1068
997
116 Llama a Python
desde C # Julij Jegorov
115 Listas enlazadas Nemo
117 Maldiciones básica…
1062/1068
998
Shrey Gupta, Simplans, SuperBiasedMan, theheadofabroom, 
user1349663, user2314737, Veedrac, W…
1063/1068
999
138 Módulo operador MSeifert
139 módulo pyautogui Damien, Rednivrug
140 Módulo Sqlite3 Chinm…
1064/1068
1000
los resultados.
153 Patrones de diseño Charul, denvaar, djaszczurowski
154 Perfilado J F, k…
1065/1068
1001
172 Recolección de 
basura
bogdanciobanu, Claudiu, Conrad.Dean, Elazar, FazeL, J F, 
James…
1066/1068
1002
mensajes entre el 
cliente y el servidor
187
Subcomandos CLI 
con salida de ayuda 
preci…
1067/1068
1003
202
Uso del módulo "pip": 
PyPI Package 
Manager
Zydnar
203 Velocidad de Python 
del pr…
1068/1068


  • Previous
  • Next
  • f Fullscreen
  • esc Exit Fullscreen
@ProfGastonPerez

Share

Aprende todo sobre Python

Embed code

Report Inappropriate Content on Jaunt

Choose the reason you are reporting: Aprende todo sobre Python as inappropriate to Jaunt's content team.


Swipe LEFT
to view Related

Scroll DOWN
to read doc

We, and our third-party partners, use cookies, pixels, and other technologies (“cookies”) to collect, record, and share information you provide, as well as information about your interactions with, our site for ad targeting, analytics, personalization, and site functionality purposes. By clicking Allow All, you agree to the use of tracking technologies and acknowledge our privacy practices as described in our Privacy Notice.

Cookies to automatically collect, record, and share information about your interactions with our site for analytics purposes.
Cookies used to enable advertising on our site.

Login

OR

Forgot password?

Don't have an account? Sign Up