3. Funciones

3.1. Módulos

Un módulo contiene «programas» que resuelven problemas particulares.

import <modulo>
from <modulo> import <identificador>
from <modulo>.<modulo> import <identificador>

3.1.1. Módulo math

>>> import math
>>> x = 16
>>> y = x ** 2
>>> z = math.sqrt(y)
>>> z
16.0
>>> math.pow(x, 2)
256.0
>>> math.gcd(16, 20)  # python >= 3.5
4

3.2. Funciones

Una función es una secuencia de enunciados que regresan un valor.

>>> type(42)
<class 'int'>

La expresión entre paréntesis se llama argumento.

Las funciones toman un argumento y regresan un valor.

>>> print('hola')
hola

Ejemplos de funciones:

>>> abs(-9)
9
>>> abs(3.3)
3.3
>>> abs(-7) + abs(3.3)
10.3
>>> pow(2, 4)
16
>>> import math
>>> math.pow(2,4)
16.0
>> int(34.6)
34
>>> int(-4.2)
-4
>>> int('34')
34
>>> int('ad')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'ad'
>>> float(21)
21.0
>>> round(3.8)
4
>>> round(3.3)
3
>>> x, y = 45, 125
>>> max(x, y)
125
>>> y = 45.9
>>> max(x, y)
45.9
def nombre_de_la_funcion(parametros):
    # la indentación es importante
    # deben ser 4 espacios
    <enunciados>
    return <valor>
def hola(name):
    return 'Hola ' + name

hola('Mónica')
def perimetro(r):
    pi = 3.1415926535897931
    return pi * r * 2


perimetro(4)
perimetro(6)
import math

def area(r):
    return math.pi * r ** 2

perimetro(4)
perimetro(6)