0
0
Pythonprogramming~20 mins

Variable-length keyword arguments (**kwargs) in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Keyword Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of function using **kwargs with default values

What is the output of this Python code?

Python
def greet(**kwargs):
    name = kwargs.get('name', 'Guest')
    greeting = kwargs.get('greeting', 'Hello')
    return f"{greeting}, {name}!"

print(greet(name='Alice'))
AHello, Alice!
BAlice, Hello!
CHello, Guest!
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint

Look at how kwargs.get() provides default values if the key is missing.

โ“ Predict Output
intermediate
1:30remaining
Counting keys in **kwargs

What will be printed by this code?

Python
def count_keys(**kwargs):
    return len(kwargs)

print(count_keys(a=1, b=2, c=3))
ATypeError
B0
C3
D1
Attempts:
2 left
๐Ÿ’ก Hint

Count how many keyword arguments are passed to the function.

๐Ÿ”ง Debug
advanced
2:00remaining
Identify the error with **kwargs unpacking

What error does this code raise when run?

Python
def show_info(**kwargs):
    print(kwargs['age'])

info = {'name': 'Bob', 'age': 25}
show_info(info)
ATypeError
BKeyError
CSyntaxError
DNo error, prints 25
Attempts:
2 left
๐Ÿ’ก Hint

Check how the dictionary is passed to the function expecting keyword arguments.

๐Ÿš€ Application
advanced
2:30remaining
Which call prints all keyword arguments correctly?

Given this function, which call will print all keyword arguments as expected?

Python
def print_all(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
Aprint_all({'x': 1, 'y': 2})
Bprint_all([('x', 1), ('y', 2)])
Cprint_all(*{'x': 1, 'y': 2})
Dprint_all(x=1, y=2)
Attempts:
2 left
๐Ÿ’ก Hint

Remember how to pass keyword arguments to a function expecting **kwargs.

๐Ÿง  Conceptual
expert
3:00remaining
Behavior of **kwargs with overlapping keys

Consider this code snippet. What will be the output?

Python
def func(a, **kwargs):
    print(a)
    print(kwargs)

func(1, a=2, b=3)
A
2
{'b': 3}
BTypeError
C
1
{'a': 2, 'b': 3}
D
1
{'b': 3}
Attempts:
2 left
๐Ÿ’ก Hint

Think about how Python handles duplicate argument names in function calls.