- 1
Can someone explain me this code of variable arguments in function?
def total(initial=5, *numbers, **keywords): count = initial for number in numbers: count += number for key in keywords: count += keywords[key] return count print(total(10, 1, 2, 3, vegetables=50, fruits=100)) Output is 166
7 Réponses
+ 8
Here is an explanation what happens to the various parameters in the function header:
def total(initial=5, *numbers, **keywords):
...
calling the function like it is done in the sample:
print(total(10, 1, 2, 3, vegetables=50, fruits=100))
the first argument 10 will be stored in var "initial" and will overwrite the default value of 5.
"initial": 10, type int
the next n arguments (3 integers) will be stored in "numbers", which are called "args" = arguments. the number of arguments depends on the call of the function
args: (1, 2, 3), type tuple
the next n arguments (2) will be stored in "keywords", which are called "keyword args"
the number of arguments depends on the call of the function
keywords: {'vegetables': 50, 'fruits': 100}, type dictionary
+ 1
it just adds up all the values.
https://www.geeksforgeeks.org/args-kwargs-JUMP_LINK__&&__python__&&__JUMP_LINK/
+ 1
Slick thanks so much helped alot !
Can you name some other useful sites like geeksforgeeks which I just discovered via you?
+ 1
tutorialspoint.com
realpython.com
w3schools.com
stackoverflow.com
docs.python.org
+ 1
Slick thanks again will check them out soon! 😀
+ 1
Thanks so much Lothar for giving me your time & explaining wonderfully! 😀
0
No problem at all