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?
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:]))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With