Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Using Variable-Length Keyword Arguments (**kwargs) in Python
๐ Scenario: You are creating a simple program to store information about a car. Different cars have different features, so you want a flexible way to add any number of details about each car.
๐ฏ Goal: Build a Python function that accepts any number of named details about a car using **kwargs and then prints those details.
๐ What You'll Learn
Create a function called car_info that accepts variable-length keyword arguments using **kwargs.
Inside the function, use a for loop with variables key and value to iterate over kwargs.items().
Print each key and value pair in the format: key: value.
Call the function with at least three named arguments representing car details.
๐ก Why This Matters
๐ Real World
Many programs need to handle flexible data inputs, like user profiles or product details, where the exact information can vary.
๐ผ Career
Understanding <code>**kwargs</code> is important for writing adaptable Python functions used in web development, data processing, and automation tasks.
Progress0 / 4 steps
1
Define the car_info function with **kwargs
Write a function called car_info that accepts variable-length keyword arguments using **kwargs. Inside the function, write a pass statement for now.
Python
Hint
Use def car_info(**kwargs): to define the function and write pass inside to keep it empty for now.
2
Add a for loop to iterate over kwargs.items()
Inside the car_info function, add a for loop with variables key and value to iterate over kwargs.items(). For now, just write pass inside the loop.
Python
Hint
Use for key, value in kwargs.items(): to loop through all keyword arguments.
3
Print each key and value inside the loop
Replace the pass inside the for loop with a print statement that shows the key and value in the format: key: value using an f-string.
Python
Hint
Use print(f"{key}: {value}") to display each detail clearly.
4
Call car_info with three named arguments and print the output
Call the car_info function with these exact named arguments: make='Toyota', model='Corolla', and year=2020. This will print the car details.
Python
Hint
Call car_info(make='Toyota', model='Corolla', year=2020) exactly to see the details printed.
Practice
(1/5)
1. What does **kwargs allow you to do in a Python function?
easy
A. Pass a variable number of keyword arguments as a dictionary
B. Pass a variable number of positional arguments as a tuple
C. Return multiple values from a function
D. Define a function without any parameters
Solution
Step 1: Understand **kwargs usage
**kwargs collects extra keyword arguments into a dictionary inside the function.
Step 2: Compare with other options
Pass a variable number of positional arguments as a tuple describes *args, not **kwargs. Options A and C are unrelated to **kwargs.
Final Answer:
Pass a variable number of keyword arguments as a dictionary -> Option A
Quick Check:
**kwargs = keyword args dict [OK]
Hint: Remember: **kwargs collects named arguments as a dict [OK]
Common Mistakes:
Confusing *args with **kwargs
Thinking **kwargs collects positional arguments
Believing **kwargs returns multiple values
2. Which of the following is the correct way to define a function that accepts variable keyword arguments?
easy
A. def func(*kwargs):
B. def func(**kwargs):
C. def func(**kwargs, *args):
D. def func(kwargs**):
Solution
Step 1: Recall correct syntax for keyword arguments
The correct syntax to accept variable keyword arguments is **kwargs.
Step 2: Check each option
def func(*kwargs): uses single star which is for positional args. def func(**kwargs, *args): is invalid syntax because **kwargs must come after any *args. def func(kwargs**): is invalid syntax.
Final Answer:
def func(**kwargs): -> Option B
Quick Check:
Double star before kwargs means keyword args [OK]
Hint: Use double star ** before kwargs in function definition [OK]
Common Mistakes:
Using single star * instead of double star **
Placing **kwargs incorrectly in parameters
Writing invalid syntax like kwargs**
3. What will be the output of the following code?
def greet(**kwargs):
if 'name' in kwargs:
return f"Hello, {kwargs['name']}!"
else:
return "Hello, stranger!"
print(greet(name='Alice'))
print(greet(age=30))
medium
A. Error: KeyError
B. Hello, Alice!\nHello, None!
C. Hello, stranger!\nHello, stranger!
D. Hello, Alice!\nHello, stranger!
Solution
Step 1: Analyze function behavior with kwargs
The function checks if 'name' is a key in kwargs. If yes, it returns a greeting with that name; otherwise, it returns "Hello, stranger!".
Step 2: Evaluate each print statement
First call passes name='Alice', so output is "Hello, Alice!". Second call passes age=30, no 'name' key, so output is "Hello, stranger!".
Final Answer:
Hello, Alice!\nHello, stranger! -> Option D
Quick Check:
Check key in kwargs dict to decide greeting [OK]
Hint: Check if 'name' key exists in kwargs before using it [OK]
Common Mistakes:
Assuming missing key returns None instead of else case
Expecting KeyError without checking key presence
Confusing positional and keyword arguments
4. Identify the error in the following code and choose the correct fix:
C. Add a default value for 'age' using kwargs.get('age', default)
D. Call show_info with age parameter
Solution
Step 1: Identify the error cause
The function tries to print kwargs['age'], but the call only passes name='Bob'. This causes a KeyError because 'age' key is missing.
Step 2: Choose the fix
Using kwargs.get('age', default) safely returns a default value if 'age' is missing, avoiding the error.
Final Answer:
Add a default value for 'age' using kwargs.get('age', default) -> Option C
Quick Check:
Use kwargs.get() to avoid KeyError on missing keys [OK]
Hint: Use kwargs.get('key', default) to avoid missing key errors [OK]
Common Mistakes:
Not handling missing keys causing KeyError
Confusing *args and **kwargs
Ignoring the need to pass required keys
5. You want to write a function build_profile that accepts a mandatory username and any number of additional keyword arguments describing user info. Which of the following implementations correctly returns a dictionary with all this data?
Mandatory parameters must come before **kwargs. def build_profile(**kwargs, username):
kwargs['username'] = username
return kwargs is invalid syntax because **kwargs must be last.
Step 2: Check dictionary construction
def build_profile(username, **kwargs):
profile = kwargs
profile['username'] = username
return profile modifies kwargs directly, which can cause unexpected side effects. def build_profile(username, **kwargs):
profile = {'username': username}
profile.update(kwargs)
return profile creates a new dict with username, then updates with kwargs safely.
Step 3: Evaluate *args usage
def build_profile(username, *args):
profile = dict(args)
profile['username'] = username
return profile uses *args which collects positional arguments, not keyword arguments, so it won't work as intended.