What should I do if I want to take multiple arguments (by using *) as well as a key word argument while defining a function? Is there a way to take multiple keyword arguments (by using **) and a single argument or both multiple keywords (by using **) and arguments (by using *) at the same time while defining a function? I tried to do this by myself, and I did it this way.
code
def function_name(*x, a):
for i in x:
print(f"{a} {i}")
function_name("Aditya", "neer", "parth", "ralph", a="hello" )
output
"C:\Users\Admin\Desktop\my graph\Scripts\python.exe" C:/Users/Admin/Desktop/pythonProject1/main.py
hello Aditya
hello neer
hello parth
hello ralph
Process finished with exit code 0
Is there a better way to accomplish all of these conditions?
CodePudding user response:
Yes, use **kwargs
to capture the keyword arguments. One restriction to be aware of that is the keyword arguments should come after the positional arguments. kwargs
will be a dictionary.
def function_name(*x, **greetings):
for k in greetings:
for i in x:
print(f"{greetings[k]} {i}")
function_name("Aditya", "neer", "parth", "ralph", a="hello", b="hi" )
Output:
hello Aditya
hello neer
hello parth
hello ralph
hi Aditya
hi neer
hi parth
hi ralph