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! While you're at it, check out some resources Treehouse students have shared here.

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

Python

Elgene Ee
Elgene Ee
3,554 Points

What is the main difference between these 2 styles of codes?

I typed 2 different layouts of a simple adding function. One is using the simple, less code way, while another using tuples taught by Kenneth Love. Check it out below:

#typical way
def adding(x, y):
  result = x + y
  return result 

#using tuples
def add(base, *args): 
  total = base 
  for num in args: 
    total += num 
  return total 

So what is the big difference between these two? I tried to input values via these functions and got the exact some output...There must be something special tuples has to offer than the typical way. Can you explain to me in details? Thank You!

2 Answers

Ricky White
Ricky White
8,799 Points

The first function works well when you have a fixed set of arguments to pass to the function. But there will be a case when you don't know how many variables will be passed to the function. In this instance, the second version should be used. The *args will catch addition arguments and store them in a tuple. In this example, the for loop cycles through the tuple to add each number for the tuple to the total. The first function will only work when exactly two arguments (x and y) are passed. The second will work with 2 or 2000 (and beyond).

Hope that helps.

Elgene Ee
Elgene Ee
3,554 Points

Thank you Ricky, You made me understand so well, but how about the base value? Could give some explanation on that?

Ricky White
Ricky White
8,799 Points

Tha base argument will be the current total being passed to the function which will be added to.