简体   繁体   中英

Python: Accept multiple arguments

In Python I am trying to make a function that can accept 1 or more arguments. For simplicity let's say I want to make a function that prints all the arguments that are passed

def print_all(**arguments**):
    print(arg1, arg2, ..., argN)

so print_all("A", "B") would output AB .

The number of arguments passed could be 1 or more strings.

What is the best way to do this?

*args and **kwargs allow to pass any no of arguments, positional (*) and keyword (**) to the function

>>> def test(*args):
...     for var in args:
...         print var
... 
>>> 

For no of variable

>>> test("a",1,"b",2)         
a
1
b
2

>>> test(1,2,3)
1
2
3

For list & dict

>>> a = [1,2,3,4,5,6]
>>> test(a)
[1, 2, 3, 4, 5, 6]
>>> b = {'a':1,'b':2,'c':3}
>>> test(b)
{'a': 1, 'c': 3, 'b': 2}

For detail

You are looking for the usage of *args which allows you to pass multiple arguments to function without caring about the number of arguments you want to pass.

Sample example:

>>> def arg_funct(*args):
...     print args
...
>>> arg_funct('A', 'B', 'C')
('A', 'B', 'C')
>>> arg_funct('A')
('A',)

Here this function is returning the tuple of parameters passed to your function.

For more details, check: What does ** (double star) and * (star) do for parameters?

Simply this:

def print_all(*args):
    for arg in args:
        print(arg)

Use the splat operator ( * ) to pass one or more positional arguments. Then join them as strings in your function to print the result.

def print_all(*args):
    print("".join(str(a) for a in args))

>>> print_all(1, 2, 3, 'a')
123a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM