8

I have to write a simple function that takes variable number of arguments and prints the sum, something simple like(ignoring error checks):

def add(*params):
    sum = 0
    for num in params:
        sum += num
    print(sum)

I have to call the script and give it arguments that will then be used in the function. I get these arguments like this:

import sys
sys.argv[1:]

But that's an array and sending it to add would just mean passing 1 argument that is a list. I'm new to Python so maybe all of this sounds stupid, but is there any way to pass these arguments to the function properly?

Angelo
  • 183
  • 1
  • 1
  • 10
  • 1
    `add(*sys.argv[1:])` – Chris_Rands Nov 12 '18 at 13:42
  • you now about builtin `sum()` I assume? `add()` is already a function too for adding two values, so it's a bad name choice here – Chris_Rands Nov 12 '18 at 13:43
  • @Chris_Rands I have to write the function myself for a small assignment. And yeah I named them in my language just wrote the english version here, didn't know add was already a thing but the editor highlights these stuff so I know not to use keywords. – Angelo Nov 12 '18 at 13:47
  • `def my_sum(` would be better IMO, but it's a small point – Chris_Rands Nov 12 '18 at 13:48

2 Answers2

7

Yes, just unpack the list using the same *args syntax you used when defining the function.

my_list = [1,2,3]
result = add(*my_list)

Also, be aware that args[1:] contains strings. Convert these strings to numbers first with

numbers = [float(x) for x in args[1:]]

or

numbers = map(float, args[1:]) # lazy in Python 3

before calling add with *numbers.

Short version without your add function:

result = sum(map(float, args[1:]))
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You should use the argument unpacking syntax:

def add(*params):
    sum = 0
    for num in params:
        sum += num
    print(sum)

add(*[1,2,3])
add(*sys.argv[1:])

Here's another Stack Overflow question covering the topic

rjmurt
  • 1,135
  • 2
  • 9
  • 25