Funções


In [1]:
def soma(x, y):
    """Realiza a soma de dois números"""
    return x + y

In [3]:
def imprimir(valor):
    print(valor)

In [2]:
help(soma)


Help on function soma in module __main__:

soma(x, y)
    Realiza a soma de dois números


In [4]:
resultado = imprimir("teste")


teste

In [5]:
print(resultado)


None

In [6]:
resultado = soma(10.5, 4)

In [7]:
print(resultado)


14.5

In [8]:
soma("teste", "oi")


Out[8]:
'testeoi'

In [9]:
soma([1,2,3], [4,5,6])


Out[9]:
[1, 2, 3, 4, 5, 6]

In [10]:
soma


Out[10]:
<function __main__.soma>

In [11]:
soma_tmp = soma

In [12]:
soma_tmp(2, 3)


Out[12]:
5

In [13]:
soma(2, 3)


Out[13]:
5

In [14]:
def sub(x, y=1):
    return x - y

In [15]:
sub(2)


Out[15]:
1

In [16]:
sub(3, 2)


Out[16]:
1

In [17]:
sub(y=4, x=10)


Out[17]:
6

In [18]:
def aplicar(x, y, func):
    return func(x, y)

In [19]:
aplicar(10, 4, sub)


Out[19]:
6

In [20]:
def mult(*args):
    total = 1
    for i in args:
        total = total * i
    return total

In [21]:
mult(2, 4, 6, 10)


Out[21]:
480

In [22]:
mult()


Out[22]:
1

In [23]:
def criar_dict(**kwargs):
    d = {}
    for chave, valor in kwargs.items():
        d[chave] = valor
    return d

In [24]:
criar_dict(nome="gileno", email="c@c.com", idade=28)


Out[24]:
{'email': 'c@c.com', 'idade': 28, 'nome': 'gileno'}

In [ ]: