Accepting Any Number of args
00:24 Note that the examples in this course have shown running in the Bpython shell, which also has some improved functionality, such as syntax color-coding. Everything you see on-screen will run in the standard Python shell, but Bpython makes seeing the syntax easier.
If you use
some_items as an argument to
print(), then you’re passing one variable to
print() displays the list as you would expect. However, if you use
*some_items within the parentheses of
print(), you get a different outcome.
You can also use
print() with empty parentheses, and it will print a blank line. You’re now ready to define your own functions that can accept a variable number of input arguments. For the time being, you can simplify
add_items() to accept only the names of the items you want in the shopping list.
You’ll then set the quantity to
1 for each item. You’ll get back to including the quantities as part of the input arguments later on in the course. The function signature that includes the variable number of input arguments using
args looks like this.
The first argument when calling
add_items() is a required argument. Following the first argument, the function can accept any number of additional arguments. In this case, you’ve added four additional arguments when calling the function. On-screen, you can see the output of this code.
This is not the same as passing a tuple as an argument in the function call. Using
*args allows you to use the function more flexibly, as you can add as many arguments as you wish without the need to place them in a tuple in the function call. If you don’t add any additional arguments when you call the function, then the tuple will be empty, as seen on-screen.
When you add
args to a function definition, you’ll usually add them after the required and optional parameters. You can have keyword-only arguments that follow the
args. But for this course, you can assume that
args will usually be added after all the other arguments, except for
kwargs, which you’ll see next.
Become a Member to join the conversation.