0

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?

Bijay Regmi
  • 1,187
  • 2
  • 11
  • 25
night bot
  • 5
  • 4
  • 1
    Might want to review this: [What does ** (double star/asterisk) and * (star/asterisk) do for parameters?](https://stackoverflow.com/q/36901/13843268). – sj95126 Oct 23 '22 at 22:24
  • Your syntax is fine. Any parameters following a `*` parameter will be a keyword-only parameter, which *must* be set with a keyword argument. – chepner Oct 23 '22 at 23:23

1 Answers1

0

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
bn_ln
  • 1,648
  • 1
  • 6
  • 13