single
Combination of Positional and Keyword Arbitrary Arguments
Swipe to show menu
Consider a function that calculates the total cost of multiple items while allowing you to pass any number of prices and optional keyword settings such as discounts or taxes.
12345678910111213141516171819202122232425def calculate_total_cost(*prices, **settings): subtotal = sum(prices) discount = settings.get("discount", 0) tax = settings.get("tax", 0) discount_amount = subtotal * (discount / 100) taxed_amount = (subtotal - discount_amount) * (1 + tax / 100) print(f"Subtotal: ${subtotal:.2f}") if discount > 0: print(f"Discount: {discount}% (-${discount_amount:.2f})") else: print("No discount applied.") if tax > 0: print(f"Tax: {tax}% (+${taxed_amount - (subtotal - discount_amount):.2f})") print(f"Final total: ${taxed_amount:.2f}") print() # Examples of using the function calculate_total_cost(1000, 250, 50) calculate_total_cost(1200, 800, discount=10) calculate_total_cost(500, 750, 250, discount=5, tax=8)
In the code above, you will notice the line settings.get("discount", 0).
Because settings collects keyword arguments into a standard Python dictionary, we use the dictionary .get() method to retrieve values safely.
Normally, if you try to look up a key that doesn't exist in a dictionary using square brackets (like settings["discount"]), Python will crash and throw a KeyError. The .get() method prevents this by allowing you to provide a fallback default value.
The syntax works like this:
dictionary.get(key, default_value)
key: the name of the setting you are looking for (e.g., "discount" or "tax").
default_value: the value to return if that key was not passed into the function.
Rules for Combining Arbitrary Arguments
Positional Arbitrary Arguments (*args)
*args collects all extra positional arguments into a tuple.
In this example, the function can take any number of item prices without needing to define them explicitly.
For example:
calculate_total_cost(500, 250, 100)
Here, *prices becomes (500, 250, 100).
Keyword Arbitrary Arguments (**kwargs)
**kwargs collects all named (keyword) arguments into a dictionary.
This allows the function to accept additional named settings such as discount or tax, even if they weren’t predefined.
For example:
calculate_total_cost(1000, 500, discount=10, tax=5)
Here, **settings becomes {'discount': 10, 'tax': 5}.
Combining Both
You can use both *args and **kwargs in the same function to achieve maximum flexibility — letting you handle any number of positional values and any combination of named settings.
Always place *args before **kwargs in the function signature – reversing the order will result in a SyntaxError.
Swipe to start coding
Implement a generate_report function that accepts any number of numeric scores and optional keyword settings.
-
Use
*argsto collect scores (name the parameterscores) and**kwargsto collect optional settings. -
Calculate the average of all provided scores by summing all values in scores and dividing by the number of scores:
Average=len(scores)sum(scores) -
If a
"label"key is present in**kwargs, use its value as the report title; otherwise use"Report". -
If a
"passing_score"key is present in**kwargs, check whether the average meets or exceeds it:- If yes, add
"Status: Pass"to the report. - If no, add
"Status: Fail".
- If yes, add
-
Return the result as a formatted string:
"{label} | Average: {avg:.2f} | {status}". If no"passing_score"is provided, omit the status part:"{label} | Average: {avg:.2f}".
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat