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?

4
  • 1
    add(*sys.argv[1:]) Commented Nov 12, 2018 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 Commented Nov 12, 2018 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. Commented Nov 12, 2018 at 13:47
  • def my_sum( would be better IMO, but it's a small point Commented Nov 12, 2018 at 13:48

2 Answers 2

9

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:]))
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.