Función
Una función es un código reutilizable. Nosotros usamos ese código.
def function(parameters):
instructions
return value
Ejemplo
Un ejemplo de una función:#!/usr/bin/python
def f(x):
return x*x
print(f(3))
Resultado:
9
Esa función tiene un parámetro, x. El valor de retorno no es siempre necesario.
Función con mas parámetros.
Es posible usar mas parámetros. Es posible usar variables en el código bloque:#!/usr/bin/python
def f(x,y):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)
print 'x * y = ' + str(x*y)
print(f(3,2))
Resultado:
You called f(x,y) with the value x = 3 and y = 2 x * y = 6
Función en una función
Es posible usar una función en una función.#!/usr/bin/python
def highFive():
return 5
def f(x,y):
z = highFive() # we get the variable contents from highFive()
return x+y+z # returns x+y+z. z is reachable becaue it is defined above
result = f(3,2)
print(result)
Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser, no install needed.
Practice Python with interactive exercises