0

My code

def tripleAll(nums):
    for trip in [nums]:
        new = trip * 3
        print(new)

Then I would call the function with multiple numbers, like so.

tripleAll(3, 6, 7)

But, when I do this, it says it can only take one positional argument. How can I make it so it takes multiple positional arguments?

TimeWillTell
  • 191
  • 2
  • 11

3 Answers3

4

Change your function to this

def tripleAll(*nums):
    ...

*nums will allow you to pass arbitrary number of positional arguments to tripleAll. All of 'em will be stored in nums and you can iterate through them:

for trip in nums:
    ...

* is called splat operator. It unpacks the elements from an iterable to positional arguments of a function. The simple example

def f(*a):
    print('function received these arguments:', a)

f(1, 2, 3) # three arguments
f([1, 2, 3]) # one argument
f(*[1, 2, 3]) # unpack everything from [1, 2, 3] to function arguments

outputs

function received these arguments: (1, 2, 3)
function received these arguments: ([1, 2, 3],)
function received these arguments: (1, 2, 3)
vaultah
  • 44,105
  • 12
  • 114
  • 143
3

There are few things which can be readily observed.

def tripleAll(nums):     # Accepts only one argument
    for trip in [nums]:  # Creates a list with the number
        new = trip * 3   # Creates a local variable
        print(new)       # but does nothing, but printing

tripleAll(3, 6, 7)       # Passes three arguments

Apart from that. nothing is returned from tripleAll. You might be trying to do inplace tripling. So, its totally not clear what you are trying to do.

But, if you have a list of numbers and if you want to triple them, you can use list comprehension to create a new list with all the numbers tripled, like this

def tripleAll(nums):
    return [num * 3 for num in nums]

print tripleAll([1, 2, 3])
# [3, 6, 9]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

Your problem is that you are not passing a sequence of numbers as one argument, but rather several individual arguments. Your call should instead look like:

tripleAll([3, 6, 7])
kindall
  • 178,883
  • 35
  • 278
  • 309