+ 2

Can someone explain me this code (Python 3).

I have this little code: a = 3; def sumofnum(*nums): return sum(nums); print(sumofnum(a, a**a, a * 4)); output: 42 I don't understand the * in the argument of sumofnum, what does it mean? why is there 3 arguments? does not have just to be one?

29th May 2018, 4:48 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
4 Respostas
+ 17
any function in python can be written as: def my_func(*args, **kwargs): ...... where args will be a list of all positional arguments and kwargs will be a dictionary of all named arguments. I.e. if you call that function like this: my_func( 1, 'a', 33, name='me', other=42) then inside the function args = [ 1, 'a', 33 ] and kwargs = { 'name': 'me', 'other':42}. Hope that makes it a bit more clear 😀
29th May 2018, 5:07 PM
Nikolay Nachev
Nikolay Nachev - avatar
+ 3
Its called the splat operator https://stackoverflow.com/questions/2322355/proper-name-for-JUMP_LINK__&&__python__&&__JUMP_LINK-operator it unpacks the arguments in the input to the function. thus 3+27+12
29th May 2018, 5:09 PM
Louis
Louis - avatar
+ 3
This example shows how you can use unpacking on a list and combine it with print's funtions https://code.sololearn.com/c4TA37yaJaB2/?ref=app
29th May 2018, 5:53 PM
Louis
Louis - avatar
+ 2
sum(nums) = a + a**a + a * 4 = 3 + 3**3 + 3 * 4 = 3 + 27 + 12 = 42
29th May 2018, 6:15 PM
Markus Kaleton
Markus Kaleton - avatar