Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
How to create a multiply method that accepts *args and multiplies all the values and returns the product?
Let's play with the *args pattern. Create a function named multiply that takes any number of arguments. Return the product (multiplied value) of all of the supplied arguments. The type of argument shouldn't matter. Slices might come in handy for this one.
def multiply(*args): total = 0 for num in args: total *= args[num::1] return total
Hey Kirome, Your function is mostly correct with only a few errors.
- When you loop through all of the
argsnum is set to each separate e.g if the args were
2, 7, 4, 5, 5, num during the first iteration would be 2 and then 7 and so on. So there is no need to use
(just a heads up the slice method already has a step of 1 by default so you don't need to include it unless you are specifying a step like 2 or 3.)
- The only other thing I found is that make sure you set your initial multiplying varible (total) to 1 - if you multiply your initial arg by 0 it will always return 0
def multiply(*args): total = 1 for num in args: total *= num return total
thanks a lot for the help managed to get there in the end appreciate this exactly what I got :)