-1

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

gre_gor
  • 6,115
  • 9
  • 39
  • 46
Ravi Siswaliya
  • 115
  • 1
  • 6
  • 1
    Possible duplicate of http://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user. Can't VTC, since I already VTC'd for a different reason initially. – Heinzi Mar 16 '17 at 16:03
  • 2
    Why will the output be 180? Won't the output depend on the input? – Bryan Oakley Jan 24 '18 at 15:32

1 Answers1

4

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)
kyriakosSt
  • 1,621
  • 2
  • 17
  • 31
  • 1
    Instead of `list(map(lambda x: int(x), argv[1:]))` it would be a bit clearer (more Pythonic) to use a list comprehension: `[int(x) for x in argv[1:]]` – Arthur Tacca Jan 24 '18 at 15:42
  • Or indeed not to define a lambda which just calls another function! i.e. `list(map(int, argv[1:]))`. But I still think the list comprehension is clearer still (but your final suggestion is clearest of all; but I would move the import out of the function to the top of the file). – Arthur Tacca Jan 24 '18 at 15:47
  • @ArthurTacca Indeed, `map` and `lambda` completely unnecessary. I am about to edit that. Yes, I suppose you could also argue that importing in the beginning is better, although in some cases I greatly prefer it just before usage. In that case, I placed inside so that the code is truly self-contained. – kyriakosSt Jan 24 '18 at 16:23