# Is there a better alternative than adding each number?

I found this one to be an odd exercise. I knew while completing it that there were better ways to write the function, but couldn’t think of anything except for the following:

# Write your first_three_multiples function here:

def first_three_multiples(num):
print(num, num + num, num + num + num)
return num + num + num

Running this worked and met the requirements to complete this portion of the lesson, but for practical application, how could I write this better? For example, how would I write this function if I wanted to see the first 50 multiples and have it return or print the 27th, 32nd and 50th? My solution above would still work but would require a LOT of "+ num"s. Obviously the better choice is to keep your code as simple and condensed as possible.

I feel silly asking but for some reason I’m not connecting the dots on this one…

1 Like

Returning three values implies a list, or a tuple sent back to the caller.

``````return num, num * 2, num * 3
``````

Given that as a return value, we can use the `unpack operator` on either list or tuple.

``````>>> def first_three_multiples(x):
return x, x * 2, x * 3

>>> first_three_multiples(10)
(10, 20, 30)
>>> print (*first_three_multiples(10), end=' ')
10 20 30
>>>
``````
``````>>> def first_three_multiples(x):
return [x, x * 2, x * 3]

>>> print (*first_three_multiples(10), end=' ')
10 20 30
>>>
``````

The lesson expects only a single value on return, the third multiple, and for us to print the values in the loop.

``````for x in range(num, num * 4, num):
print (x, end=' ')
return x``````

Absolutely no reason to feel silly! We’re all learning here!

def first_three_multiples(num):
print(num, num + num, num + num + num)
return num + num + num

you can just use a num, a num*2, and a num*3 (Also return num*3)
Like this

def first_three_multiples(num):
print (num)
print (num*2)
print (num*3)
return num*3

Multiplying is just simplified addition, so here we can just use multiplying and be neat and simple - instead of adding all of them.

How do we ‘simplify addition’? Multiplication is repeated addition and only exists because of the additive property of numbers.

1 Like

You’re completely right, I did mean repeated! My apologies, it was pretty late when I replied to that, didn’t completely get to convey my thoughts haha.
But yeah, the code should still be correct, regardless of my language barrier blunder.
(When I said simplified, I meant less items in code, replying to their question on how to keep code “as simple and condensed as possible.”)
Thanks for the keen eye!

2 Likes

Thank you for explaining this. Totally helped me

1 Like