arguments while defining function in python

Question:

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:UsersAdminDesktopmy graphScriptspython.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?

Asked By: night bot

||

Answers:

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
Answered By: bn_ln
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.