Search code examples
pythonargs

How take *args input from user in a function


How take *args input from user in a function in Python.
I want to take input from user and get the addition user given input.

def add(*args):
    s = 0
    for i in args:
        s+=i
    print(s)

Output will be: 180


Solution

  • Command line arguments are inserted by the interpreter in argv list which is a global variable in sys module. So you just need to import it.

    Note however that argv[0] is the actual name of the running script and so the real arguments start from argv[1]. Also, those arguments are treated as strings even if they are numbers. So we need to convert them to ints (Here, I am assuming your addition function is supposed to be adding integers. If not, edit accordingly or write me a comment).

    The code for the above, if we were to use your function without any changes, would be the following:

    from sys import argv
    args = [int(x) for x in argv[1:]]
    add(args) # your function call
    

    If we were to also change your function, a simpler code (self-contained inside your function) would be the following:

    from sys import argv
    
    def add_args():
        s = 0
        for i in argv[1:]:
            s += int(i)
    
        print(s)