How take *args input from user in a function

Question:

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

Asked By: Ravi Siswaliya

||

Answers:

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)
Answered By: kyriakosSt
def add(*args):
    s = 0
    for i in args:
        s+=i
    print(s)

add(*list(map(int,input("Enter the numbers").split())))
Answered By: Arkapratim Ghosh
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.