Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
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 :)