Using *args in Python: Handling Variable-Length Positional Arguments
In Python, you can add any number of arguments to a function, and *args and **kwargs can be helpful.
We should remember that asterisks * help in
packing and unpacking values.
Let’s use the same add function as in the previous chapter but with the use of *args.
def add(*args):
result = 0
for num in args:
result += num
return result
The difference is that you can pass any number of arguments to the function; even if you do not pass any arguments, the result will be 0, just like a calculator in your phone.
The function add receives any number of arguments and packs them into a tuple with the variable name args. The for loop goes through the tuple values and adds them to the result variable in the body of the function.
Note
You can use not only
*argsbut any name. However, it is best practice to use the nameargsfor arbitrary arguments.
Arbitrary arguments must appear after the positional and optional arguments.
def add(a, b=0, *args):
result = a + b
for num in args:
result += num
return result
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Pergunte-me perguntas sobre este assunto
Resumir este capítulo
Mostrar exemplos do mundo real
Awesome!
Completion rate improved to 3.7
Using *args in Python: Handling Variable-Length Positional Arguments
Deslize para mostrar o menu
In Python, you can add any number of arguments to a function, and *args and **kwargs can be helpful.
We should remember that asterisks * help in
packing and unpacking values.
Let’s use the same add function as in the previous chapter but with the use of *args.
def add(*args):
result = 0
for num in args:
result += num
return result
The difference is that you can pass any number of arguments to the function; even if you do not pass any arguments, the result will be 0, just like a calculator in your phone.
The function add receives any number of arguments and packs them into a tuple with the variable name args. The for loop goes through the tuple values and adds them to the result variable in the body of the function.
Note
You can use not only
*argsbut any name. However, it is best practice to use the nameargsfor arbitrary arguments.
Arbitrary arguments must appear after the positional and optional arguments.
def add(a, b=0, *args):
result = a + b
for num in args:
result += num
return result
Obrigado pelo seu feedback!