Creating functions with a variable
number of arguments
In most cases, you know precisely how many arguments to provide with your
function. It pays to work toward this goal whenever you can because functions
with a fixed number of arguments are easier to troubleshoot later. However,
sometimes you simply can’t determine how many arguments the function will
receive at the outset. For example, when you create a Python application that
works at the command line, the user might provide no arguments, the maximum
number of arguments (assuming there is one), or any number of arguments in
between.
Fortunately, Python provides a technique for sending a variable number of argu-
ments to a function. You simply create an argument that has an asterisk in front
of it, such as
*VarArgs
. The usual technique is to provide a second argument that
contains the number of arguments passed as an input. To see how this works,
open a copy of IPython and type the following code:
CHAPTER 4
Do'stlaringiz bilan baham: |