0% encontró este documento útil (0 votos)
12 vistas

Python Fundaments ExtendedVersion

El documento presenta un curso de programación en Python, abarcando desde conceptos básicos hasta programación orientada a objetos y manipulación de datos. Se discuten características del lenguaje, su historia, tipos de datos y la instalación de librerías. Además, se menciona la tipificación dinámica y la conversión de tipos en Python.

Cargado por

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

Python Fundaments ExtendedVersion

El documento presenta un curso de programación en Python, abarcando desde conceptos básicos hasta programación orientada a objetos y manipulación de datos. Se discuten características del lenguaje, su historia, tipos de datos y la instalación de librerías. Además, se menciona la tipificación dinámica y la conversión de tipos en Python.

Cargado por

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

Programación en

Python
ANTONIO VARELA
ESTEBAN VÁZQUEZ
Temario
1.Conceptos básicos de programación en Python
2.Bucles y estructuras de decisión en Python
3.Funciones y estructuras de datos en Python
4.Uso de módulos y paquetes en Python
5.Programación orientada a objetos en Python
6.Manipulación de ficheros en Python.
7.Estructura datos complejos.
8.Data Wrangling y Cleansing con Python.
Conceptos básicos de programación en
Python

Tema 1
¿ Qué es un LP ?

Definición: Un lenguaje de programación es un sistema


notacional para describir computaciones de una forma
legible tanto para la máquina como para el ser humano.

Computación
Máquina Turing, tesis de Church
Legibilidad por parte de la máquina
Legibilidad por parte del ser humano
Características

COMPILADOS:

Eficiencia
INTERPRETADOS: lanzamos el script e interprete lo traduce a lenguaje máquina. Requiere un tiempo extra para traducirlo.
(Python) Si tengo una función que no está bien pero no se usa, no salta error.

Expresividad Cantidad de operadores matemáticos que tiene el lenguaje. Python por ejemplo tiene exponentes.

Capacidad de mantenimiento Librerías, paquetes, etc. Significa buen mantenimiento.

Legibilidad Si al escribir sintaxis en código se entiende como si fuera escrito es porque es legible.

Confiabilidad
Seguridad
Simplicidad
Productividad
Abstracciones

Clases: Datos y control


Niveles: básicas, estructuradas y unitarias
Se aplica la abstracción, para eliminar los elementos que no necesitamos y quedarnos con los que sí interesan.

Listas, Sets, Tuplas, Diccionarios.

Librerías: nos abstraemos de lo que hay dentro y usamos aquello que queramos.

Abstracciones de datos:
● Básicas: tipos básicos (enteros, reales, ...)
● Estructuradas: tipos estructurados (arreglos, registros)

● Unitarias: Tipos abstractos de datos (TDAs), paquetes,

módulos, clases, componentes


Abstracciones

Abstracciones de control
Básicas: asignación, goto
Estructuradas: condicionales e iteradores
Unitarias: paquetes, módulos, hilos y tareas.
Procesos y subprocesos. Manejo de hilos.

Un lenguaje de programación es completo en Turing


siempre que tenga variables enteras y aritméticas, y que
ejecute enunciados en forma secuencial, incluyendo
enunciados de asignación, selección e iteración.
Paradigmas de programación

Imperativo
modelo de Von Neuman, cuello de botella de Von
Neuman Busca encapsular datos junto a sus actividades. Un objeto tendrá sus propiedades y podrá ejecutar

Orientado a Objetosacciones (datos y funciones). Si coche encendido apagado eso será un atributo. També tendrá sus
métodos. Si el coche se mueve debemos definir velocidad.

TDAs, encapsulación, modularidad, reutilización


Funcional
noción abstracta de función, cálculo lambda,
recursividad, listas
Lógico
Lógica simbólica, programación declarativa
Definición del lenguaje

Sintaxis (estructura)
Gramáticas libres de contexto, estructura léxica, tokens
Semántica (significado)
Lenguaje natural
Semántica operacional
Semántica denotacional
Traducción del lenguaje

Traductor es un programa que acepta otros programas


escritos en un lenguaje y:
los ejecuta directamente (interprete)
los transforma en una forma adecuada para su ejecución
(compilador).

código
fuente

El intérprete coge el código y se lo traduce al procesador.

entrada intérprete salida


Traducción

código código
fuente objeto
compilación traducción código
adicional ejecutable

Pseudointérpretes: intermedio entre interprete y compilador:


lenguajes intermedios
Operaciones de un traductor: analizador léxico (tokens),
analizador sintáctico, analizador semántico, preprocesador
Traducción

Tiempo de compilación y tiempo de ejecución


Propiedades estáticas: tiempo de compilación
Propiedades dinámicas: tiempo de ejecución Python es dinámico. Le generamos clases al objeto a medida que se está ejecutando el
código.

Recuperación de errores (compilación y ejecución)


Eficiencia y optimización (compilación o ejecución)
Historia

50
FORTRAN
60 LISP
AlGOL 60 COBOL
Simula PL/I Prolog
70 Pascal
Smalltalk
C
80 Ada ML

90 Miranda
Historia

1950 1960 1970 1980 1990

PL/I(66) Eiffel (86)


Ada(95)

Ada(83)
Cobol(58)
ENSAMBLADOR

Pascal(70)
Java(96)
Algol(60)
C(72) C++(89)
Fortran(54)
Simula(67) Smalltalk(80)

Basic(66)
Preguntas

Clasifica los siguientes lenguajes (C, Ada, C++, Java, LISP,


Prolog, Visual Basic, JavaScript, C#, PHP) en base a :
Paradigma
tipos de traductor (compilador, interprete,
pseudointérprete)
Propiedades estáticas y dinámicas
Eficiencia

Extraed conclusiones de esta clasificación


¿Qué es Python?

• Python es un lenguaje de programación interpretado


de alto nivel y multiplataforma (Windows, MacOS,
Linux). Creado por Guido van Rossum (1991).
• Es sencillo de aprender y de entender.
• Los archivos de python tienen la extensión .py
– Archivos de texto que son interpretados por el compilador.
Para ejecutar programas en Python es necesario el
intérprete de python, y el código a ejecutar.
• Python dispone de un entorno interactivo y muchos
módulos para todo tipo deaplicaciones.
Python 1
Instalación de Python

• La última versión de Python es la 3. Más seguro y más eficiente.

• Sitio oficial de descargas.


– Con ello se instala el intérprete Python, IDLE (Integrated
Development and Learning Environment), and Tkinter.
– Se recomienda incluir python en la variable de entorno
PATH
• Sitio oficial de documentación

Python 1
Instalación de librerías científicas en
Python
• Los módulos se instalan con el comando pip Python Install Package

> python -m p ip i n s t a l l - - u s e r numpy scipy m a t p l o t l i b ipython j u p y t e r pandas sympy nose

Módulos = Librerías de terceros

Python 1
Distribuciones alternativas de Python

• Existen distribuciones alternativas de Python:


• IronPython (Python running on.NET)
• Jython (Python running on the Java Virtual Machine)
• PyPy (Afast python implementation with a JIT compiler)
• Stackless Python(Branch of CPython with microthreads)
• MicroPython(Python running on micro controllers)
• IPython (provides a rich architecture for interactive
computing)

Python 20
Implementaciones alternativas de Python

• Hay paquetes que incluyen librerías especializadas:


• ActiveState ActivePython(scientific computing modules)
• pythonxy(Scientific-oriented Python Distribution)
• winpython(scientific Python distribution for Windows)
• Conceptive Python SDK (business, desktop and database)
• Enthought Canopy(for scientific computing)
• PyIMSLStudio (for numerical analysis)
• Anaconda(for data management, analysis and
visualization of large data sets)
• eGenix PyRun(portable Python runtime)
• Versión cloud:
• PythonAnywhere(run Python in the browser)
Python 21
Lenguaje de programación se puede
estructurar según tipo de dato.

Tipos de datos
Tipados: debes definir el dato que estás definiendo.
No tipado: No cal
Parcialmente tipado: si pongo el tipo de dato he de cumplirlo.

• Un tipo de dato es el conjunto de valores y el


conjunto de operaciones definidas en esos valores.
• Python tiene un gran número de tipos de datos
incorporados tales como Números (Integer, Float,
Boolean, Complex Number), String, List, Tuple, Set,
Dictionary and File.
• Otros tipos de datos de alto nivel, tales como Decimal
y Fraction, están soportados por módulosexternos.

Python 22
Definiciones

• Objetos. Todos los datos en un programa Python se


representan por objetos. Cada objeto se caracteriza
por suidentidad, tipo y valor.
• Referencias a objetos.
• Literales.
• Operadores.
• Identificadores.
• Variables.
• Expresiones.
Python 23
Palabras reservadas

• Las palabras reservadas no se pueden usar como


identificadores.

Python 24
Integers - Enteros

• Tipo de dato (int) para representar enteros o números


naturales.

– Se puede expresar enteros en hexadecimal con el prefijo


0x (o 0X); en octal con el prefijo 0o (o 0O); y en binario
con prefijo 0b (o 0B). Ejemplo: 0x1abc, 0X1ABC, 0o1776,
0b11000011.
– Adiferencia de otros lenguajes, los enteros en Python son
de tamaño ilimitado.
Python 25
Integers - Enteros

• Ejemplo
>>> 123 + 456 - 789
-210
>>> 123456789012345678901234567890 + 1
123456789012345678901234567891
>>> 1234567890123456789012345678901234567890 + 1
1234567890123456789012345678901234567891
>>> 2 * * 888 # Raise 2 t o the power o f 888
......
>>> l e n ( s t r ( 2 * * 888)) # Convert i n t e g e r t o s t r i n g and get i t s length
268 # 2 t o the power o f 888 has 268 d i g i t s
>>> type(123) # Get the type
<class ' i n t ' >
>>> h e l p ( i n t ) # Show the help menu f o r type i n t

Python 26
Floating-Point Numbers - Reales

• Tipo de dato (float) para representar números en


punto flotantes, para uso en aplicaciones científicas o
comerciales

– Para obtener el máximo valor entero usar


sys.float_info.max
– Tienen una representación IEEE de 64 bits. Típicamente
tienen 15-17 dígitos decimales de precisión
Python 27
Floating-Point Numbers - Reales

• Ejemplo
>>> 1.23 * -4e5
-492000.0
>>> t y p e ( 1 . 2 ) # Get the type
<class ' f l o a t ' >
>>> import math # Using the math module
>>> math.pi
3.141592653589793
>>> import random # Using the random module
>>> random.random() # Generate a random number i n [ 0 , 1 )
0.890839384187198

Python 28
Números complejos

• Tipo de dato (complex) para representar números


complejos de la forma a + b j
>>> x = 1 + 2 j # Assign var x t o a complex number
>>> x # Display x
(1+2j)
>>> x . r e a l # Get the r e a l p a r t
1.0
>>> x.imag # Get the imaginary p a r t
2.0
>>> t y p e ( x ) # Get type
<class ' c o mplex' >
>>> x * ( 3 + 4 j) # Mul t i p l y two compl e x numbers
(-5+10j)
>>> z = complex( 2 , - 3) # As s ign a comple x number

Python 29
Booleans

• Tipo de dato (bool) que tiene dos valores: True y


False
• El entero 0, un valor vacío (como una cadena vacía '',
"", lista vacía [], tuple vacía (), diccionario vacío {}), y
None es tratado como False; todo lo demás es
tratado como True .
• Los Booleans se comportan como enteros en
operaciones aritméticas con 1 para True y 0 para
False.

Python 30
Booleans

• Ejemplo
>>> 8 == 8 # Compare
True
>>> 8 == 9
False
>>> type(True) # Get type
<class ' b o o l ' >
>>> bool(0)
False
>>> bool(1)
True
>>> True + 3
4
>>> False + 1
1

Python 31
Otros tipos

• Otros tipos de números son proporcionados por


módulos externos, como decimal y fraction
# f l o a t s are imprecise
>>> 0.1 * 3
0.30000000000000004

# Decimal are precise


>>> import decimal # Using the decimal module
>>> x = d e c i m a l .D e c i m a l ( ' 0 .1 ' ) # Construct a Decimal o b j e c t
>>> x * 3 # Mult i p l y wi t h over l o a ded * operat o r
Decimal('0.3')
>>> t y p e ( x ) # Get type
<class 'decimal.Decimal'>

Python 32
El valor None

• Python proporciona un valor especial llamado None


que puede ser usado para inicializar un objeto (en
OOP)
>>> x = None
>>> t y p e ( x ) # Get type
<class 'NoneType'>
>>> p r i n t ( x )
None

# Use ' i s ' and ' i s n o t ' t o check f o r 'None' v a l u e .


>>> p r i n t ( x i s None)
True
>>> p r i n t ( x i s not None)
False
Python 33
Tipado dinámico y operador asignación

• Python es tipado dinámico, esto es, asocia tipos con


objetos en lugar de variables. Así, una variable no
tiene un tipo fijo y se le puede asignar un objeto de
cualquier tipo. Una variable solo proporciona una
referencia a un objeto.
• No es necesario declarar una variable. Una variable se
crea automáticamente cuando un valor es asignado la
primera vez, que enlaza el objeto a la variable. Se
puede usar la función implícita type(nombre_var) para
obtener el tipo de objeto referenciado por una variable.
Python 34
Tipado dinámico y operador asignación

• Ejemplo:
>>> x = 1 # Assign an i n t value t o create v a r i a b l e x
>>> x # Display x
1
>>> t y p e ( x ) # Get the type o f x
<class ' i n t ' >
>>> x = 1.0 # Re-assign x t o a f l o a t
>>> x
1.0
>>> t y p e ( x ) # Show the type
<class ' f l o a t ' >
>>> x = ' h e l l o ' # Re-assign x t o a string
>>> x
'hello'
>>> t y p e ( x ) # Show the type
<class ' s t r ' >
>>> x = ' 1 2 3 ' # Re-assign x t o a string (of digits)
>>> x
'123'
>>> t y p e ( x ) # Show the type
<class ' s t r ' >

Python 35
Conversión de tipo

• Se puede convertir tipos mediante las funciones


integradas int( ), float( ), str( ), bool( ), etc.
>>> x = ' 1 2 3 '
>>> t y p e ( x )
<class ' s t r ' >
>>> x = i n t ( x ) # Parse s t r t o i n t , and assign back t o x
>>> x
123
>>> t y p e ( x )
<class ' i n t ' >
>>> x = f l o a t ( x ) # Convert x from i n t t o f l o a t , and assign back t o
x
>>> x
123.0
>>> t y p e ( x )
<class ' f l o a t ' >

Python 36
Conversión de tipo
>>> x = s t r ( x ) # Convert x from f l o a t t o s t r , and assign back t o x
>>> x
'123.0'
>>> t y p e ( x )
<class ' s t r ' >
>>> l e n ( x ) # Get the length o f the s t r i n g
5
>>> x = b o o l ( x ) # Convert x from s t r t o boolean, and assign back t o x
>>> x # Non-empty s t r i n g i s converted t o True
True
>>> t y p e ( x )
<class ' b o o l ' >
>>> x = s t r ( x ) # Convert x from bool t o s t r
>>> x
'True'

Python 37
El operador asignación (=)

• En Python no es necesario declarar las variables


antes de usarlas. La asignación inicial crea la variable
y enlaza el valor a la variable
>>> x = 8 # Create a v a r i a b l e x by assigning a value
>>> x = ' H e l l o ' # Re-assign a value ( o f a d i f f e r e n t t y p e ) t o x

>>> y # Cannot access undefined (unassigned) v a r i a b l e


NameError: name ' y ' i s not defined

Python 38
del

• Se puede usar la instrucción d e l para eliminar una


variable
>>> x = 8 # Create v a r i a b l e x v i a assignment
>>> x
8
>>> d e l x # Delete v a r i a b l e x
>>> x
NameError: name ' x ' i s not defined

Python 39
Asignación por pares y en cadena

• La asignación es asociativa por la derecha


>>> a = 1 # Ordinary assignment
>>> a
1
>>> b , c , d = 123, 4 . 5 , ' H e l l o ' # assignment o f 3 v a r i a b l e s pares
>>> b
123
>>> c
4.5
>>> d
'Hello'
>>> e = f = g = 123 # Chain assignment
>>> e
123
>>> f
123
>>> g
123
Python 40
Operadores aritméticos
Operador Descripción Ejemplos
+ Addition
- Subtraction
* Multiplication
/ Float Division 1 / 2 ⇒ 0.5
(returns a float) -1 / 2 ⇒ -0.5
// Integer Division 1 // 2 ⇒ 0
(returns the floor -1 // 2 ⇒ -1
integer) 8.9 // 2.5 ⇒ 3.0
-8.9 // 2.5 ⇒ -4.0
-8.9 // -2.5 ⇒ 3.0
** Exponentiation 2 ** 5 ⇒ 32
1.2 ** 3.4 ⇒ 1.858729691979481

% Modulus (Remainder) 9 %2 ⇒ 1
-9 %2 ⇒ 1
9 %-2 ⇒ -1
-9 %-2 ⇒ -1
9.9 %2.1 ⇒ 1.5
-9.9 %2.1 ⇒ 0.6000000000000001

Python 41
Operadores de comparación

• Los operadores de comparación se aplican a enteros


y flotantes y producen un resultado booleano
Operador Descripción Ejemplo
<, <=, >, >=, ==, != Comparison 2 == 3 3 != 2
2 < 13 2 <= 2
13 > 2 3 >= 3
in, not in xin y comprueba si xestá lis = [1, 4, 3, 2, 5]
contenido en la secuencia y if 4 in lis: ….
if 4 not in lis: …
is, is not xis y esTruesi xy y hacen x= 5
referencia al mismoobjeto if (type(x) is int): …
x = 5.2
if (type(x) is not int): …

Python 42
Operadores lógicos

• Se aplican a booleans. No hay exclusive-or (xor)

Operador Descripción
and Logical AND
or Logical OR
not Logical NOT

Python 43
Operadores de bits

• Permiten operaciones a nivel de bits

Operador Descripción Ejemplo


x=0b10000
001
y=0b10001111
& bitwise AND x & y ⇒ 0b10000001
| bitwise OR x | y ⇒ 0b10001111
~ bitwise NOT (or negate) ~x ⇒ -0b10000010
^ bitwise XOR x ^ y ⇒ 0b00001110
<< bitwise Left-Shift (padded withzeros) x << 2 ⇒ 0b1000000100
>> bitwise Right-Shift (padded withzeros) x >> 2 ⇒ 0b100000

Python 44
Operadores de asignación
Operador Ejemplo Equivalente a
= x= 5 x= 5
+= x += 5 x = x +5
-= x -= 5 x =x - 5
*= x *= 5 x =x * 5
/= x /= 5 x =x / 5
%= x %=5 x = x %5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x = x &5
|= x |= 5 x =x | 5
^= x ^= 5 x =x ^ 5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
b , c , d = 123, 4 . 5 , ' H e l l o ' # asignación m u l t i p l e
Python 45
Funciones integradas

• Python contiene funciones integradas para manipular


números:
– Matemáticas: r o u n d ( ) , pow(), abs()
– Conversión de tipos: i n t ( ) , f l o a t ( ) , s t r ( ) ,
bool(), type()
– Conversión debase: h e x ( ) , b i n ( ) , o c t ( )
>>> x = 1.23456 # Test b u i l t - i n f u n c t i o n round()
>>> t y p e ( x )
<type ' f l o a t ' >
>>> round(x) # Round t o the nearest i n t e g e r
1
>>> type( r ound( x) )
<class ' i n t ' >
Python 46
Funciones integradas
>>> round(x, 1) # Round t o 1 decimal place
1.2
>>> round(x, 2) # Round t o 2 decimal places
1.23
>>> round(x, 8) # No change - not f o r f o r m a t t i n g
1.23456
>>> pow(2, 5 ) # Test other b u i l t - i n f u n c t i o n s
32
>>> a b s ( - 4 . 1 )
4.1
# Base r a d i x conversion
>>> hex(1234)
'0 x 4 d 2 '
>>> bin(254)
'0b11111110'
>>> oct(1234)
'0o2322'
>>> 0xABCD # Shown i n decimal by d e f a u l t
43981
Python 47
Funciones integradas

# L i s t b u i l t - i n functions
>>> d i r ( b u i l t i n s )
[ ' t y p e ' , 'round', 'abs', ' i n t ' , ' f l o a t ' , ' s t r ' , 'bool ', 'hex',
'bin', 'oct',......]

# Show number o f b u i l t - i n f u n c t i o n s
>>> l e n ( d i r ( b u i l t i n s ) ) # Python 3
151

# Show documentation o f b u i l t i n s module


>>> h e l p ( b u i l t i n s _ _ )

Python 48
Cadenas de caracteres - Strings

• Tipo de dato (str) para representar cadenas de


caracteres, para uso en procesado de textos.
–Se delimitan por ('...'), ("..."), ('''...'''), o("""...""")
– Python 3 usa el conjunto de caracteres Unicode
– Para especificar caracteres especiales se usan
“secuencias de escape”. Ejemplo: \t, \n, \r
– Los String son immutables, es decir, su contenido no se
puede modificar
– Para convertir números en strings se usa la función s t r ( )
– Para convertir strings a números se usa i n t ( ) o f l o a t ( )

Python 49
Ejemplo Strings
>>> s1 = ' a p p l e '
>>> s1
'apple'
>>> s2 = "orange"
>>> s2
'orange'
>>> s3 = " ' o r a n g e ' " # Escape sequence not required
>>> s3
"'orange'"
>>> s3 = " \ " o r a n g e \ " " # Escape sequence needed
>>> s3
'"orange"'

# At r i p l e - s i n g l e / d o u b l e - q u o t e d s t r i n g can span m u l t i p l e l i n e s
>>> s4 = " " " t e s t i n g
testing"""
>>> s4
'testing\ntesting'

Python 50
Funciones y operadores para cadenas de
caracteres
Función/Operador Descripción Ejemplos
s = 'Hello'
len() Length len(s) ⇒ 5
in Contain? 'ell' in s ⇒ True
'he' in s ⇒ False
+ Concatenation s + '!' ⇒ 'Hello!'
* Repetition s * 2 ⇒ 'HelloHello'
[i], [-i] Indexing to get acharacter. s[1] ⇒ 'e'
The front indexbegins s[-4] ⇒ 'e'
at 0; backindex begins at -
1 (=len()-1).

[m:n], [m:], [:n], [m:n:step] Slicing to get asubstring. s[1:3] ⇒ 'el'


From index m (included) s[1:-2] ⇒ 'el'
to n (excluded) with an s[3:] ⇒ 'lo'
optional step size. s[:-2] ⇒ 'Hel'
The default m=0, n=- s[:] ⇒ 'Hello'
1, step=1. s[0:5:2] ⇒ 'Hlo'
Python 51
Ejemplo de funciones/operadores Strings
>>> s = " H e l l o , world" # Assign a s t r i n g l i t e r a l t o the v a r i a b l e
s
>>> t y p e ( s ) # Get data type o f s
<class ' s t r ' >
>>> l e n ( s ) # Length
12
>>> ' e l l o ' i n s # The i n operator
True
# Indexing
>>> s [ 0 ] # Get character a t index 0 ; index begins a t 0
'H'
>>> s [ 1 ]
'e'
>>> s [ - 1 ] # Get Last c h a r a c t e r , same as s [ l e n ( s ) - 1 ]
'd'
>>> s [ - 2 ] # 2nd l a s t character
'l'

Python 52
Ejemplo de funciones/operadores Strings
# Slicing
>>> s [ 1 : 3 ] # Substring from index 1 ( i n c l u d e d ) t o 3 (excluded)
'el'
>>> s [ 1 : - 1 ]
' e l l o , worl'
>>> s [ : 4 ] # Same as s [ 0 : 4 ] , from the beginning
'Hell'
>>> s [ 4 : ] # Same as s [ 4 : - 1 ] , t i l l the end
' o , world'
>>> s [ : ] # E n t i r e s t r i n g ; same as s [ 0 : l e n ( s ) ]
' H e l l o , world'
# Concatenation ( + ) and Repetition ( * )
>>> s = s + " again" # Concatenate two s t r i n g s
>>> s
' H e l l o , world a g a i n '
>>> s * 3 # Repeat 3 times
' H e l l o , world againHello, world againHello, world a g a i n '
>>> s [ 0 ] = ' a ‘ # S t r i n g i s immutable
TypeError: ' s t r ' o b j e c t does not support item assignment
Python 53
Funciones específicas para cadenas de
caracteres
• La clase str proporciona varias funciones miembro.
Suponiendo que s es un objeto str:
– s.strip(), s.rstrip(), s.lstrip(): the strip() strips the leading
and trailing whitespaces. The rstrip() strips the right
(trailing) whitespaces; while lstrip() strips the left (leading)
whitespaces.
– s.upper(), s.lower(), s.isupper(), s.islower()
– s.find(s), s.index(s)
– s.startswith(s)
– s.endswith(s)
– s.split(delimiter-str), delimiter-str.join(list-of-strings)

Python 54
Conversión de tipos

• Explícita: uso de funciones i n t ( ) , f l oat( ) ,


s t r ( ) , y round()

• Implícita: Python convierte automáticamente enteros


y flotantes convenientemente.
Python 55
¿Tipo caracter?

Python no tiene un tipo de dato dedicado a caracteres.


Un caracter es un string de longitud 1. Las funciones
integradas o r d ( ) y c h a r ( ) operan sobre string 1
>>> o r d ( ' A ' ) # o r d ( c ) r e t u r n s the i n t e g e r o r d i n a l (Unicode)
65
>>> o r d ( ' 水' )
27700
# c h r ( i ) r e t u r n s a one-character s t r i n g w i t h Unicode o r d i n a l I
# 0 <= i <= 0 x 1 0 f f f f .
>>> chr(65)
'A'
>>> chr(27700)
' 水'

Python 56
Formato de Strings

Python 3 usa la función f o r m a t ( ) y { }


# Replace format f i e l d s { } by arguments i n f o r m a t ( ) i n the same
order
>>> ' | { } | { } | m o r e | ' . f o r m a t ( ' H e l l o ' , ' w o r l d ' )
'|Hello|world|more|'

# You can use p o s i t i o n a l index i n the form o f { 0 } , { 1 } , . . .


>>> ' | { 0 } | { 1 } | m o r e | ' . f o r m a t ( ' H e l l o ' , ' w o r l d ' )
'|Hello|world|more|'
>>> ' | { 1 } | { 0 } | m o r e | ' . f o r m a t ( ' H e l l o ' , ' w o r l d ' )
'|world|Hello|more|'

# You can use keyword i n s i d e { }


>>> ' | { g r e e t i n g } | { n a m e } | ' . f o r m a t ( g r e e t i n g = ' H e l l o ' , name='Peter')
'|Hello|Peter|'
Python 57
Formato de Strings
# s p e c i f y f i e l d width and alignment i n the form o f i : n o r k e y : n , #
where i p o s i t i o n a l i n d e x , key keyword, and n f i e l d w i d t h .
>>> ' | { 1 : 8 } | { 0 : 7 } | ' . f o r m a t ( ' H e l l o ' , ' P e t e r ' )
'|Peter |Hello | ' # Default l e f t - a l i g n e d
# > ( r i g h t a l i g n ) , < ( l e f t a l i g n ) , -< ( f i l l char)
>>> ' | { 1 : 8 } | { 0 : > 7 } | { 2 : - < 1 0 } | ' . f o r m a t ( ' H e l l o ' , ' P e t e r ' , ' a g a i n ' )
'|Peter | Hello|again-----|'
>>> ' | { g r e e t i n g : 8 } | { n a m e : 7 } | ' . f o r m a t ( n a m e = ' P e t e r ' , g r e e t i n g = ' H i ' )
'|Hi |Peter | '
# Format i n t using ' d ' o r ' n d ‘ , Format f l o a t using ' f ' o r ' n . m f '
>>> ' | { 0 : . 3 f } | { 1 : 6 . 2 f } | { 2 : 4 d } | ' . f o r m a t ( 1 . 2 , 3.456, 78)
' | 1 . 2 0 0 | 3.46| 7 8 | '
# With keywords
>>> ' | { a : . 3 f } | { b : 6 . 2 f } | { c : 4 d } | ' . f o r m a t ( a = 1 . 2 , b=3.456, c=78)
' | 1 . 2 0 0 | 3.46| 7 8 | '

Python 58
Formato de Strings

Se pueden usar las funciones string s t r . r j u s t ( n ) ,


s t r . l j u s t ( n ) , s t r. c e n t e r ( n ) , s t r . z f i l l ( n )
donde n es el ancho de campo
>>> ' 1 2 3 ' . r j u s t ( 5 ) # S e t t i n g f i e l d width and alignment '
123'
>>> ' 1 2 3 ' . l j u s t ( 5 )
'123 '
>>> ' 1 2 3 ' . c e n t e r ( 5 )
' 123 '
>>> ' 1 2 3 ' . z f i l l ( 5 ) # Pad w i t h leading zeros
'00123'
>>> ' 1 . 2 ' . r j u s t ( 5 ) # Floats
' 1.2'
>>> ' - 1 . 2 ' . z f i l l ( 6 )
'-001.2'
Python 59
Listas

• Python dispone de una estructura de datos potente


integrada (lista - list) para arrays dinámicos.
• Una lista es encerrada entre corchetes [ ].
• Puede contener elementos de diferentes tipos.
• Puede crecer y encogerse dinámicamente.
• Los elementos se acceden medianteíndice,
empezando por cero.
• Hay funciones integradas (ej. l en( ) , max( ) ,
m i n ( ) , sum()), yoperadores.
Python 60
Operadores para listas
Operador Descripción Ejemplos
• l s t = [ 8 , 9, 6, 2]
in Contain? 9 in lst ⇒ True
5 in lst ⇒ False
+ Concatenation lst + [5, 2]
⇒ [8, 9, 6, 2, 5, 2]
* Repetition lst * 2
⇒ [8, 9, 6, 2, 8, 9, 6, 2]
[i], [-i] Indexing to get an item. lst[1] ⇒ 9
Front index begins at 0; backindex begins at - lst[-2] ⇒ 6
1 (or len-1). lst[1] = 99 ⇒ modify an existingitem
[m:n], [m:], [:n], [m:n:step] Slicing to get asublist. lst[1:3] ⇒ [9,6]
From index m (included) to n (excluded) with an lst[1:-2] ⇒ [9]
optional step size. lst[3:] ⇒ [2]
The default m is 0, n islen-1. lst[:-2] ⇒ [8,9]
lst[:] ⇒ [8, 9, 6, 2]
lst[0:4:2] ⇒ [8,6]
newlst = lst[:] ⇒ copy the list
lst[4:] = [1, 2] ⇒ modify asub-list
del Delete one or more items del lst[1] ⇒ lst is [8, 6, 2]
(for mutable sequences only) del lst[1:] ⇒ lst is[8]
del lst[:] ⇒ lst is [] (clear all items)

Python 61
Funciones para listas
Función Descripción Ejemplos
l s t = [ 8 , 9, 6, 2]
len() Length len(lst) ⇒ 4
max(), min() Maximum and minimum value (for list of max(lst) ⇒ 9
numbers only) min(lst) ⇒ 2
sum() Sum (for list of numbers only) sum(lst) ⇒ 16
• Suponiendo que lst es un objeto list:
– lst.append(item): append the given item behind the lst and return None; same as lst[len(lst):] = [item].
– lst.extend(lst2): append the given list lst2 behind the lst and return None; same as lst[len(lst):] = lst2.
– lst.insert(index, item): insert the given item before the index and return None. Hence, lst.insert(0, item) inserts before the first item of the
lst; lst.insert(len(lst), item) inserts at the end of the lst which is the same as lst.append(item).
– lst.index(item): return the index of the first occurrence of item; or error.
– lst.remove(item): remove the first occurrence of item from the lst and return None; or error.
– lst.pop(): remove and return the last item of the lst.
– lst.pop(index): remove and return the indexed item of the lst.
– lst.clear(): remove all the items from the lst and return None; same as del lst[:].
– lst.count(item): return the occurrences of item.
– lst.reverse(): reverse the lst in place and return None.
– lst.sort(): sort the lst in place and return None.
– lst.copy(): return a copy of lst; same as lst[:].

Python 62
Tuplas

• Es similar a las listas excepto que es inmutable


(como los string).
• Consiste en una serie de elementos separados por
comas, encerrados entre paréntesis.
• Se puede convertir a listas mediante list(tupla).
• Se opera sobre tuplas (tup) con:
– funciones integradas len(tup), para tuplas de números
max(tup), min(tup), sum(tup)
– operadores como in, + y *
– funciones de tupla tup.count(item), tup.index(item), etc
Python 63
Diccionarios

• Soportan pares llave-valor (mappings). Esmutable.


• Un diccionario se encierra entre llaves { }. La llave y
el valor se separa por : con el formato
{k1:v1, k2:v2, ...}
• Adiferencia de las listas y tuplas que usan un índice
entero para acceder a los elementos, los diccionarios
se pueden indexar usando cualquier tipo llave
(número, cadena, otros tipos).

Python 64
Ejemplo - Diccionarios
>>> d c t = { ' n a m e ' : ' P e t e r ' , ' g e n d e r ' : ' m a l e ' , ' a g e ' : 2 1 }
>>> d c t
{ ' a g e ' : 21, 'name': ' P e t e r ' , ' g e n d e r ' : ' m a l e ' }
>>> d c t [ ' n a m e ' ] # Get value v i a key
'Peter'
>>> d c t [ ' a g e ' ] = 22 # Re-assign a value
>>> d c t
{ ' a g e ' : 22, 'name': ' P e t e r ' , ' g e n d e r ' : ' m a l e ' }
>>> l e n ( d c t )
3
>>> d c t [ ' e m a i l ' ] = '[email protected]' # Add new item
>>> d c t
{ ' n a m e ' : ' P e t e r ' , ' a g e ' : 22, ' e m a i l ' : '[email protected]', ' g e n d e r ' :
'male'}
>>> t y p e ( d c t )
<class ' d i c t ' >
Python 65
Funciones para diccionarios

• Las más comunes son: (dct es un objeto dict)


– dct.has_key()
– dct.items(), dct.keys(), dct.values()
– dct.clear()
– dct.copy()
– dct.get()
– dct.update(dct2): merge the given dictionary dct2 into dct.
Override the value if key exists, else, add new key-value.
– dct.pop()

Python 66
Operaciones comunes con diccionarios

Python 67
Operaciones comunes con diccionarios

Python 68
Conjuntos - set

• Es una colección de objetos sin ordenar no


duplicados. Es una colección mutable, se puede usar
add() para añadir elementos.
• Un set se especifica encerrando los elementos entre
entre llaves.
• Se puede pensar que un set es un dict de llaves sin
valor asociado.
• Python tiene operadores set: & (intersection), |
(union), - (difference), ^ (exclusive-or) y in
(pertenencia).
Python 69
Operaciones comunes con conjuntos

Python 70
Operaciones comunes con conjuntos

Nota: union, i n t e r s e c t i o n y d i ff e r e n c e devuelve nuevos conjuntos, no


modifican el conjunto al que seaplica

Python 71
Estructuras complejas

• Los contenedores son muy útiles para almacenar


colecciones de valores. Las listas y diccionarios
pueden contener cualquier dato incluyendo otros
contenedores.
• Así se puede crear un diccionario de conjuntos o
diccionario de listas

Python 72
Funciones y APIs

• Tipos de funciones:
integrada ( i n t ( ) ,
float(), str()),
standard o librería
(math.sqrt()) requiere
importar el módulo donde
se encuentra.
• API: application
programming interface

Python 73
Bucles y estructuras de decisión en Python

Tema 2
Condicionales – if - else

• Se usa cuando se requiere realizar diferentes


acciones para diferentes condiciones.
• Sintaxis general: Ejemplo:
i f test-1:
block-1
e l i f test- 2:
block-2
......
e l i f test-n:
block- n
else:
else-block
Python 75
Operadores de comparación y lógicos

• Python dispone de operadores de comparación que


devuelven un valor booleano True o False:
–< , <= , == , != , > , >=
– in, not in: Comprueba si un elemento está|no está en una
secuencia (lista, tupla, etc).
– is, is not: Comprueba si dos variables tienen la misma
referencia
• Python dispone de tres operadores lógicos (Boolean):
– and
– or
– not
Python 76
Comparación encadenada

• Python permite comparación encadenada de la forma


n1 < x <n2
>>> x = 8
>>> 1 < x < 10
True
>>> 1 < x and x < 10 # Same as above
True
>>> 10 < x < 20
False
>>> 10 > x > 1
True
>>> n o t (10 < x < 20)
True

Python 77
Comparación de secuencias

• Los operadores de comparación están sobrecargados


para aceptar secuencias (string, listas, tuplas)
>>> ' a ' < ' b '
True
>>> ' a b ' < ' a a '
False
>>> ' a ' < 'b' < ' c '
True
>>> ( 1 , 2, 3) < ( 1 , 2 , 4 )
True
>>> [ 1 , 2 , 3 ] <= [ 1 , 2 , 3 ]
True

Python 78
Forma corta de if - else

• Sintaxis:
expr-1 i f t e s t else expr-2
# Evalua expr- 1 s i t e s t es True; s i n o , evalua expr- 2

>>> x = 0
>>> p r i n t ( ' z e r o ' i f x == 0 else ' n o t z e r o ' )
zero

>>> x = - 8
>>> abs_x = x i f x > 0 else - x
>>> abs_x
8

Python 79
Ciclo while

• Instrucción que permite cálculos repetitivos sujetos a


una condición. Sintaxis general:
while t e s t :
true-block
# whi l e l oop has an opt i onal el se bl ock
while t e s t :
true-block
el se: # Run onl y i f no br eak encount er ed
else-block
• El bloque else es opcional. Se ejecuta si se sale del
ciclo sin encontrar una instrucción break.
Python 80
Ciclo while - Ejemplo

# Sum from 1 t o the given upperbound


n = int(input('Enter the upperbound: ' ) )
i = 1
sum = 0
while ( i < n ) :
sum += =
i i
+= 1
print(sum)

Python 81
Ciclo while - Ejemplo
impor t std i o
import sys
# Filename: powersoftwo.py. Accept p o s i t i v e i n t e g e r n as a
# command-line argument. Write t o standard output a t a b l e
# showing the f i r s t n powers o f two.
n = int(sys.argv[1])
power = 1
i = 0
while i <= n :
# Write the i t h power o f 2 .
p r i n t ( st r ( i ) + ' ' + st r ( power ) )
power = 2 * power
i = i + 1
# pytho n powerso f t wo.py 1
# 0 1
# 1 2

Python 82
Ciclos - for

• Sintaxis general del ciclo for - in:


# s e q u e n c e : s t r i n g , l i s t , t u p l e , d i c t i o n a r y, s e t
f o r item i n sequence:
true-block
# f or - i n l oop wi t h a el se bl ock
f o r item i n sequence:
true-block
el se: # Run onl y i f no br eak encount er ed
else-block
– Se interpreta como “para cada ítem en la secuencia...”. El
bloque else se ejecuta si el ciclo termina normalmente sin
encontrar la instrucción break.
Python 83
Ciclos - for

• Ejemplos de iteraciones sobre unasecuencia.


# S t r i n g : i t e r a t i n g through each character
>>> f o r char i n ' h e l l o ' : p r i n t ( c h a r )
h
e
l
l
o
# L i s t : i t e r a t i n g through each item
>>> f o r item i n [ 1 2 3 , 4 . 5 , ' h e l l o ' ] : p r i n t ( i t e m )
123
4.5
Hello
# Tuple: i t e r a t i n g through each item
>>> f o r item i n (123, 4 . 5 , ' h e l l o ' ) : p r i n t ( i t e m )
123
4.5
hello
Python 84
Ciclos - for
# D i c t i o n a r y : i t e r a t i n g through each key
>>> d c t = { ' a ' : 1 , 2 : ' b ' , ' c ' : ' c c ' }
>>> f o r key i n d c t : p r i n t ( k e y, ' : ' , d c t [ k e y ] )
a: 1
c : cc
2: b

# S e t : i t e r a t i n g through each item


>>> f o r item i n { ' a p p l e ' , 1 , 2 , ' a p p l e ' } : p r i n t ( i t e m )
1
2
apple

# F i l e : i t e r a t i n g through each l i n e
>>> f = o p e n ( ' t e s t . t x t ' , ' r ' )
>>> f o r l i n e i n f : p r i n t ( l i n e )
. . . E a c h l i n e o f the f i l e . . .
>>> f . c l o s e ( )

Python 85
Ciclos - for

• Iteraciones sobre una secuencia de secuencias.


# Al i s t o f 2-item t u p l e s
>>> l s t = [ ( 1 , ' a ' ) , ( 2 , ' b ' ) , ( 3 , ' c ' ) ]
# I t e r a t i n g t h r u the each o f the 2-item t u p l e s
>>> f o r i 1 , i 2 i n l s t : p r i n t ( i 1 , i 2 )
...
1 a
2 b
3 c

# Al i s t o f 3-item l i s t s
>>> l s t = [ [ 1 , 2 , 3 ] , [ ' a ' , ' b ' , ' c ' ] ]
>>> f o r i 1 , i 2 , i 3 i n l s t : p r i n t ( i 1 , i 2 , i 3 )
...
1 2 3
a b c

Python 86
Ciclos - for

• Iteraciones sobre un diccionario.


>>> d c t = { ' n a m e ' : ' P e t e r ' , ' g e n d e r ' : ' m a l e ' , ' a g e ' : 2 1 }

# I t e r a t e through the keys (as i n the above example)


>>> f o r key i n d c t : p r i n t ( k e y, ' : ' , d c t [ k e y ] )
age : 21
name : Peter
gender : male

# I t e r a t e through the key-value p a i r s


>>> f o r key, value i n d c t . i t e m s ( ) : p r i n t ( k e y, ' : ' , value)
age : 21
name : Peter
gender : male

>>> d c t . i t e m s ( ) # Return a l i s t o f key-value ( 2 - i t e m ) t u p l e s


[ ( ' g e n d e r ' , ' m a l e ' ) , ( ' a g e ' , 21), ('name', ' P e t e r ' ) ]

Python 87
Instrucción break

• break termina el ciclo y sigue en la instrucción que


sigue al ciclo.

Python 88
Instrucción continue

• continue se usa para saltar el resto del código del


ciclo y continuar con la siguiente iteración.

Python 89
Instrucciones pass, loop - else

• pass no hace nada. Sirve como marcador de una


instrucción vacía o bloque vacía.
• loop –else se ejecuta si del ciclo se sale
normalmente sin encontrar la instrucción break.

Python 90
Ciclos – for else

• Ejemplo de cláusula else enfor


# L is t a l l prim es b e tween 2 and 100
f o r number i n range(2, 101):
f o r f a c t o r i n range(2, number//2+1): # Look f o r f a c t o r
i f number % f a c t o r == 0 : # breaki f a f a c t o r found
p r i n t ( '%d i s NOT a pr i me' % numbe r )
break
e l s e: # Only i f no break encountered
p ri n t ( ' %d i s a p r i me' % number )

Python 91
Funciones y estructuras de datos en
Python

Tema 3
Funciones

• Se definen con la palabra clave def seguida por el


nombre de la función, la lista de parámetros, las
cadenas de documentación y el cuerpo de la función.
• Dentro del cuerpo de la función se puede usar la
instrucción r e t u r n para devolver unvalor.
• Sintaxis:
def fu nct ion _name( arg1 , a rg2 , . . . ) :
"""Function doc-stri ng"""
# Can be r e t r i e v e d v i a function_name.__doc
statements
return return-value
Python 93
Funciones - Ejemplos
>>> def my_square(x):
" " "Returnt he square of the g iven number" " "
return x * x

# Invoke the f u n c t i o n defined e a r l i e r


>>> my_squar e ( 8 )
64
>>> my_squar e ( 1 . 8)
3.24
>>> my_square('hello')
TypeError : c a n ' t mu lt i p l y sequence by non- i n t o f t ype
'str'
>>> my_square
<function my_square a t 0x7fa57ec54bf8>
>>> type(my_square)
<class ' f u n c t i o n ' >
Python 94
Funciones - Ejemplos
>>> my_squa r e . doc # Show f unction doc- s t r i n g
'Return the square o f thegivennumber'
>>> he l p(my_square ) # Show documen ta ion
my_square(x)
Return the square o f the given number
>>> dir(my_square) # Show a t t r i b u t e s
......

Python 95
Funciones - Ejemplos
def f i b o n ( n ) :
" " "Pr i n t t h e f i r s t n F i bonac c i number s , where
f ( n ) = f ( n - 1 ) + f ( n - 2 ) and f ( 1 ) = f ( 2 ) = 1 " " "
a, b = 1, 1
f o r count i n range(n):
p ri n t ( a , end= ' ' ) # pr i n t a space
a , b = b , a+b
print() # p r i n t a newline

fibon(20)

Python 96
Funciones - Ejemplos
def my_cube(x):
" " " ( number) - > ( number)
Retu rn t h e cube o f the gi v en number .
Examples (can beused by d o c t e s t ) :
>>> my_cube( 5 )
125
>>> my_cube(-5)
-125
>>> my_cube( 0 )
0
"""
r e t u r n x*x*x
# Test the f u n c t i o n
print(my_cube(8)) # 512
print(my_cube(-8)) # -512
print(my_cube(0)) # 0
Python 97
Parámetros de funciones

• Los argumentos inmutables (enteros, floats, strings,


tuplas) se pasan por valor. Es decir, se clona una
copia y se pasa a la función, y el original no se puede
modificar dentro de la función.
• Los argumentos mutables (listas, diccionarios, sets e
instancias de clases) se pasan por referencia. Es
decir, se pueden modificar dentro de la función.

Python 98
Parámetros de funciones con valores por
defecto
• Se puede asignar un valor por defecto a los
parámetros de funciones.
>>> def my_sum(n1, n2 = 4 , n3 = 5 ) : # n1 r e q u i r e d , n2, n3 o p t i o n a l
"""Return the sum o f a l l the arguments"""
r e t u r n n1 + n2 + n3

>>> print(my_sum(1, 2 , 3 ) )
6
>>> print(my_sum(1, 2 ) ) # n3 d e f a u l t s
8
>>> print(my_sum(1)) # n2 and n3 d e f a u l t
10
>>> print(my_sum())
TypeError: my_sum() takes a t l e a s t 1 argument ( 0 given)
>>> print(my_sum(1, 2 , 3 , 4 ) )
TypeError: my_sum() takes a t most 3 arguments ( 4 given)

Python 99
Argumentos posicionales y nominales

• Las funciones en Python permiten argumentos


posicionales y nombrados.
• Normalmente se pasan los argumentos por posición
de izquierda a derecha (posicional).
def my_sum(n1, n2 = 4 , n3 = 5 ) :
" " " Retur n t he sumo f al l the argument s " " "
r e t u r n n1 + n2 +n3
print(my_sum(n2 = 2 , n1 = 1 , n3 = 3 ) )
# Keywor d argume n ts need no t f o l l ow t h e ir pos i t i onal or der
print(my_sum(n2 = 2 , n1 = 1 ) ) # n3 d e f a u l t s
print(my_sum(n1 = 1 ) ) # n2 and n3 d e f a u l t
print(my_sum(1, n3 = 3 ) ) # n2 d e f a u l t
# p r in t ( my_sum(n2 = 2 )) # TypeError, n1 missing
Python 100
Número de argumentos posicionales
variables
• Python ofrece un número variable (arbitrario) de
argumentos. En la definición de función se puede
usar * para indicar los restantes argumentos.
def my_sum(a, * a r g s ) : # one p o s i t . a r g . & a rb i t.n u mb .o f args
"""Return the sum o f a l l the arguments (one o r more)"""
sum = a
f o r i t em i n a rgs: # args i s a tu p l e
sum += item
r e t u r n sum

print(my_sum(1)) # args is ()
p r i n t(m y_sum(1, 2 )) # args is ( 2 ,)
print(my_sum(1, 2 , 3 ) ) # args is ( 2 , 3)
p r i n t(m y_sum(1, 2 , 3 , 4 ) ) # args is ( 2 , 3, 4)
Python 101
Número de argumentos posicionales
variables
• Python permite poner *args en medio de la lista de
parámetros. En ese caso todos loas argumentos
después de *args deben pasarse por nombre clave.
def my_sum( a , * args , b) :
sum = a
f o r i t em i n a rgs:
sum += item
sum += b
r e t urn sum

print(my_sum(1, 2 , 3 , 4 ) )
#TypeError: my_sum() missing 1 required keyword-only argument: ' b '
p r i n t(m y_sum(1, 2 , 3 , 4 , b=5))

Python 102
Número de argumentos posicionales
variables
• De forma inversa cuando los argumentos ya están en
una lista/tupla, se puede usar * para desempacar la
lista/tupla como argumentos posicionalesseparados.
>>> def my_sum(a, b , c ) : r e t u r n a+b+c

>>> l s t 1 = [ 11 , 22, 33]


# my_sum() expects 3 arguments, NOT a 3-item l i s t
>>> my_sum(*lst1) # unpack the l i s t i n t o separate p o s i t . args
66

>>> l s t 2 = [ 4 4 , 55]
>>> my_sum(*lst2)
TypeEr r o r:my_sum( ) mi s s i n g 1 re qui r e d pos i t i onal a rgumen t : ' c '

Python 136
Argumentos con palabra clave **kwargs

• Para indicar parámetros con palabras claves se


puede usar ** para empaquetarlos en un diccionario.
def my_print_kwargs(**kwargs):
# Accept var i a b l e numbe r of keywor d argument s
" " " P r i n t a l l the keyword arguments"""
f o r key, val u e i n kwarg s .i t e ms ( ) : # kwargs i s a di c t i .
p r i n t ( ' % s : %s' % ( k e y, v a l u e ) )

my_print_kwargs(name='Peter', age=24)

# use* * t ounpack a di c t . i n t o i nd i v i dual keyword arguments


d i c t ={ ' k 1 ' : ' v 1 ' , ' k 2 ' : ' v 2 ' }
my_print_kwargs(**dict)
# Use * * t o unpack d i c t . i n t o separate keyword args k1=v1, k2=v2

Python 104
Argumentos variables *args y **kwargs

• Se puede usar ambos *args y **kwargs en la


definición de una función poniendo *args pimero.
def my_pri nt_al l _args(*args, **kwargs):
# Place *args before **kwargs
" " " P r int a ll po s it ional and keywor d arguments " " "
f o r item i n a r g s : # args i s a tuple
print(item)
f o r key, val u e i n kwarg s .i t e ms ( ) : #kwargs i s d ic t i onary
p r i n t ( ' % s : %s' % ( k e y, v a l u e ) )

my_pr i n t_a l l _ a rg s(' a ' , ' b ' , ' c ' , name='Pete r ' , age=24)
# Place the p o s i t i o n a l arguments before the keyword
# arguments during i nvocati on

Python 105
Valores retornados por una función

• Se puede retornar valores múltiples desde una


función Python. En realidad retorna una tupla.
>>> def my_fun():
return 1, ' a ' , ' h e l l o '

>>> x , y, z = my_fun()
>>> z
'hello'
>>> my_fun()
(1, ' a ' , 'hello')

Python 106
Funciones iter() y next()

• La función iter(iterable) devuelve un objeto iterator de


iterable y con next(iterator) para iterar a través de los
items.
>>> i = i t e r ( [ 11 , 22, 3 3 ] )
>>> n e x t ( i )
11
>>> n e x t ( i )
22
>>> n e x t ( i )
33
>>> n e x t ( i ) # Raise S t o p I t e r a t i o n exception i f no more item
Traceback (most recent c a l l l a s t ) :
F i l e " < s t d i n > " , l i n e 1 , i n <module>
StopIteration
>>> t y p e ( i )
<class ' l i s t _ i t e r a t o r ' >

Python 10
Función range()

• La función range produce una secuencia de enteros.


Formato:
– range(n) produce enteros desde 0 a n-1;
– range(m, n) produce enteros desde ma n-1;
– range(m, n, s) produce enteros desde ma n-1 en paso de
s.
f o r num i n r ange (1, 5 ) :
print(num)
#
Resul
t 12
3 4 10
Python
Función range()
# Sumfrom 1 t o the given upperbound
upperbound = i n t ( i n p u t ( ' E n t e r the upperbound: ' ) )
sum = 0
f o r number i n range(1, upperbound+1): # l i s t of 1 to n
sum += number
p r i n t ( " T h e sum i s : %d" % sum)
# Suma given l i s t
l s t = [ 9 , 8, 4, 5]
sum = 0
f o r index i n r a n g e ( l e n ( l s t ) ) : # l i s t o f 0 t o len-1
sum += l s t [ i n d e x ]
print(sum)
# Bet t er a l t e r n a t i v e o f the above
l s t = [ 9 , 8, 4, 5]
sum = 0
f o r item i n l s t : # Each item o f l s t
sum += item
print(sum)
# Use b u i l t - i n f u n c t i o n
del sum # Need t o remove the sum v a r i a b l e before using b u i l t i n f u n c t i o n sum
print(sum(lst))

Python 10
Función enumerate()

• Se puede usar la función integrada enumerate() para


obtener los índices posicionales cuando se recorre a
través deuna secuencia.
# List
>>> f o r i , v i n e n u m e r a t e ( [ ' a ' , ' b ' , ' c ' ] ) : p r i n t ( i , v)
1 a
2 b
3 c
>>> e n u m e r a t e ( [ ' a ' , ' b ' , ' c ' ] )
<enumerate o b j e c t a t 0x7ff0c6b75a50>

# Tuple
>>> f o r i , v i n e n u m e r a t e ( ( 'd ', ' e ' , ' f ' ) ) : p r i n t ( i , v)
1 d
2 e
3 f
Python 110
Función reversed()

• Se usa para iterar una secuencia en orden inverso.


>>> l s t = [ 11 , 22, 33]
>>> f o r item i n r e v e r s e d ( l s t ) : p r i n t ( i t e m , end=' ' )
33 22 11
>>> r e v e r s e d ( l s t )
< l i s t _ r e v e r s e i t e r a t o r o b j e c t a t 0x7fc4707f3828>

>>> s t r = " h e l l o "


>>> f o r c i n r e v e r s e d ( s t r ) : p r i n t ( c , e n d = ' ' )
olleh

Python 111
Secuencias múltiples y función zip()

• Para iterar sobre dos o más secuencias de forma


concurrente y emparejadas se usa la función zip.
>>> l s t 1 = [ ' a ' , ' b ' , ' c ' ]
>>> l s t 2 = [ 11 , 22, 33]
>>> f o r i 1 , i 2 i n z i p ( l s t 1 , l s t 2 ) : p r i n t ( i 1 , i 2 )
a 11
b. 22
c. 33
>>> z i p ( l s t 1 , l s t 2 ) # Return a l i s t o f t u p l e s
[ ( ' a ' , 11 ) , ( ' b ' , 2 2 ) , ( ' c ' , 3 3 ) ]

# z i p ( ) f o r more than 2 sequences


>>> tuple3 = ( 4 4 , 55)
>>> z i p ( l s t 1 , l s t 2 , t u p l e 3 )
[ ( ' a ' , 11, 4 4 ) , ( ' b ' , 22, 5 5 ) ]

Python 112
Uso de módulos y paquetes en Python

Tema 4
Módulos

• Un módulo Python es un fichero que contiene código


Python, incluyendo instrucciones, variables, funciones
y clases.
• Debe guardarse con la extensión .py
• El nombre del módulo es el nombre del fichero:
<nombre_modulo>.py
• Típicamente un módulo comienza con una cadena de
documentación (triple comilla) que se invoca con
<nombre_modulo>. doc

Python 114
Instrucción import

• Para usar un módulo en un programa se utiliza la


instrucción import
• Una vez importado, se referencia los atributos del
módulo como <nombre_modulo>.<nombre_atributo>
• Se usa import-as para asignar un nuevo nombre al
módulo para evitar conflicto de nombres en el módulo
• Se puede agrupar en el siguiente orden:
– Librería standard
– Librerías de terceros
– Librerías de aplicación local
Python 115
Ejemplo módulo e import

• Ejemplo: fichero greet.py


"""
greet

This mod u le cont a i ns t he greet i n g message ' ms g ' and


greeti ng f u n c t i o n ' g r e e t ( ) ' .
"""

msg = ' Hell o ' # Global Va r i able

def greet(name): # Function


p r i n t ( ' { } , { } ' . f o r m a t ( m s g , name))

Python 116
Ejemplo módulo e import
>>> import greet
>>> greet.greet('Peter') # <module_name>.<function_name>
H e l l o , Peter
>>> print(greet.msg) # <module_name>.<var_name>
Hello

>>> greet. doc # module's d o c - s t r i n g


'greet.py: the greet module w i t h a t t r i b u t e s msg and
greet()'
>>> greet. name # module's name
'greet'

>>> d i r ( g r ee t ) # L i s t a l l a tt r i butes def i n ed i n th e module


[ ' builtins ' , ' cached ' , ' doc ' , ' f i l e ' ,
' l oade r ' , ' name ' , ' package ' , ' spec ' ,
' g r e e t ' , 'msg']

Python 117
Ejemplo módulo e import
>>> h e lp(gr e e t ) # Show mod u le ' s name, f unct ions, data , . . .
Help on module greet:
NAME
greet
DESCRIPTION
...doc-string...
FUNCTIONS
gree t ( name)
DATA
msg = ' H e l lo '
FILE
/path/to/greet.py

>>> impo r t greet as gr # Refe r . the ' g r e e t' modu l e as ' g r '
>>> g r . greet ( ' P a u l' )
H e l l o , Paul

Python 118
Instrucción from - import

• La sintaxis es:
from <module_name> import <attr_name> # import one a t t r i b u t e
from <module_name> import <attr_name_1>, <attr_name_2>, . . . #
import selected a t t r i b u t e s
from <module_name> import * #import ALL a t t r i b u t e s (NOT recomm.)
from <module_name> import <attr_name> as <name>
# import a t t r i b u t e as the given name

• Con from –import se referencia los atributos


importados usando <attr_name> directamente.
>>> from greet import g r e e t , msg as message
>>> g r e e t ( ' P e t e r ' ) # Reference without the 'module_name'
H e l l o , Peter
>>> message
'Hello'
>>> msg
NameError: name 'msg' i s not defined
Python 119
Variable de entorno sys.path y
PYTHONPATH
• El camino de búsqueda de módulos es mantenida por
la variable Python path del módulo sys, sys.path
• sys.path es inicializada a partir de la variable de
entorno PYTHONPATH. Por defecto incluye el
directorio de trabajo en curso.

>>> import sys


>>> sys.path
[ ' ' , '/usr/lib/python3.5', '/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3.5/dist-packages', . . . ]

Python 120
Packages

• Un módulo contiene atributos (variables, funciones y


clases). Los módulos relevantes (mantenidos en el
mismo directorio) se pueden agrupar en un package.
• Python también soporta sub-packages (en sub-
directorios).
• Los packages y sub-packages son una forma de
organizar el espacio de nombres en la forma:
<pack_name>.<sub_pack_name>.<sub_sub_pack_name>.<module_name>.<attr_name>

Python 121
Plantilla de módulo individual
"""
<package_name>.<module_name>

Ad e s c r i p t i o n t o explain f u n c t i o n a l i t y o f t h i s module.
Class/Function however should not be documented here.
: a u t h o r : <author-name>
: v e r s i o n : x . y. z ( v e r i o n . r e l e a s e . m o d i f i c a t i o n )
:copyright: . . . . . .
:license: . . . . . .
"""
import <standard_library_modules>
import <third_party_library_modules>
import <application_modules>
# Define g l o b a l v a r i a b l e s
......
# Define helper f u n c t i o n s
......
# Define the e n t r y ' m a i n ' f u n c t i o n
def m a i n ( ) :
"""The main f u n c t i o n d o c - s t r i n g " " "
.......
# Run the main f u n c t i o n i f
name == ' main ' :
main()

Python 122
Packages

• Para crear un package:


– Crear un directorio y nombrarlo con el nombre del package
– Poner los módulos en el directorio
– Crear un fichero ‘ init .py’ en el directorio para marcar el
directorio como unpackage

Python 123
Ejemplo package
myapp/ # This d i r e c t o r y i s i n the ' s y s . p a t h '
|
+ mypack1/ # A d i r e c t o r y o f r e l e v a n t modules
| |
| + i n i t . p y # Mark as a package c a l l e d 'mypack1'
| + mymod1_1.py # Reference as 'mypack1.mymod1_1'
| + mymod1_2.py # Reference as 'mypack1.mymod1_2'
|
+ mypack2/ # A d i r e c t o r y o f r e l e v a n t modules
|
+ i n i t . p y # Mark as a package c a l l e d 'mypack2'
+ mymod2_1.py # Reference as 'mypack2.mymod2_1'
+ mymod2_2.py # Reference as 'mypack2.mymod2_2'

Python 124
Ejemplo package

• Si ‘myapp’ está en ‘sys.path’ se puede importar


‘mymod1_1’como:
import mypack1.mymod1_1
# Ref e r ence ' a t t r 1 _1_1' as
'mypack1.mymod1_1. a t t r1_1_1' from mypack1
import mymod1_1
# Reference ' a t t r 1 _ 1 _ 1 ' as 'mymod1_1.attr1_1_1'

Python 125
Variables locales y globales

• Los nombres creados dentro de una función son


locales a la función y están disponibles dentro de la
función solamente.
• Los nombres creados fuera de las funciones son
globales en el módulo y están disponibles dentro de
todas las funciones definidas en el módulo.

Python 126
Variables locales y globales - ejemplo

x = 'global' # x i s a g l o b a l v a r i a b l e f o r t h i s module

def myfun(arg): # arg i s a l o c a l v a r i a b l e f o r t h i s


function
y = ' l o c a l ' # y i s also a l o c a l v a r i a b l e
# Funct i o n can access b o th l oc a l and g lob a l va riab l es
print(x)
print(y)
p r i n t ( ar g )

myfun ( 'abc' )
print(x)
#print(y) # l ocal s ar e no t v i s i b l e o u ts i d e the fu n c ti on
#print(arg)

Python 127
Variables función

• Auna variable se le puede asignar un valor, una


función o un objeto.
>>> def square(n): r e t u r n n * n
>>> square( 5)
25
>>> sq = square # Assign a f u n c t i o n t o a v a r i a b l e
>>> s q (5)
25
>>> type(square)
<class ' f u n c t i o n ' >
>>> type(sq)
<class ' f u n c t i o n ' >
>>> square
<function square a t 0x7f0ba7040f28>
>>> sq
<function square a t 0x7f0ba7040f28> # same reference square
Python 128
Variables función

• Se puede asignar una invocación específica de una


función a una variable.
>>> def square(n): r e t u r n n * n

>>> sq5 = square(5) # A s p e c i f i c f u n c t i o n i nvocati on


>>> sq5
25
>>> type(sq5)
<class ' i n t ' >

Python 129
Funciones anidadas

• Se puede anidar funciones. Definir una función dentro


de una función
def o u t e r ( a ) : #Outer f u n c t i o n
p r i n t ( ' outer be g ins w it h arg = ' , a)
x = 1 # Defineal o c a l variable
def i n n e r ( b ) : # Definean i n n e r f u n c t i o n
p ri n t ( ' inn e r begins wi t h arg =%s ' % b)
y = 2
p ri n t ( ' a = %s, x = %d, y = %d' % (a , x , y ) )
p r i n t ( ' i n n e r ends')
# Ca l l inner f unct i o n d e fine d earl i e r
inner('bbb')
p r i n t ( ' o u t e r ends')
# Cal l o u ter fu n c t, whi c h i n t u r n c a ll s the inner f unct ion
outer('aaa')
Python 130
Función lambda

• Las funciones lambda son funcione anónimas o


funciones sin nombre. Se usan para definir una
función inline. Lasintaxis es:
lambda arg1, arg2, . . . : return-expression

>>> def f1 ( a , b, c) : r e t u rn a + b + c # ordi nary fu n c ti on


>>> f 1 ( 1 , 2 , 3 )
6
>>> t y p e ( f 1 )
<class ' f u n c t i o n ' >
>>> f 2 = lambda a, b , c : a + b + c # Define a Lambda f u n c t
>>> f 2 ( 1 , 2 , 3 ) # Invoke f u n c t i o n
6
>>> t y p e ( f 2 )
<class ' f u n c t i o n ' >
Python 131
Las funciones son objetos

• Las funciones son objetos, por tanto:


– Una función se puede asignar a unavariable
– Una función puede ser pasada en una función como
argumento
– Una función puede ser el valor retornado de una función

Python 132
Paso de una función como argumento de
una función
• El nombre de una función es el nombre de una
variable que se puede pasar en otra función como
argumento.
def my_add(x, y ) :
return x + y
def my_sub(x,y ) :
return x - y
def my_apply(func, x , y ) : # takes a f u n c t i o n as f i r s t arg
return func(x, y ) # Invoke the f u n c t i o n received
print(my_apply(my_add, 3 , 2 ) ) # Output: 5
print(my_apply(my_sub, 3 , 2 ) ) # Output: 1
# We can also pass an anonymous f u n c t i o n as argument
p r i n t(m y_app l y ( lambda x , y: x * y, 3 , 2 )) # Outp u t: 6
Python 133
Nombres, Espacio de nombres
(Namespace) y ámbito
• Un nombre se aplica a casi todo incluyendo una
variable, función, clase/instancia, módulo/package
• Los nombre definidos dentro de una función son
locales a ella. Los nombres definidos fuera de todas
las funciones son globales al módulo y son accesibles
por todas las funciones dentro del módulo.
• Un espacio de nombres (namespace) es una
colección de nombres.
• El ámbito se refiere a la porción del programa a partir
de la cual un nombre se puede acceder sin prefijo.
Python 134
Cada módulo tiene un Espacio de
nombres Global
• Un módulo es un fichero que contiene atributos
(variables, funciones y clases) y tiene su propio
espaciodenombres globales.
– Por ello no se puede definir dos funciones o clases con el
mismo nombre dentro de un módulo, pero sí en diferentes
módulos.
• Cuando se ejecuta el Shell interactivo, Python crea
un módulo llamado main , con su namespace
global asociado.

Python 135
Cada módulo tiene un Espacio de
nombres Global
• Cuando se importa un módulo con ‘import
<module_name>’:
– En caso de Shell interactivo, se añade <module_name> al
namespace de main
– Dentro de otro módulo se añade el nombre al namespace
del módulo donde se ha importado.
• Si se importa un atributo con ‘from <module_name>
import <attr_name>’ el <attr_name> se añade al
namespace de main , y se puede acceder al
<attr_name> directamente.
Python 136
Funciones globals(), locals() y dir()

• Se puede listar los nombres del ámbito en curso con


las funciones integradas:
– globals(): devuelve un diccionario con las variables
globales en curso
– locals(): devuelve un diccionario con las variables locales.
– dir(): devuelve una lista de los nombres locales, que es
equivalente a locals().keys()

Python 137
Modificación de variables globales dentro
de una función
• Para modificar una variable global dentro de una
función se usa la instrucción global.
x = 'global' # Global f i l e - s c o p e

def myfun():
global x # Declare x g l o b a l t o modify g l o b a l v a r i a b l e
x =
' c hange'
print(x)
myfun()
prin t(x ) # Gl obal changes

Python 138
Funciones - terminología

Python 139
Funciones – control de flujo

• import
• def
• return

Python 140
Funciones – alcance

• Las variables son locales en el bloque donde se


definen

Python 141
Funciones – código típico

Python 142
Funciones - Paso de argumentos

• Los argumentos de tipo integer, float, boolean, o


string por valor. El resto de objetos se pasan por
referencia.

Python 143
Funciones – código típico con arrays

Python 144
Funciones - recursión

• Técnica de programación utilizada en muchas


aplicaciones. Capacidad de invocar una función
desde la misma función.
import sys
# Return n !
def f a c t o r i a l ( n ) :
i f n == 1 :
return 1
return n * f a c t o r ia l( n - 1 )
def m ain( ) :
n = int(sys.argv[1])
fact = factorial(n)
print(fact)
i f name == ' main ' :
main()
# python f a c t o r i a l . p y 3
#6

Python 145
Funciones - recursión
# Imprime l o s movimientos para r esolver l a s t o r r e s de hanoi
# parametros: numero discos, t o r r e p a r t i d a , t o r r e f i n a l , t o r r e a u x i l i a r
def mover(discos, d e t o r r e , a t o r r e , auxt or r e) :
i f discos >= 1 :
mover(discos - 1 , d e t o r r e , a u x t o r r e , a t o r r e )
print("Mover disco " , discos, " de " , d e t o r r e , " a " , atorre)
mover(discos - 1 , a u x t o r r e , a t o r r e , d e t o r r e )
def main() :
mover(5, " A " , " C " , " B " )
i f name == ' main ' :
main()
# python t or r es h. py

Python 146
Funciones como objetos

• En Python cada elemento es un objeto, incluyendo


funciones.
# Fichero i n t e g . p y
# Calcula l a i n t e g r a l de Riemann de una f u n c t i o n f
def i n t e g r a t e ( f , a , b , n=1000):
t o t a l = 0.0
d t = 1.0 * ( b - a ) / n
f o r i i n range(n):
t o t a l += d t * f ( a + ( i + 0 . 5 ) * d t )
return t o t a l

Python 147
Funciones como objetos

# Fichero i n t d r i v e . p y
import funarg as f a
def square(x):
r e t u r n x*x

def m a i n ( ) :
p r i n t ( f a . i n t e g r a t e ( s q u a r e , 0 , 10)

i f name == ' main ' :


main()

Python 148
Módulos

• Un módulo contiene funciones que están


disponibles para su uso en otros programas.
• Un cliente es un programa que hace uso de
una función en un módulo.
• Pasos:
– En el cliente: import el módulo.
– En el cliente: hacer llamada a la función.
– En el módulo: colocar una prueba de cliente main().
– En el módulo: eliminar código global.
Usar if name == ' main ':
main()
– Hacer accesible el módulo para el cliente.
Python 149
Módulos

Python 150
Programación modular

• Implementaciones.
• Clientes.
• Application programming interfaces (APIs).

• Funciones privadas:
–Funciones que solo se usan en los módulos y que no se
ofrecen a los clientes. Por convención se usa un guión
bajo como primer caracter del nombre de la función.
Python 151
Programación modular

• Librerías:
–Colección de módulos relacionados. Ejemplo: NumPy,
Pygame, Matplolib, SciPy, SymPy, Ipython.
• Documentación.
>>> import stddraw
>>> help stddraw

Python 152
Assertion and Exception Handling - assert

• Instrucción assert. Se usa para probar una aserción.


– Sintaxis:
assert test, error-message

>>> x = 0
>>> asse r t x == 0 , ' x i s no t ze ro? ! ' # Asser t i o n t rue, no
output

>>> x = 1
# Assertion f a l s e , r a i s e AssertionError w i t h the message
>>> assert x == 0 , ' x i s not z e r o ? ! '
......
Asser t i onEr r o r : x i s no t zero? !

Python 153
Assertion and Exception Handling -
Exceptions
• Los errores detectados durante la ejecución se
llaman excepciones. Cuando se produce el programa
termina abruptamente.
>>> 1/0 # Divide by 0
......
Z e ro D i vi si o n E rro r: d i v i s i o n by zero
>>> zzz # Variable not defined
......
NameError: name ' z z z ' i s not defined
>>> ' 1 ' + 1 # Cannot concatenate s t r i n g and i n t
......
TypeError: Can't convert ' i n t ' o b j e c t t o s t r i m p l i c i t l y

Python 154
Assertion and Exception Handling -
Exceptions
>>> l s t = [ 0 , 1 , 2 ]
>>> l s t [ 3 ] # Index out o f range
......
IndexError: l i s t index out o f range
>>> l s t . i n d e x ( 8 ) # Item i s not i n the l i s t
......
ValueError: 8 i s not i n l i s t

>>> i n t ( ' a b c ' ) # Cannot parse t h i s s t r i n g i n t o i n t


......
ValueErr o r : i n v a l i d l i t e r a l f o r i n t ( ) w it h base 10: 'a bc '

>>> tup = ( 1 , 2, 3)
>>> t u p [ 0 ] = 11 # Tuple i s immutable
......
TypeE r ro r : ' t u p l e ' obj e c t does not suppor t i tem assign ment

Python 155
Assertion and Exception Handling –
try-except-else-finally
• Sintaxis:
try:
statements
excep t excep t i o n- 1: # Catch one excep t i on
statements
excep t (exce p t ion- 2 , except i o n- 3) : # Catch mu l t i p l e exce p t .
statements
excep t excep t i o n- 4 as var_name : # Ret r i eve the excep. i n s t
statements
except: # For ( o t h e r ) exceptions
sta tements
else:
sta tements # Run i f no excep t i o n r a i s ed
finally:
statements # Always run regardless o f whether
excep t i on r aise d
Python 156
Assertion and Exception Handling –
try-except-else-finally
• Ejemplo 1: Gestión de índice fuera de rango en
acceso a lista: ejem1_excep.py
• Ejemplo2: Validación de entrada.
>>> while True:
try:
x = i n t ( i n pu t ( ' Ente r an in teg e r : ' ) )
break
except ValueError:
p r i n t ( ' Wrong in p u t! Tr y again . . . ' ) # Repea t
Enter an i n t e g e r : abc
Wrong i nput ! Try ag a in. . .
Enter an i n t e g e r : 11.22
Wrong i nput ! Try ag a in. . .
Enter an i n t e g e r : 123
Python 157
Instrucción with-as y gestores de contexto

• La sintaxis de with-as es:


w i t h . . . as . . . :
statements
# More than one items
w i t h . . . as . . . , . . . as . . . , . . . :
statements

• Ejemplos:
# automa t i ca l l y c l ose the f i l eat the end of w i th
w i t h o p e n ( ' t e s t . l o g ' , ' r ' ) as i n f i l e :
f o r l i ne i n in f i l e:
print(line)

Python 158
Instrucción with-as y gestores de contexto

• Ejemplos:
# automa t i ca l l y c l ose the f i l eat the end of w i th
w i t h o p e n ( ' t e s t . l o g ' , ' r ' ) as i n f i l e :
f o r l i ne i n in f i l e:
print(line)

# Copy a f i l e
w i t h open(' i n . t x t ' , ' r ' ) as i n f i l e , open( ' o ut . t x t ' , 'w ' ) as
outfile:
for line in i n f i l e :
out f i l e . w ri t e ( l i n e )

Python 159
Módulos de librería standard Python de
uso común
• Python dispone de un conjunto de librerías standard.
• Para usarlas se usa ‘import <nombre_modulo>’ o
‘from <nombre_modulo> import < nombre_atributo>’
para impotar la librería completa o el atributo
seleccionado.
>>> impo r t math # i mp o r t an ext ernal modul e
>>> d i r ( m a th ) # List a l l attributes
[ ' e ' , ' p i ' , ' s i n ' , ' c os ' , ' t a n ' , ' t a n 2 ' , . . . . ]
>>> help(math)
......
>>> help(math.atan2)
......

Python 160
Módulos de librería standard Python de
uso común
>>> math.atan2(3, 0 )
1.5707963267948966
>>> math.s i n(mat h . p i / 2)
1.0
>>> math.c os(mat h . p i / 2)
6.123233995736766e-17

>>> from math import p i


>>> p i
3.141592653589793

Python 161
Módulos math y cmath

• El módulo math proporciona acceso las funciones


definidas por el lenguaje C. Los más comunes son:
– Constantes: pi, e.
– Potencia y exponente: pow(x,y), sqrt(x), exp(x), log(x), log2(x),
log10(x)
– Conversión float a int: ceil(x), floor(x), trunc(x)
– Operaciones float: fabs(), fmod()
– hypot(x,y) (=sqrt(x*x + y*y))
– Conversión entre grados y radianes: degrees(x), radians(x)
– Funciones trigonométricas: sin(x), cos(x), tan(x), acos(x), asin(x),
atan(x), atan2(x,y)
– Funciones hiperbólicas: sinh(x), cosh(x), tanh(x), asinh(x),
acosh(x), atanh(x)
Python 162
Módulo statistics

• El módulo statistics calcula las propiedades


estadísticas básicas.
>>> import s t a t i s t i c s
>>> d i r ( s t a t i s t i c s )
[ ' m e a n ' , ' m e d i a n ' , 'median_grouped', 'median_high',
'median _lo w' , ' mode ' , ' p s t dev' , ' pvarian c e ',
' s t dev' , 'variance', . . . ]
>>> h e l p ( s t a t i s t i c s )
......
>>> h e l p ( s t a t i s t i c s . p s t d e v )
......

>>> data = [ 5 , 7 , 8 , 3 , 5 , 6 , 1 , 3 ]
>>> s t a t i s t i c s . m e a n ( d a t a )
4.75

Python 163
Módulo statistics

>>> s t a t i s t i c s . m e d i a n ( d a t a )
5.0
>>> sta t i s t i c s . std e v (da t a )
2.3145502494313788
>>> s t a t i s t i c s . v a r i a n c e ( d a t a )
5.357142857142857
>>> s t a t i s t i c s . m o d e ( d a t a )
s t a ti s t i c s . S t a ti s t i c s Er r o r : no unique mode; found 2 equa l l y
common values

Python 164
Módulo random

• El módulo random se usa para generar números


pseudo random.
>>> import random
>>> dir(random)
......
>>> help(random)
......
>>> help(random.random)
......

>>> random. random() # f loa t i n [ 0 , 1 )


0.7259532743815786
>>> random. random()
0.9282534690123855

Python 165
Módulo random

• El módulo random se usa para generar números


pseudo random.
>>> random.randint(1, 6 ) # i n t i n [ 1 , 6 ]
3
>>> random.randrange(6) # From range(6), i . e . , 0 t o 5
0
>>> random. c h o ice ([ ' a pp l e ', ' orang e ' , 'b anana' ] )
'apple'

Python 166
Módulo sys

• El módulo sys (de system) proporciona parámetros y


funciones específicos de sistema. Los más usados:
– sys.exit([exit-status=0]): salir del programa.
– sys.path: Lista de rutas de búsqueda. Initializado con la
variable de entorno PYTHONPATH.
– sys.stdin, sys.stdout, sys.stderr: entrada, salida y error
estándard.
– sys.argv: Lista de argumentos en la línea de comandos

Python 167
Módulo sys

• Script test_argv.py
import sys
print(sys.argv) # Pri n t command- l i ne argument l i st
p r i n t ( l en(sys.a rgv) ) # P r i n t length o f l i s t

• Ejecución del script


$ pytho n t est_argv.py
[ ' t e s t _ a r g v. p y ' ]
1

$ python test_argv.py h e l l o 1 2 3 apple orange


[ ' t e st_ argv. p y ', ' h e ll o ' , ' 1 ' , ' 2' , ' 3 ' , 'a pp l e ', ' orang e ' ]
# l i s t of strings
7

Python 168
Módulo os

• El módulo os proporciona una interfaz con el sistema


operativo. Los atributos más usados son:
– os.m kdir ( path, mode=0777): Crea un d i r e c t o r i o
– os.mkdirs(path, mode=0777]): S i m i l a r a mkdir
– os.getcwd(): devuelve e l d i r e c t o r i o en curso
– o s . c h d i r ( p a t h ) : Cambia e l d i r e c t o r i o en curso
– os.system(command): ejecuta un commando s h e l l .
– os.getenv(varname, value=None): devuelve l a
v a r i a b l e de entorno s i e x i s t e
– os.putenv(varname, v a l u e ) : asigna la v a r i a b l e de
entorno a l v a l o r
– os.unsetenv(varname): elimina la v a r i a b l e de
entorno
Python 169
Módulo os

• Ejemplo:
>>> import os
>>> d i r ( o s ) # L i s t al l at t r i b u tes
......
>>> help(os) # Show man page
......
>>> help(os.getcwd) # Show man page f o r spec i f i c f unct i o n
......

>>> o s .g e tcwd() # Ge t curre n t worki n g d i r e c tor y


. . . c u r r e n t working d i r e c t o r y. . .
>>> o s .l i s t d i r ( ' . ' ) # L i s t conte nt s of t he curre n t d i r ec t
. . . c o n t e n t s o f c u r r e n t d i r e c t o r y. . .
>>> o s . c h d i r ( ' t e s t - p y t h o n ' ) # Change d i r e c t o r y
>>> e x e c ( o p e n ( ' h e l l o . p y ' ) . r e a d ( ) ) # Run a Python s c r i p t
>>> o s . s y s t e m ( ' l s - l ' ) # Run s h e l l command

Python 170
Módulo os

• Ejemplo:
>>> import os
>>> o s .name # Name o f OS
'posix'
>>> o s .ma k e d i rs (d i r) # Creat e sub- d ir ect ory
>>> o s . r e m o v e ( f i l e ) # Remove f i l e
>>> os.rename(oldFile, newFile) # Rename f i l e
>>> o s . l i s t d i r ( ' . ' )
# Return a l i s t o f e n t r i e s i n the given d i r e c t o r y
>>> f o r f i n sor t e d(os. l i s t d i r ( ' . ' ) ) :
print(f)

Python 171
Módulo date

• Proporciona clases para la manipulación de fechas y


tiempos
>>> import datetime
>>> d i r ( d a t e t i m e )
['MAXYEAR', ' M INYEAR', ' d a t e ' , ' da t e time' , ' datetim e_CAP I ' ,
' t i m e ' , ' ti m e d e l ta ' , 'timezone', ' t z i n f o ' , . . . ]
>>> d i r (dat etim e.d ate )
['today', . . . ]

>>> from datetime import date


>>> today = d a te .to d a y ( )
>>> today
datetim e.d at e ( 2 016, 6, 17)

Python 172
Módulo date

• Proporciona clases para la manipulación de fechas y


tiempos
>>> import datetime
>>> aday = date(2016, 5 , 1) # Con s t ru c t a da t e time.da t e i
>>> aday
datetim e.d at e ( 2 016, 5, 1 )
>>> d i f f = today - aday # Fin d the d if f between 2 d a tes
>>> d i f f
datetime.timedelta(47)
>>> d i r ( d a t e t i m e . t i m e d e l t a )
[ ' d a y s ', ' ma x ' , 'mi c r oseconds' , ' m i n ', ' resol u t i o n ',
'seconds', 'total_seconds', . . . ]
>>> d i f f . d ays
47

Python 173
Módulo time

• Se puede usar para medir el tiempo de ejecución de


un script
import time
s t a r t = time.time()

“codi g o que se desea me d i r e l t i empo aqui ”

end = t i m e . t i m e ( )
print(end - s t a r t )

Python 174
Sympy

• Sympy es una librería que permite hacer operaciones


simbólicas en lugar de con valores numéricos
• Portal Sympy
• SymPyTutorial

Python 175
Scipy

• Librería de funciones matemáticas para cálculo


numérico tales como integración y optimización
• Portal
• Tutorial

Python 176
Programación orientada a objetos en
Python

Tema 5
Programación orientada a objetos (OOP)
en Python
• Una clase es una plantilla de entidades del mismo
tipo. Una instancia es una realización particular de
una clase. Python soporta instancias de clases y
objetos.
• Un objeto contiene atributos: atributos de datos (o
variables) y comportamiento (llamados métodos).
Para acceder un atributo se usa el operador punto,
ejemplo: nombre_instancia.nombre_atributo
• Para crear una instancia de una clase se invoca el
constructor:nombre_instancia = nombre_clase(*args)
Python 178
Objetos de clase vs Objetos de instancia

• Los objetos de clase sirven como factorías para


generar objetos de instancia. Los objetos
instanciados son objetos reales creados por una
aplicación. Tienen su propio espacio de nombres.
• La instrucción class crea un objeto de clase con el
nombre de clase. Dentro de la definición de la clase
se puede crear variables de clase y métodos
mediante defs que serán compartidos por todas las
instancias

Python 179
Sintaxis de la definición de clase

• La sintaxis es:
cl a s s cl a s s_name(super cl a s s 1 , . . . ) :
"""Class doc-string"""
c l a ss_var1 = valu e1 # C lass v a r ia b les
......
def i n i t ( s e l f , arg1 , . . . ) :
"""Constructor"""
sel f . i n sta nce_var1 = arg1 # i n s t var by ass i g nment
......
def str (self):
" " " F o r p r i n t f ( ) and s t r ( ) " " "
......
def repr ( s e l f ) :
" " " F o r r e p r ( ) and i n t e r a c t i v e prompt"""
......
def met hod_name(sel f , * a rg s , **kwargs ) :
"""Method d o c - s t r i n g " " "
......
Python 180
Contructor: Self

• El primer parámetro de un constructor debe ser s e l f


• Cuando se invoca el constructor para crear un nuevo
objeto, el parámetro s e l f se asigna al objeto que
esta siendo inicializado
Referencia a l
def _ _ i n i t _ _ ( s e l f ) :
o b jeto i ni c i a l i zado
sel f . _ i t emCount = 0
sel f . _to t a l Pri ce = 0
r e g i s t e r = CashRegister()

Cuando el con t r uct o r t e r mina t h i s es


l a r e f e r e n c i a a l objeto creado
Python 181
Ejemplo

• circle.py:
from math import p i

class C i r c l e :
" " " A C ir c l e i n s tan ce models a c i r c l e w i th a r a d ius" " "
def i n i t ( s e l f , radius=1.0):
" " " C o n s tr u c to r w i t h d e f a u l t radiuso f 1 . 0 " " "
sel f . r a diu s = r a d ius# Cr e a tean i ns t va r radi us
def str (self):
" " " Retur n s t r i ng, i n v oked by p r i n t ( ) and s t r ( ) " " "
r e t u r n ' c i r c l e w i t h radius o f % . 2 f ' %s e l f . r a d i u s
def repr ( s e l f ) :
" " " Retur n s t r i ng used t o r e - creat e t h i s i n s tan ce " " "
return 'Circle(radius=%f)' % self.radius
def g e t _ a r e a ( s e l f ) :
"""Return the area o f t h i s C i r c l e i n s t a n c e " " "
return self.radius * self.radius * p i

Python 182
Ejemplo

• circle.py (cont.):
# i f ru n underPython i n t e r p r ete r , name i s ' ma i n
'. #If importedi n t o another module, name is
'circle'
i f c1 name = C i r == c l e '( 2 . 1main
) ' : # Const r u c t an in stance
print(c1) # Invoke str ()
p r i n t ( c1.get_a rea( ) )
c2 = C i r c l e ( ) # Defa ul t r a d ius
print(c2)
p r i n t ( c2.get_a rea( ) ) # I nvoke member method
c 2 .c o lor = ' r e d ' # Cre a te new a tt r i b u te v i a ass i g nment
print(c2.color)
#pri n t ( c1.colo r ) # Err o r - c1 has no at t r i b ute colo r
# Test d o c - s tr i n g s
p r i n t ( doc ) # This module
p r i n t ( Ci r c l e . doc ) # C ir c l e c l a ss
p r i n t ( Ci r c l e.g e t _ar e a . doc ) # get _ar e a ( ) me thod
p r i n t ( i s i n s t a n c e ( c 1 , C i r c l e ) ) # True
Python 183
Construcción de clase

• Para construir una instancia de una instancia se


realiza a través del constructor nombre_clase(…)
c1 = C i r c l e ( 1 . 2 )
c2 = C i r c l e ( ) # radius d e f a u l t
• Python crea un objeto Circle, luego invoca el método
init (self, radius) con self asignado a la nueva
instancia
• init () es un inicializador para crear variables de
instancia
• init() nunca devuelve un valor
• init() es opcional y se puede omitir si no hay variables
de instancia
Python 184
Clase Point y sobrecarga de operadores

• point.py modela un punto 2D con coordenadas x e y.


Se sobrecarga los operadores + y *:
" " " p o i n t . p y : p o i n t module defines the Point c l a s s " " "
class P o i n t :
" " " APoi n t mode l s a 2D poi n t x and y coor d i n ate s" " "
def i n i t ( s e l f , x=0,y=0):
" " " Const r u cto r x and y wi t h defa u l t o f ( 0,0 ) " " "
self.x = x
self.y = y
def str (self):
" " " Retur n a des c r ip t i ve st r i n g f o r t h i s i n s tan ce " " "
return ' ( % . 2 f , %.2f)' % ( s e l f . x , s e l f . y )
def add ( s e l f , r i g h t ) :
" " " Overr i d e t he '+ ' operat o r " " "
p = Point(self.x + ri g h t.x , self.y + right.y)
return p

Python 185
Clase Point y sobrecarga de operadores
def mul ( s e l f , f a c t o r ) :
" " " Overr i d e t he ' * ' operat o r " " "
s e l f . x *= f a c t o r
sel f . y *= fac t or
return s e l f
# Test
if name == ' main
': p1 = P o i n t ( )
p r i n t ( p1) # ( 0.00, 0.00 )
p1.x = 5
p1.y = 6
p r i n t ( p1 ) # ( 5.00, 6.00 )
p2 = P o i n t ( 3 , 4 )
print(p2) # (3.00, 4.00)
p r i n t ( p1 + p2) # ( 8.00, 10.0 0) Same as p1 . add ( p2 )
print(p1) # (5.00, 6.00) No change
print(p2 * 3) # (9.00, 12.00) Same as p1. mul (p2)
print(p2) # (9.00, 12.00) Changed

Python 186
Herencia

• cylinder.py un cilindro se puede derivar de un circulo


" " " c y l i n d e r. p y : which defines the Cylinder c l a s s " " "
from c i r c l e import C i r c l e # Using the C i r c l e class
class C y l i n d e r ( C i r c l e ) :
"""The Cylinder class i s a subclass o f C i r c l e " " "
def i n i t ( s e l f , radius = 1 . 0 , height = 1 . 0 ) :
"""Constructor"""
supe r ( ) . i n i t ( r a d ius) # Invoke superclass
s e l f . h e i g h t = height
def str (self):
" " " S e l f Description f o r p r i n t ( ) " " "
re t urn 'Cyl i n de r ( r a d ius=%. 2 f , h e ig h t=%.2f) '
%( s e l f . r a d i u s ,
self.height)
def get_vol ume(sel f):
" " " Retur n the volu me o f t he cy l i nder " " "
return self.get_area() * self.height

Python 187
Herencia

• cylinder.py (cont.)
if name == '
main ' : cy1 =
Cy l i n der( 1 . 1, 2 .2)
print(cy1) # i nh e r ited supe r c lass' method
print(cy1.get_area()) # Invoke i t s method
p ri n t(c y 1 .g e t_ v o l u me ()) # Default radius and height
cy2 = C y l i n d e r ( )
print(cy2)
print(cy2.get_area())
p ri n t(c y 2 .g e t_ v o l u me ())
print(dir(cy1))
p r i n t ( C y l i n d e r. g e t _ a r e a )
print(Circle.get_area)
p r in
c1 = tC ( c1i r c) l e ( 3 #. 3 Out
) p u t : ci r cle w i th r a d ius o f 3 .30
p r i n t ( i s s u b c l a s s ( C y l i n d e r , C i r c l e ) ) # True
p r i n t ( i s s u b c l a s s ( C i r c l e , C y l i n d e r ) ) # False
print(isinstance(cy1, Cylinder)) # True
Python 188
Métodos mágicos

Magic Method Invoked Via Invocation Syntax


lt (self, right) Comparison Operators self < right
gt (self, right) self > right
le (self, right) self <= right
ge (self, right) self >= right
eq (self, right) self == right
ne (self, right) self != right

add (self, right) Arithmetic Operators self + right


sub (self, right) self - right
mul (self, right) self * right
truediv (self, right) self / right
floordiv (self, right) self // right
mod (self, right) self % right
pow (self, right) self ** right

Python 189
Métodos mágicos

Magic Method Invoked Via Invocation Syntax


and (self, right) Bitwise Operators self & right
or (self, right) self | right
xor (self, right) self ^ right
invert (self) ~self
lshift (self, n) self << n
rshift (self, n) self >>n
str (self) Function call str(self), print(self)
repr (self) repr(self)
sizeof (self) sizeof(se
lf)
len (self) Sequence Operators & len(self)
contains (self, item) Functions item in self
iter (self) iter(self)
next (self) next(self)
getitem__(self, key) self[key]
setitem (self, key, value) self[key] = value
delitem__(self, key) del self[key]
Python 190
Métodos mágicos
Magic Method Invoked Via Invocation Syntax
int (self) TypeConversion Function int(self)
float (self) call float(se
bool (self) lf)
oct (self) bool(se
hex (self) lf)
oct(self)
hex(self)
init (self, *args) Constructor x = ClassName(*args)
new (cls, *args)
del (self) Operator del del x
index (self) Convert this object to an x[self]
index
radd (self, left) RHS(Reflected) addition, left + self
rsub (self, left) subtraction, etc. left - self
... ...
iadd (self, right) In-place addition, self += right
isub (self, right) subtraction, etc self -= right
... ...
Python 191
Métodos mágicos

Magic Method Invoked Via Invocation Syntax


pos (self) Unary Positive and +self
neg (self) Negative operators -self
round__(self) Function Call round(self)
floor (self) floor(self)
ceil (self) ceil(self)
trunc (self) trunc(se
lf)
getattr (self, name) Object's attributes self.name
setattr (self, name, value) self.name = value
delattr (self, name) del self.name
call (self, *args, **kwargs) Callable Object obj(*args, **kwargs);
enter (self), exit (self) Context Manager with-statement

Python 192
Números random

• Módulo stdrandom.py

Python 193
Procesado de arrays

• Módulo stdarray.py

Python 194
Estadística

• Módulo stdstats.py

Python 195
Beneficios de la programación modular

• Programas de tamaño razonable.


• Depuración.
• Reusabilidad de código.
• Mantenimiento.

Python 196
Programación orientada a objetos -
Métodos
• Un método es una función asociada a un objeto
específico.
• Se invoca utilizando el nombre del objeto seguido del
operador punto (.) seguido por el nombre del método
ylos argumentosdel mismo.

Python 197
Programación orientada a objetos –
Métodos de la clase str

Python 198
Tipo de dato definido por el usuario

• Se define un tipo Charge para partículas cargadas.


• Se usa la ley de Coulomb para el cálculo del
potencial de un punto debido a una carga V=kq/r ,
donde q es el valor de la carga, r es la distancia del
punto a la carga y k=8.99 ×109N m2/C2.
Constructor

Python 199
Convenciones sobre ficheros

• El código que define el tipo de dato definido por el


usuario Charge se coloca en un fichero del mismo
nombre(sin mayúscula) charge.py
• Un programa cliente que usa el tipo de dato Charge
seponeenel cabecerodel programa:
from charge import Charge

Python 200
Creación de objetos, llamada de métodos
y representación de String
#
# chargec l i ent.py
#
import sys
import s t d i o
from charge import Charge
# Acepta f l o a t s x e y como argumentso en l a l í n e a de comandos. Crea dos objetos
# Charge con posición y carga. Imprime e l p o t e n c i a l en ( x , y ) en l a s a l i d a estandard x =
float(sys.argv[1])
y = float(sys.argv[2])
c1 = Charge(.51, . 6 3 , 21.3)
c2 = Charge(.13, . 9 4 , 81.9)
v1 = c 1 . p o t e n t i a l A t ( x , y )
v2 = c 2 . p o t e n t i a l A t ( x , y )
s t d i o . w r i t e f ( ' p o t e n t i a l a t ( % . 2 f , %.2f) due t o \ n ' , x , y )
std i o. wri t eln ( ' + s t r(c 1) + ' and')
' ' + str(c2))
std
s t dii o.
o . wri
w r it teln
e f ((' 'i s % . 2 e \ n ' , v1+v2)
#
# python chargecl i ent.py . 2 . 5
# p o t e n t i a l a t ( 0 . 2 0 , 0.50) due t o #
21.3 a t ( 0 . 5 1 , 0.63) and
# 81.9 a t ( 0 . 1 3 , 0.94)
# i s 2.22e+12from charge import Charge

Python 201
Elementos básicos de un tipo de dato

• API

• Clase. Fichero charge.py. Palabra reservada class


• Constructor. Método especial init (), self
• Variable de instancia. _nombrevar
• Métodos. Variable de instancia self
• Funciones intrínsecas. str()
• Privacidad

Python 202
Implementación de Charge

• Encharge.py

Python 203
Clases Stopwatch, Histogram, Turtle

• En stopwatch.py

• En histogram.py

• En turtle.py

Python 204
Clase Complex

• Métodos especiales. En Python la expresión a + b se


reemplaza con la llamada del método a. mul (b)

Python 205
Métodos especiales

Python 206
Ficheros

Tema 6
Ficheros

• Python dispone de funciones integradas para


gestionar la entrada/salida desde ficheros:
– open(filename_str, mode): retorna un objeto fichero. Los
valores válidos de mode son: 'r' (read-only, default), 'w'
(write - erase all contents for existing file), 'a' (append), 'r+'
(read and write). También se puede usar 'rb', 'wb', 'ab',
'rb+' para operaciones modo binario (raw bytes).
– file.close(): Cierra el objeto file.
– file.readline(): lee una línea (up to a newline and including
the newline). Retorna una cadena vacía después end-of-
file (EOF).
Python 208
Ficheros

– file.read(): lee el fichero entero. Retorna una cadena vacía


después de end-of-file (EOF).
– file.write(str): escribe la cadena dada en el fichero.
– file.tell(): retorna la “posición en curso”. La “posición en
curso" es el número de bytes desde el inicio del fichero en
modo binario, y un número opaco en modo texto.
– file.seek(offset): asigna la “posición en curso” a offset
desde el inicio del fichero.

Python 209
Ficheros - Ejemplos
>>> f = open('test.txt', 'w') # Create (open) a f i l e f o r
write
>>> f . w r i t e ( ' a p p l e \ n ' ) # Write given s t r i n g t o f i l e
>>> f . w r i t e ( ' o r a n g e \ n ' )
>>> f . c l o s e ( ) # Close the f i l e

>>> f = open('test.txt', 'r') # Create (open) a f i l e f o r


read ( d e f a u l t )
>>> f.readline() # Read t i l l newline
'apple\n'
>>> f.readline()
'orange\n'
>>> f.readline() # Return empty s t r i n g a f t e r
end-of-file
''
>>> f . c l o s e ( )

Python 210
Ficheros - Ejemplos
>>> f = open ( ' t e s t. t x t ' , ' r ' )
>>> f . r e a d ( ) # Read ent i r e f i l e
'appl e \ norange\ n '
>>> f . c l o s e ( )
>>> f = o p e n ( ' t e s t . t x t ' , ' r ' ) # Test t e l l ( ) and seek()
>>> f . t e l l ( )
0
>>> f . r e a d ( )
'appl e \ norange\ n '
>>> f . t e l l ( )
13
>>> f . r ead( )
''
>>> f . s eek( 0) # Rewind
0
>>> f . r e a d ( )
' appl e \n o ra n g e \n '
>>> f . c l o s e ( ) Python 211
Iterando a través de ficheros

• Se puede procesar un fichero texto línea a línea


mediante un for-in-loop
w i t h open(' t e s t. t x t ' ) as f : # Aut o c l ose th e f i l e upon e x i t
for line in f :
l i ne = l i n e . r st r i p ( ) # St r i p t r a i l spaces and newl
print(line)

# Same as above
f = open ( 't e s t .t x t ' , ' r ' )
for line in f :
print(line.rstrip())
f.close()

Python 212
Iterando a través de ficheros

• Cada línea incluye un newline


>>> f = open('temp.txt', ' w ' )
>>> f.write('apple\n')
6
>>> f.write('orange\n')
7
>>> f.close()

>>> f = o p e n ( ' t e m p . t x t ' , ' r ' )


# l i ne i n c l udes a newl i n , d i s a b le p r i n t ( ) ' s defau l t newln
>>> f o r l i ne i n f : p ri n t ( l ine , end = ' ')
apple
orange
>>> f . c l o s e ( )

Python 213
Estructura datos complejos

Tema 7
Creación de lista y diccionario

• Existe una forma concisa para generar una lista


(comprehension). Sintaxis:
r e s u l t _ l i s t = [expression_with_item f o r item i n i n _ l i s t ]
# w i t h an o p t i o n a l t e s t
r e s u l t _ l i s t = [expression_with_item f o r item i n i n _ l i s t i f t e s t ]
# Sameas
result_list = [ ]
f o r item i n i n _ l i s t :
i f test:
result_list.append(item)

Python 215
Creación de lista y diccionario

• Ejemplos listas:
>>> sq = [ i t e m * item f o r item i n range(1,11)]
>>> sq
[ 1 , 4 , 9 , 16, 25, 36, 49, 64, 81, 100]

>>> x = [ 3 , 4 , 1 , 5 ]
>>> sq_x = [ i t e m * item f o r item i n x ] # no t e s t , a l l items
>>> sq_x
[ 9 , 16, 1 , 25]
>>> sq_odd = [ i t e m * item f o r item i n x i f item % 2 ! = 0 ]
>>> sq_odd
[ 9 , 1 , 25]

# Nested f o r
>>> [ ( x , y ) f o r x i n range(1,3) f o r y i n range(1,4) i f x ! = y ]
[(1, 2), (1, 3), (2, 1), (2, 3)]

Python 216
Creación de lista y diccionario

• Ejemplos diccionarios:
# Dictionary {k1:v1, k 2 : v 2 , . . . }
>>> d = { x : x * * 2 f o r x i n range(1, 5)} # Use braces f o r d i c t i o n a r y
>>> d
{ 1 : 1 , 2 : 4 , 3 : 9 , 4 : 16}

# Set { v 1 , v 2 , . . . }
>>> s = { i f o r i i n ' h e l l o ' i f i not i n ' a e i o u ' } # Use braces
>>> s
{'h', ' l ' }

Python 217
Ciclos – patrones

Python 218
Ciclos anidados

Python 219
Ciclos anidados

Python 220
Listas

• Es una estructura de datos que almacena una


secuencia de objetos, normalmente del mismo tipo.
• El acceso a los elementos de la lista se basa en
índices encerrados por corchetes. En una lista
bidimensional se realiza con un par de índices.
• El índice del primer elemento es 0
• Las formas de procesar arrays en Python son:
– Tipo de dato implícito Python.
– Uso del módulo Python numpy.
– Uso del módulo stdarray.
Python 221
Listas - ejemplo
x = [ 0 . 3 0 , 0 . 6 0 , 0 .1 0 ]
y = [ 0 . 5 0 , 0 . 1 0 , 0 .4 0 ]
t o t a l = 0.0
f o r i i n r ange(len ( x ) ) :
t o t a l += x [ i ] * y [ i ]

Python 222
Operaciones y funciones comunes con
Listas

Python 223
Operaciones y funciones comunes con
Listas

Python 224
Métodos comunes con Listas

Python 225
Matriz con Listas - lectura
def lee_matriz(M):
#Dato de l a dimensi ó n de l a ma t r i z ,
print('Lectura Matriz')
m = i nt(i nput(' N umero de f i l a s ' ) )
n = in t ( i n p u t ( 'Numero de c o lumnas ' ) )
#Creacion matriz nula en invocacion
# M= []
f o r i i n range(m):
M.append ( [ 0 ] * n )
# l e c tu r a deelementos
f o r i i n ra nge(m):
f o r j i n range(n):
M [ i] [ j ] = f l o a t ( i nput ( ' I n gresa elemento\
({0},{1}): '.format(i,j)))
Python 226
Matriz con Listas - output

def imp_matriz(M):
#imprime matriz
p r i n t ( ' \ nMa t r i z ' )
m = len(M)
n = len(M[0])
f o r i i n range(m):
f o r j i n range(n):
p r i n t ( M [ i] [ j ] , end= ' \ t ' )
print('')

Python 227
Example Problem:
Simple Statistics
Many programs deal with large collections of similar information.
Words in a document
Students in a course
Data from an experiment
Customers of a business
Graphics objects drawn on the screen
Cards in a deck

228
Sample Problem:
Simple Statistics
Let’s review some code we wrote in chapter 8:
# average4.py
# A program to average a set of numbers
# Illustrates sentinel loop using empty string as sentinel
def main():
sum = 0.0
count = 0
xStr = raw_input("Enter a number (<Enter> to quit) >> ")
while xStr != "":
x = eval(xStr)
sum = sum + x
count = count + 1
xStr = raw_input("Enter a number (<Enter> to quit) >> ")
print "\nThe average of the numbers is", sum / count
main()

229
Sample Problem:
Simple Statistics
This program allows the user to enter a sequence of
numbers, but the program itself doesn’t keep track of
the numbers that were entered – it only keeps a
running total.
Suppose we want to extend the program to compute
not only the mean, but also the median and standard
deviation.

230
Sample Problem:
Simple Statistics
The median is the data value that splits the data into equal-sized parts.
For the data 2, 4, 6, 9, 13, the median is 6, since there are two values greater than 6 and
two values that are smaller.
One way to determine the median is to store all the numbers, sort them, and identify the
middle value.

231
Sample Problem:
Simple Statistics
The standard deviation is a measure of how spread out the
data is relative to the mean.
If the data is tightly clustered around the mean, then the
standard deviation is small. If the data is more spread out,
the standard deviation is larger.
The standard deviation is a yardstick to measure/express
how exceptional the data is.

232
Sample Problem:
Simple Statistics

The standard deviation is


å( x - x )
2

s= i

n -1
Here is the mean, represents the ith data value and n
is the number ofxdata values. xi
The expression is the square of the “deviation” of an
individual item from the mean.
( x - xi )
2

233
Sample Problem:
Simple Statistics
The numerator is the sum of these squared “deviations” across all the data.
Suppose our data was 2, 4, 6, 9, and 13.
The mean is 6.8
The numerator of the standard deviation is

( 6.8 - 2 ) + ( 6.8 - 4 ) + ( 6.8 - 6 ) + ( 6.8 - 9 ) + ( 6.8 - 13)


2 2 2 2 2
= 149.6
149.6
s= = 37.4 = 6.11
5 -1
234
Sample Problem:
Simple Statistics
As you can see, calculating the standard deviation not only requires the mean (which can’t
be calculated until all the data is entered), but also each individual data element!
We need some way to remember these values as they are entered.

235
Applying Lists
We need a way to store and manipulate an entire collection of numbers.
We can’t just use a bunch of variables, because we don’t know many numbers there will
be.
What do we need? Some way of combining an entire collection of values into one object.

236
Lists and Arrays

Python lists are ordered sequences of items. For instance,


a sequence of n numbers might be called S:
S = s0, s1, s2, s3, …, sn-1
Specific values in the sequence can be referenced using subscripts.
By using numbers as subscripts, mathematicians can succinctly
summarize computations over items in a sequence using subscript
variables.

n -1

ås
i =0
i

237
Lists and Arrays
Suppose the sequence is stored in a variable s. We could write a loop to calculate the sum
of the items in the sequence like this:
sum = 0
for i in range(n):
sum = sum + s[i]
Almost all computer languages have a sequence structure like this, sometimes called an
array.

238
Lists and Arrays
A list or array is a sequence of items where the entire
sequence is referred to by a single name (i.e. s) and
individual items can be selected by indexing (i.e. s[i]).
In other programming languages, arrays are generally a
fixed size, meaning that when you create the array, you
have to specify how many items it can hold.
Arrays are generally also homogeneous, meaning they can
hold only one data type.

239
Lists and Arrays
Python lists are dynamic. They can grow and shrink on demand.
Python lists are also heterogeneous, a single list can hold arbitrary data types.
Python lists are mutable sequences of arbitrary objects.

240
List Operations

Operator Meaning
<seq> + <seq> Concatenation
<seq> * <int-expr> Repetition
<seq>[] Indexing
len(<seq>) Length
<seq>[:] Slicing
for <var> in <seq>: Iteration
<expr> in <seq> Membership (Boolean)
241
List Operations
Except for the membership check, we’ve used these operations before on strings.
The membership operation can be used to see if a certain value appears anywhere in a
sequence.
>>> lst = [1,2,3,4]
>>> 3 in lst
True

242
List Operations

The summing example from earlier can be written like this:


sum = 0
for x in s:
sum = sum + x
Unlike strings, lists are mutable:
>>> lst = [1,2,3,4]
>>> lst[3]
4
>>> lst[3] = "Hello“
>>> lst
[1, 2, 3, 'Hello']
>>> lst[2] = 7
>>> lst
[1, 2, 7, 'Hello']

243
List Operations
A list of identical items can be created using the repetition operator. This command
produces a list containing 50 zeroes:
zeroes = [0] * 50

244
List Operations
Lists are often built up one piece at a time using append.
nums = []
x = input('Enter a number: ')
while x >= 0:
nums.append(x)
x = input('Enter a number: ')
Here, nums is being used as an accumulator, starting out empty, and each time through
the loop a new value is tacked on.

245
List Operations

Method Meaning

<list>.append(x) Add element x to end of list.

<list>.sort() Sort (order) the list. A comparison function may be passed as a


parameter.
<list>.reverse() Reverse the list.

<list>.index(x) Returns index of first occurrence of x.

<list>.insert(i, x) Insert x into list at index i.

<list>.count(x) Returns the number of occurrences of x in list.

<list>.remove(x) Deletes the first occurrence of x in list.

<list>.pop(i) Deletes the ith element of the list and returns its value.

246
List Operations
>>> lst = [3, 1, 4, 1, 5, 9]
>>> lst.append(2)
>>> lst
[3, 1, 4, 1, 5, 9, 2]
>>> lst.sort()
>>> lst
[1, 1, 2, 3, 4, 5, 9]
>>> lst.reverse()
>>> lst
[9, 5, 4, 3, 2, 1, 1]
>>> lst.index(4)
2
>>> lst.insert(4, "Hello")
>>> lst
[9, 5, 4, 3, 'Hello', 2, 1, 1]
>>> lst.count(1)s
2
>>> lst.remove(1)
>>> lst
[9, 5, 4, 3, 'Hello', 2, 1]
>>> lst.pop(3)
3
>>> lst
[9, 5, 4, 'Hello', 2, 1]

247
List Operations
Most of these methods don’t return a value – they change the contents of the list in some
way.
Lists can grow by appending new items, and shrink when items are deleted. Individual
items or entire slices can be removed from a list using the del operator.

248
List Operations
>>> myList=[34, 26, 0, 10]
>>> del myList[1]
>>> myList
[34, 0, 10]
>>> del myList[1:3]
>>> myList
[34]
del isn’t a list method, but a built-in operation that can be used on list items.

249
List Operations
Basic list principles
A list is a sequence of items stored as a single object.
Items in a list can be accessed by indexing, and sublists can be accessed by slicing.
Lists are mutable; individual items or entire slices can be replaced through assignment
statements.

250
List Operations

Lists support a number of convenient and frequently used methods.


Lists will grow and shrink as needed.

251
Statistics with Lists
One way we can solve our statistics problem is to store the data in lists.
We could then write a series of functions that take a list of numbers and calculates the
mean, standard deviation, and median.
Let’s rewrite our earlier program to use lists to find the mean.

252
Statistics with Lists

Let’s write a function called getNumbers that gets numbers from the user.
We’ll implement the sentinel loop to get the numbers.
An initially empty list is used as an accumulator to collect the numbers.
The list is returned once all values have been entered.

253
Statistics with Lists

def getNumbers():
nums = [] # start with an empty list
# sentinel loop to get numbers
xStr = raw_input("Enter a number (<Enter> to quit) >> ")
while xStr != "":
x = eval(xStr)
nums.append(x) # add this value to the list
xStr = raw_input("Enter a number (<Enter> to quit) >> ")
return nums

Using this code, we can get a list of numbers from the user with a single line of code:
data = getNumbers()

254
Statistics with Lists
Now we need a function that will calculate the mean of the numbers in a list.
Input: a list of numbers
Output: the mean of the input list
def mean(nums):
sum = 0.0
for num in nums:
sum = sum + num
return sum / len(nums)

255
Statistics with Lists
The next function to tackle is the standard deviation.
In order to determine the standard deviation, we need to know the mean.
Should we recalculate the mean inside of stdDev?
Should the mean be passed as a parameter to stdDev?

256
Statistics with Lists
Recalculating the mean inside of stdDev is inefficient if the data set is large.
Since our program is outputting both the mean and the standard deviation, let’s compute
the mean and pass it to stdDev as a parameter.

257
Statistics with Lists
def stdDev(nums, xbar):
sumDevSq = 0.0
for num in nums:
dev = xbar - num
sumDevSq = sumDevSq + dev * dev
return sqrt(sumDevSq/(len(nums)-1))
The summation from the formula is accomplished with a
loop and accumulator.
sumDevSq stores the running sum of the squares of the
deviations.

258
Statistics with Lists
We don’t have a formula to calculate the median. We’ll
need to come up with an algorithm to pick out the middle
value.
First, we need to arrange the numbers in ascending order.
Second, the middle value in the list is the median.
If the list has an even length, the median is the average of
the middle two values.

259
Statistics with Lists
Pseudocode -
sort the numbers into ascending order
if the size of the data is odd:
median = the middle value
else:
median = the average of the two middle values
return median

260
Statistics with Lists
def median(nums):
nums.sort()
size = len(nums)
midPos = size / 2
if size % 2 == 0:
median = (nums[midPos] + nums[midPos-1]) / 2.0
else:
median = nums[midPos]
return median

261
Statistics with Lists
With these functions, the main program is pretty simple!
def main():
print 'This program computes mean, median and standard deviation.‘

data = getNumbers()
xbar = mean(data)
std = stdDev(data, xbar)
med = median(data)

print '\nThe mean is', xbar


print 'The standard deviation is', std
print 'The median is', med

262
Statistics with Lists
Statistical analysis routines might come in handy some time, so let’s add the capability to
use this code as a module by adding:
if __name__ == '__main__': main()

263
Lists of Objects
All of the list examples we’ve looked at so far have involved simple data types like numbers
and strings.
We can also use lists to store more complex data types, like our student information from
chapter ten.

264
Lists of Objects
Our grade processing program read through a file of student grade information and then
printed out information about the student with the highest GPA.
A common operation on data like this is to sort it, perhaps alphabetically, perhaps by
credit-hours, or even by GPA.

265
Lists of Objects
Let’s write a program that sorts students according to GPA using our Sutdent class from
the last chapter.
Get the name of the input file from the user
Read student information into a list
Sort the list by GPA
Get the name of the output file from the user
Write the student information from the list into a file

266
Lists of Objects

Let’s begin with the file processing. The following code


reads through the data file and creates a list of students.
def readStudents(filename):
infile = open(filename, 'r')
students = []
for line in infile:
students.append(makeStudent(line))
infile.close()
return students
We’re using the makeStudent from the gpa program,
so we’ll need to remember to import it.

267
Lists of Objects

Let’s also write a function to write the list of students back


to a file.
Each line should contain three pieces of information,
separated by tabs: name, credit hours, and quality points.
def writeStudents(students, filename):
# students is a list of Student objects
outfile = open(filename, 'w')
for s in students:
outfile.write("%s\t%f\t%f\n" %
(s.getName(),s.getHours(),s.getQPoints()))
outfile.close()

268
Lists of Objects

Using the functions readStudents and


writeStudents, we can convert our data file into
a list of students and then write them back to a file.
All we need to do now is sort the records by GPA.
In the statistics program, we used the sort method
to sort a list of numbers. How does Python sort lists
of objects?

269
Lists of Objects
Python compares items in a list using the built-in function cmp.
cmp takes two parameters and returns -1 if the first comes before the second, 0 if
they’re equal, and 1 if the first comes after the second.

270
Lists of objects
>>> cmp(1,2)
-1
>>> cmp(2,1)
1
>>> cmp("a","b")
-1
>>> cmp(1,1.0)
0
>>> cmp("a",5)
1
For types that aren’t directly comparable, the standard
ordering uses rules like “numbers always comes before
strings.”

271
Lists of Objects

To make sorting work with our objects, we need to tell


sort how the objects should be compared.
We do this by writing our own custom cmp-like function
and then tell sort to use it when sorting.
To sort by GPA, we need a routine that will take two
students as parameters and then returns -1, 0, or 1.

272
Lists of Objects
We can use the built-in cmp function.
def cmpGPA(s1, s2):
return cmp(s1.gpa(), s2.gpa()
We can now sort the data by calling sort with the appropriate comparison function
(cmpGPA) as a parameter.
data.sort(cmpGPA)

273
Lists of Objects
data.sort(cmpGPA)
Notice that we didn’t put ()’s after the function call cmpGPA.
This is because we don’t want to call cmpGPA, but rather, we want to send cmpGPA to the
sort method to use as a comparator.

274
Lists of Objects

# gpasort.py def cmpGPA(s1, s2):


# A program to sort student information into GPA order. return cmp(s1.gpa(), s2.gpa())
def main():
from gpa import Student, makeStudent print "This program sorts student grade information by
GPA"
def readStudents(filename): filename = raw_input("Enter the name of the data file: ")
infile = open(filename, 'r') data = readStudents(filename)
students = [] data.sort(cmpGPA)
for line in infile: filename = raw_input("Enter a name for the output file: ")
students.append(makeStudent(line)) writeStudents(data, filename)
infile.close() print "The data has been written to", filename
return students
if __name__ == '__main__':
def writeStudents(students, filename): main()
outfile = open(filename, 'w')
for s in students:
outfile.write("%s\t%f\t%f\n" %
(s.getName(), s.getHours(),
s.getQPoints()))
outfile.close()

275
Designing with
Lists and Classes
In the dieView class from chapter ten, each object keeps track of seven circles
representing the position of pips on the face of the die.
Previously, we used specific instance variables to keep track of each, pip1, pip2, pip3,

276
Designing with
Lists and Classes
What happens if we try to store the circle objects using a
list?
In the previous program, the pips were created like this:
self.pip1 = self.__makePip(cx, cy)
__makePip is a local method of the DieView class that
creates a circle centered at the position given by its
parameters.

277
Designing with
Lists and Classes
One approach is to start with an empty list of pips and build up the list one pip at a time.
pips = []
pips.append(self.__makePip(cx-offset,cy-offset)
pips.append(self.__makePip(cx-offset,cy)

self.pips = pips

278
Designing with
Lists and Classes
An even more straightforward approach is to create the
list directly.
self.pips = [self.__makePip(cx-offset,cy-offset),
self.__makePip(cx-offset,cy),

self.__makePip(cx+offset,cy+offset)
]
Python is smart enough to know that this object is
continued over a number of lines, and waits for the ‘]’.
Listing objects like this, one per line, makes it much easier
to read.

279
Designing with
Lists and Classes
Putting our pips into a list makes many actions simpler to perform.
To blank out the die by setting all the pips to the background color:
for pip in self.pips:
pip.setFill(self.background)
This cut our previous code from seven lines to two!

280
Designing with
Lists and Classes

We can turn the pips back on using the pips list. Our original code looked like this:
self.pip1.setFill(self.foreground)
self.pip4.setFill(self.foreground)
self.pip7.setFill(self.foreground)
Into this:
self.pips[0].setFill(self.foreground)
self.pips[3].setFill(self.foreground)
self.pips[6].setFill(self.foreground)

281
Designing with
Lists and Classes
Here’s an even easier way to access the same methods:
for i in [0,3,6]:
self.pips[i].setFill(self.foreground)
We can take advantage of this approach by keeping a list of which pips to activate!
Loop through pips and turn them all off
Determine the list of pip indexes to turn on
Loop through the list of indexes - turn on those pips

282
Designing with
Lists and Classes
for pip in self.pips:
self.pip.setFill(self.background)
if value == 1:
on = [3]
elif value == 2:
on = [0,6]
elif value == 3:
on = [0,3,6]
elif value == 4:
on = [0,2,4,6]
elif value == 5:
on = [0,2,3,4,6]
else:
on = [0,1,2,3,4,5,6]
for i in on:
self.pips[i].setFill(self.foreground)

283
Designing with
Lists and Classes
We can do even better!
The correct set of pips is determined by value. We can
make this process table-driven instead.
We can use a list where each item on the list is itself a list
of pip indexes.
For example, the item in position 3 should be the list
[0,3,6] since these are the pips that must be turned
on to show a value of 3.

284
Designing with
Lists and Classes
Here’s the table-driven code:
onTable = [ [], [3], [2,4], [2,3,4], [0,2,4,6],
[0,2,3,4,6], [0,1,2,4,5,6] ]

for pip in self.pips:


self.pip.setFill(self.background)

on = onTable[value]
for i in on:
self.pips[i].setFill(self.foreground)

285
Designing with
Lists and Classes
onTable = [ [], [3], [2,4], [2,3,4], [0,2,4,6], [0,2,3,4,6], [0,1,2,4,5,6] ]

for pip in self.pips:


self.pip.setFill(self.background)

on = onTable[value]
for i in on:
self.pips[i].setFill(self.foreground)

The table is padded with ‘[]’ in the 0 position, since it


shouldn’t ever be used.
The onTable will remain unchanged through the life of a
dieView, so it would make sense to store this table in
the constructor and save it in an instance variable.

286
Designing with
Lists and Classes

# dieview2.py # Create 7 circles for standard pip locations


# A widget for displaying the value of a die. self.pips = [ self.__makePip(cx-offset, cy-offset),
# This version uses lists to simplify keeping track of self.__makePip(cx-offset, cy),
pips. self.__makePip(cx-offset, cy+offset),
self.__makePip(cx, cy),
class DieView: self.__makePip(cx+offset, cy-offset),
""" DieView is a widget that displays a graphical self.__makePip(cx+offset, cy),
representation self.__makePip(cx+offset, cy+offset) ]
of a standard six-sided die."""
# Create a table for which pips are on for each value
def __init__(self, win, center, size): self.onTable = [ [], [3], [2,4], [2,3,4],
"""Create a view of a die, e.g.: [0,2,4,6], [0,2,3,4,6], [0,1,2,4,5,6] ]
d1 = GDie(myWin, Point(40,50), 20)
creates a die centered at (40,50) having sides self.setValue(1)
of length 20."""
def __makePip(self, x, y):
# first define some standard values """Internal helper method to draw a pip at (x,y)"""
self.win = win pip = Circle(Point(x,y), self.psize)
self.background = "white" # color of die face pip.setFill(self.background)
self.foreground = "black" # color of the pips pip.setOutline(self.background)
self.psize = 0.1 * size # radius of each pip pip.draw(self.win)
hsize = size / 2.0 # half of size return pip
offset = 0.6 * hsize # distance from center to
outer pips def setValue(self, value):
""" Set this die to display value."""
# create a square for the face # Turn all the pips off
cx, cy = center.getX(), center.getY() for pip in self.pips:
p1 = Point(cx-hsize, cy-hsize) pip.setFill(self.background)
p2 = Point(cx+hsize, cy+hsize)
rect = Rectangle(p1,p2) # Turn the appropriate pips back on
rect.draw(win) for i in self.onTable[value]:
rect.setFill(self.background) self.pips[i].setFill(self.foreground)

287
Designing with
Lists and Classes
Lastly, this example showcases the advantages of
encapsulation.
We have improved the implementation of the dieView class,
but we have not changed the set of methods it supports.
We can substitute this new version of the class without having to
modify any other code!
Encapsulation allows us to build complex software systems as a
set of “pluggable modules.”

288

También podría gustarte