Accept a variable number of arguments with kwargs #
In the previous lesson, besides using args to receive an unlimited number of positional arguments, we can also receive an unlimited number of keyword arguments by using the ** symbol in the same way. The values that are specified when calling the function will be stored as a dictionary.
def do_something(**kwargs):
print("keyword arguments: ", kwargs)
do_something(a="5", b="10", c="15")
Output:
keyword arguments: {'a': '5', 'b': '10', 'c': '15'}
Furthermore, we can use args and kwargs together in the same function.
def do_something(*args, **kwargs):
print("positional arguments:", args)
print("keywr=ord arguments:", kwargs)
do_something(1, 2, 3, a="5", b="10", c="15")
Output:
positional arguments: (1, 2, 3)
keyword arguments: {'a': '5', 'b': '10', 'c': '15'}
Exercise #
Create a function named accept_any_keyword_arguments that can take any number of keyword arguments.
Tests #
- Create a function named
accept_any_keyword_arguments - Function
accept_any_keyword_argumentsshould accept any number of keyword arguments
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules