109 lines
1.5 KiB
Python
Executable File
109 lines
1.5 KiB
Python
Executable File
#!/usr/bin/env python
|
|
"""
|
|
Argumentos de funciones
|
|
- argumento posicional
|
|
- multiples argumentos
|
|
- argumento par clave-valor (keyword)
|
|
"""
|
|
|
|
def print_nombre(nombre):
|
|
print(nombre)
|
|
|
|
print_nombre('Juen')
|
|
# Juen
|
|
|
|
# argumentos posicionales
|
|
def foo(a, b, c):
|
|
print(a, b, c)
|
|
|
|
|
|
foo(1,2,3)
|
|
# 1 2 3
|
|
|
|
foo(c=1, b=2, a=3)
|
|
# 3 2 1
|
|
|
|
foo(1, b=2, c=3)
|
|
# 1 2 3
|
|
|
|
# foo(1, b=2, 3)
|
|
# SyntaxError:
|
|
# positional argument follows keyword argument
|
|
|
|
def boo(a, b, c, d=4):
|
|
print(a, b, c, d)
|
|
|
|
boo(1, 2, 3, 7)
|
|
# 1 2 3 7
|
|
|
|
boo(1,3,5, d=6)
|
|
# 1 3 5 6
|
|
|
|
boo(5, 4, 2)
|
|
# 5 4 3 4
|
|
|
|
|
|
def koo(a, b, *args, **kwargs):
|
|
# posicional
|
|
print('argumentos:')
|
|
print(a, b)
|
|
# multiples
|
|
print('*args:')
|
|
for arg in args:
|
|
print(arg)
|
|
# par clave=valor
|
|
print('*kwargs:')
|
|
for key in kwargs:
|
|
print(key, kwargs[key])
|
|
|
|
koo(1, 2, 3, 4, 5, seis=6, siete=7)
|
|
# argumentos:
|
|
# 1 2
|
|
# *args:
|
|
# 3
|
|
# 4
|
|
# 5
|
|
# *kwargs:
|
|
# seis 6
|
|
# siete 7
|
|
|
|
# Forzar el uso de argumento 'keyword' en funciones
|
|
|
|
# los argumentos que siguen del '*' deben ser 'keyword'
|
|
def loo(a, b , *, c, d):
|
|
print(a, b, c, d)
|
|
|
|
loo(1, 2, c=3, d=4)
|
|
# 1 2 3 4
|
|
|
|
|
|
def loo(*args, ultimo):
|
|
for arg in args:
|
|
print(arg)
|
|
print(ultimo)
|
|
|
|
loo(1, 2, ultimo=16)
|
|
# 1
|
|
# 2
|
|
# 16
|
|
|
|
|
|
# Desmepaquetando argumentos
|
|
def foo(a, b, c,):
|
|
print(a, b, c)
|
|
|
|
mi_lista = [0, 1, 2]
|
|
#mi_lista = (0, 1, 2)
|
|
|
|
# desempaquetar lista, tupla en el llamado a la función
|
|
foo(*mi_lista)
|
|
# 0 1 2
|
|
|
|
mi_dic = {'a':1, 'b':2, 'c':3}
|
|
foo(**mi_dic)
|
|
# 1 2 3
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|