+ 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?
4 Antworten
+ 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 😀
+ 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
+ 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
+ 2
sum(nums)
= a + a**a + a * 4
= 3 + 3**3 + 3 * 4
= 3 + 27 + 12
= 42