Sei sulla pagina 1di 16

Funciones

Algoritmos y Programacin 2568364


Departamento de Ingeniera Elctrica
Facultad de Ingeniera
2017-1

Funciones Informtica I (2016-2)


Problem statement
Reutilizar un cdigo ya hecho en otro
programa ms grande:
los nombres de las variables deben ajustarse al
nuevo programa
copiar el mismo cdigo en todos los lugares
donde se necesite
si se quiere modificar el cdigo que se copi,
ser necesario modificar todas las copias

Solucin: encapsular el cdigo a


reutilizar en un subprograma o funcin
Funciones Algoritmos y Programacin 2
Functions in Python
Una funcin es un segmento de cdigo que ha sido
encapsulado con un nombre para ser fcilmente
reutilizado en diferentes partes de un programa o en
otros programas.

Una funcin que calcula el mnimo de dos nmeros


sera: nombre de datos de entrada
la funcin (parmetros formales) Inputs
def mini(x, y):
if x < y:
definicin de return x Process
una funcin dato de
else:
salida e
return y interrupcin
de la funcin Output

Funciones Algoritmos y Programacin 3


Using functions
age1
age1 == int(input('Enter
int(input('Enter age
age of
of first
first person:
person: '))
'))
weight1
weight1 == int(input('Enter
int(input('Enter weight
weight of
of first
first person:
person: '))
'))
age2 = int(input('Enter age of second person:
age2 = int(input('Enter age of second person: ')) '))
weight2
weight2 == int(input('Enter
int(input('Enter weight
weight of
of second
second person:
person: '))
'))
if
if age1
age1 << age2:
age2:
young
young == age1
age1
else:
else:
young
young == age2
age2
if
if weight1 < weight2:
weight1 < weight2:
slim
slim == weight1
weight1
else:
else:
slim
slim == weight2
weight2
print('The
print('The young
young one
one is',
is', young,
young, 'years
'years old')
old')
print('and
print('and the
the slim
slim one
one weights',
weights', slim,
slim, 'kilos')
'kilos')

def
def mini(x,
mini(x, y):
y):
if x<y:
parmetros
definicin de if x<y:
formales
return
return xx
la funcin
else:
else:
return
return yy
age1
age1 == int(input('Enter
int(input('Enter age
age of
of first
first person:
person: '))
'))
weight1
weight1 = int(input('Enter weight of first person: '))
= int(input('Enter weight of first person: '))
age2
age2 == int(input('Enter
int(input('Enter age
age of
of second
second person:
person: '))
'))
weight2
weight2 == int(input('Enter
int(input('Enter weight
weight of
of second
second person:
person: '))
'))
invocacin o llamado young = mini(age1, age2)
young = mini(age1, age2) argumentos
de la funcin slim
slim == mini(weight1,
mini(weight1, weight2)
weight2)
print('The
print('The young
young one
one is',
is', young,
young, 'years
'years old')
old')
print('and
print('and the
the slim
slim one
one weights',
weights', slim,
slim, 'kilos')
'kilos')

Funciones Algoritmos y Programacin 4


More on function arguments
def
def strIsIn(str1,
strIsIn(str1, str2,
str2, sen):
sen=True):
sen):
if
if not
not sen:
sen: parmetros con
str1
str1 == str1.lower()
str1.lower() valores por defecto
str2
str2 == str2.lower()
str2.lower()
if
if str1
str1 in
in str2:
str2:
return
return 'Yes'
'Yes'
else:
else:
return
return 'No'
'No'

s1
s1 == 'Hola'
'Hola'
s2
s2 == 'holas'
'holas'

print(strIsIn(s1,
print(strIsIn(s1, s2,
s2, False))
False)) ## imprime
imprime Yes
Yes

print(strIsIn(s1,
print(strIsIn(s1, s2,
s2, True))
True)) ## imprime
imprime No
No
argumentos asignados
print(strIsIn(s2,
print(strIsIn(s2, s1,
s1, False))
False)) por nombre

print(strIsIn(sen=False,
print(strIsIn(sen=False, str2=s1,
str2=s1, str1=s2))
str1=s2))
argumento omitido por
print(strIsIn(str2=s1,
print(strIsIn(str2=s1, str1=s2))
str1=s2)) tener valor por defecto

Funciones Algoritmos y Programacin 5


Specification of a function
def findRoot(x, power, epsilon=0.01):
''' Asume que x y epsilon son int o float, Especificacin de una funcin:
que power es int, epsilon > 0 y power >= 1 condiciones de uso de una
Retorna un dato float tal que ans**power funcin.
est dentro de una distancia epsilon de x Suposiciones: requisitos de
Si no existe tal dato, retorna None''' los argumentos
if x<0 and power%2==0: Garantas: lo que la funcin
return None garantiza hacer
low = 0.0
high = max(1.0, x)
ans = (high + low)/2.0
while abs(ans**power - x) >= epsilon: Docstring: comentario entre
if ans**power < x: comillas triples que resume la
low = ans especificacin de la funcin
else:
high = ans
ans = (high + low)/2.0
Las especificaciones de
return ans
las funciones permiten
desarrollar un programa
entre varias personas

Funciones Algoritmos y Programacin 6


Scoping
Es el mbito en el que es vlido el nombre de una
variable o funcin.

def
def f(x):
f(x):
variables yy == 11
locales a f xx == xx ++ yy
print('x
print('x =', =', x)
x)
return
return xx

variables xx == 33
globales yy == 22
zz == f(x)
f(x) ## valor
valor de
de xx usado
usado como
como argumento
argumento
print('z
print('z =',
=', z)
z)
print('x
print('x =',
=', x)
x)
print('y
print('y =',
=', y)
y)

Funciones Algoritmos y Programacin 7


Stack frames
def
def f(x):
f(x):
def
def g():
g():
xx == 'abc'
'abc'
print('x
print('x =',=', x)
x)
def
def h():
h():
zz == xx
print('z
print('z =',=', z)
z) z x

g
h
xx == xx ++ 11
print('x
print('x =', =', x)
x) h h h h h
h()
h() g g g g g

f
g()
g()
x x x x x x

z
print('x
print('x =', =', x)
x)
return
return gg
z z z z z z z z
global

xx == 33 x x x x x x x x
zz == f(x)
f(x) f f f f f f f f
print('x
print('x =',
=', x)
x)
1 2 3 4 5 6 7 8
print('z
print('z =',
=', z)
z)
z()
z()
Funciones Algoritmos y Programacin 8
Nested functions
def
def compare():
compare():
def
def mini(x,
mini(x, y):y):
if
if x<y:
x<y:
return
return xx funcin anidada
else:
else:
return
return yy
age1
age1 == int(input('Enter
int(input('Enter age
age of
of first
first person:
person: '))
'))
weight1
weight1 == int(input('Enter
int(input('Enter weight
weight of
of first
first person:
person: '))
'))
age2 = int(input('Enter age of second person:
age2 = int(input('Enter age of second person: ')) '))
weight2
weight2 == int(input('Enter
int(input('Enter weight
weight of
of second
second person:
person: '))
'))
young
young == mini(age1,
mini(age1, age2)
age2)
slim
slim == mini(weight1,
mini(weight1, weight2)
weight2)
print('The
print('The young
young one
one is',
is', young,
young, 'years
'years old')
old')
print('and the slim one weights', slim, 'kilos')
print('and the slim one weights', slim, 'kilos')

while(True):
while(True):
#print(mini(7,8))
#print(mini(7,8)) funcin desconocida en este mbito
wish
wish == input('Do
input('Do you
you want
want to
to compare
compare people?
people? ')')
if wish == 'no':
if wish == 'no':
break
break
compare()
compare()

Funciones Algoritmos y Programacin 9


Global vs local variables
def
def f1():
f1():
global
global aa
aa == aa ++ 11
bb == bb ++ 11 Error: b no ha sido inicializada
hh == kk ++ 11
global
global cc variables globales
cc == 77
dd == 23
23 variables locales
print(a,
print(a, b, b, c,
c, d)
d)
Las variables globales
a=4
a=4 hacen que los programas
b=15
b=15 sean muy difciles de
k=15
k=15 entender y depurar!
f1()
f1()
print(a,
print(a, b)
b)
print(c)
print(c)
print(d)
print(d) Error: d no existe en este mbito

Funciones Algoritmos y Programacin 10


Multiple Function Arguments
def
def suma(*args):
suma(*args):
'''Function
'''Function returns
returns the
the sum
sum of
of all
all values'''
values'''
rr == 00
## print(type(args))
print(type(args))
for
for ii inin args:
args:
rr +=
+= ii
return
return rr

print(suma(1,
print(suma(1, 2,
2, 3))
3))
print(suma(1,
print(suma(1, 2,
2, 3,
3, 4,
4, 5))
5))

Funciones Algoritmos y Programacin 11


Function redefinition
from
from time
time import
import gmtime,
gmtime, strftime
strftime

def
def showMessage(msg):
showMessage(msg):
print(msg)
print(msg)

showMessage("Ready.")
showMessage("Ready.")

def
def showMessage(msg):
showMessage(msg):
print(strftime("%H:%M:%S",
print(strftime("%H:%M:%S", gmtime()))
gmtime()))
print(msg)
print(msg)

showMessage("Processing.")
showMessage("Processing.")

Funciones Algoritmos y Programacin 12


Passing by reference or value
nn == [1,
[1, 2,
2, 3,
3, 4,
4, 5]
5]

print("Original
print("Original list:",
list:", n)
n)

def
def f(x):
f(x):
x.pop()
x.pop()
x.pop()
x.pop()
x.insert(0,
x.insert(0, 0)
0)
print("Inside
print("Inside f():",
f():", x)
x)

f(n)
f(n)

print("After
print("After function
function call:",
call:", n)
n)

Funciones Algoritmos y Programacin 13


Anonymous functions
import
import math
math

yy == lambda
lambda x:
x: x*6
x*6 ++ 33

print(y(8))
print(y(8))

zz == lambda
lambda x,y:
x,y: x**2
x**2 ++ y**2
y**2

print(z(2,3))
print(z(2,3))

Vp
Vp == 100
100
ff == 60
60
ww == 2*math.pi*60
2*math.pi*60
fi
fi == 00

f1
f1 == lambda
lambda t:
t: Vp*math.sin(w*t+fi)
Vp*math.sin(w*t+fi)

print(f1(0))
print(f1(0))
Funciones Algoritmos y Programacin 14
Anonymous functions
import
import math
math

yy == lambda
lambda x:
x: x*6
x*6 ++ 33

print(y(8))
print(y(8))

zz == lambda
lambda x,y:
x,y: x**2
x**2 ++ y**2
y**2

print(z(2,3))
print(z(2,3))

Vp
Vp == 100
100
ff == 60
60
ww == 2*math.pi*60
2*math.pi*60
fi
fi == 00

f1
f1 == lambda
lambda t:
t: Vp*math.sin(w*t+fi)
Vp*math.sin(w*t+fi)

print(f1(0))
print(f1(0))
Funciones Algoritmos y Programacin 15
Modules
main.py geom.py

from
from geom
geom import
import ** pi
pi == 3.14159
3.14159

rr == input('Ingrese
input('Ingrese el
el radio:
radio: ')
') def
def area(radio):
area(radio):
return
return pi*(radio**2)
pi*(radio**2)
rr == float(r)
float(r)
def
def perimetro(radio):
perimetro(radio):
print('pi:
print('pi: ',
', pi)
pi) return
return 2*pi*radio
2*pi*radio

print('rea:
print('rea: ',
', area(r))
area(r)) def
def sfEsfera(radio):
sfEsfera(radio):
return
return 4*pi*(radio**2)
4*pi*(radio**2)
print('permetro:
print('permetro: ',
', perimetro(r))
perimetro(r))
def
def volEsfera(radio):
volEsfera(radio):
print('superficie:
print('superficie: ',
', sfEsfera(r))
sfEsfera(r)) return
return (4/3)*pi*(radio**3)
(4/3)*pi*(radio**3)

print('volumen:
print('volumen: ',
', volEsfera(r))
volEsfera(r))

mdulos

Funciones Algoritmos y Programacin 16

Potrebbero piacerti anche