Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre **kwargs | An Unknown Number of Arguments
Python Functions: From Zero to Hero

book
**kwargs

Similar to *args, we use **kwargs to pass a variable number of named arguments. Similar to *args, if we put ** in front of a name, the name will accept any number of named arguments. A dictionary of several passed arguments will be available under this name. Let's look at the example.

def grocery_cart(price_of_apples, **prices_of_other_fruits):
print(price_of_apples)
for value in prices_of_other_fruits.values():
print(value)

grocery_cart(price_of_apples = 10, price_of_oranges = 7, price_of_carrots = 12)
123456
def grocery_cart(price_of_apples, **prices_of_other_fruits): print(price_of_apples) for value in prices_of_other_fruits.values(): print(value) grocery_cart(price_of_apples = 10, price_of_oranges = 7, price_of_carrots = 12)
copy

To sum up Arbitrary Arguments:

  • use a single asterisk (*) to unpack iterables.

  • and use 2 asterisks (**) to unpack dictionaries.

Tâche

Swipe to start coding

Code a function, named function, that will take in an unknown number of named arguments. This function runs for each argument using the for loop and prints only those longer than 6 characters.

Solution

def function(**variables):
for x in variables.values():
if len(x) > 6:
print(x)
function(name="Max", town="London", language="English")

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 3
single

single

# Write your code below
def function(**variables):
for x in ___.___():
if ___:
print(___)

# Testing
function(name="Max", town="London", language="English")

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

some-alt