Python Fundaments ExtendedVersion
Python Fundaments ExtendedVersion
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 ?
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.
Legibilidad Si al escribir sintaxis en código se entiende como si fuera escrito es porque es legible.
Confiabilidad
Seguridad
Simplicidad
Productividad
Abstracciones
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)
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.
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.
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
código
fuente
código código
fuente objeto
compilación traducción código
adicional ejecutable
50
FORTRAN
60 LISP
AlGOL 60 COBOL
Simula PL/I Prolog
70 Pascal
Smalltalk
C
80 Ada ML
90 Miranda
Historia
Ada(83)
Cobol(58)
ENSAMBLADOR
Pascal(70)
Java(96)
Algol(60)
C(72) C++(89)
Fortran(54)
Simula(67) Smalltalk(80)
Basic(66)
Preguntas
Python 1
Instalación de librerías científicas en
Python
• Los módulos se instalan con el comando pip Python Install Package
Python 1
Distribuciones alternativas de Python
Python 20
Implementaciones alternativas de Python
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.
Python 22
Definiciones
Python 24
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
• 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
Python 29
Booleans
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
Python 32
El valor None
• 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
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 (=)
Python 38
del
Python 39
Asignación por pares y en cadena
% 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
Python 42
Operadores lógicos
Operador Descripción
and Logical AND
or Logical OR
not Logical NOT
Python 43
Operadores de bits
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
# 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
Python 48
Cadenas de caracteres - Strings
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).
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
Python 56
Formato de Strings
Python 58
Formato de Strings
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
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
Python 66
Operaciones comunes con diccionarios
Python 67
Operaciones comunes con diccionarios
Python 68
Conjuntos - set
Python 70
Operaciones comunes con conjuntos
Python 71
Estructuras complejas
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
Python 77
Comparación de secuencias
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
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
# 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
# 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
Python 87
Instrucción break
Python 88
Instrucción continue
Python 89
Instrucciones pass, loop - else
Python 90
Ciclos – for else
Python 91
Funciones y estructuras de datos en
Python
Tema 3
Funciones
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
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
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 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
my_print_kwargs(name='Peter', age=24)
Python 104
Argumentos variables *args y **kwargs
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
>>> x , y, z = my_fun()
>>> z
'hello'
>>> my_fun()
(1, ' a ' , 'hello')
Python 106
Funciones iter() y next()
Python 10
Función range()
Python 10
Función enumerate()
# 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()
Python 111
Secuencias múltiples y función zip()
Python 112
Uso de módulos y paquetes en Python
Tema 4
Módulos
Python 114
Instrucción import
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
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
Python 120
Packages
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
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
Python 125
Variables locales y globales
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
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
Python 129
Funciones anidadas
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()
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
Python 141
Funciones – código típico
Python 142
Funciones - Paso de argumentos
Python 143
Funciones – código típico con arrays
Python 144
Funciones - recursión
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
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)
Python 148
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
>>> 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
>>> 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
• 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
Python 161
Módulos math y cmath
>>> 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
Python 165
Módulo random
Python 166
Módulo sys
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
Python 168
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
......
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
Python 172
Módulo date
Python 173
Módulo time
end = t i m e . t i m e ( )
print(end - s t a r t )
Python 174
Sympy
Python 175
Scipy
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
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
• 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
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
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
Python 189
Métodos mágicos
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
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
Python 199
Convenciones sobre ficheros
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
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
Python 205
Métodos especiales
Python 206
Ficheros
Tema 6
Ficheros
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
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
# 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
Python 213
Estructura datos complejos
Tema 7
Creación de lista y diccionario
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
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
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
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
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
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>.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
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)
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
267
Lists of Objects
268
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
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
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] ]
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] ]
on = onTable[value]
for i in on:
self.pips[i].setFill(self.foreground)
286
Designing with
Lists and Classes
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