Can someone explain me this code of variable arguments in function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 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

10th Oct 2020, 11:37 AM
VINIT SHARMA
VINIT SHARMA - avatar
7 Answers
+ 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
10th Oct 2020, 12:25 PM
Lothar
Lothar - avatar
10th Oct 2020, 11:41 AM
Slick
Slick - avatar
+ 1
Slick thanks so much helped alot ! Can you name some other useful sites like geeksforgeeks which I just discovered via you?
10th Oct 2020, 11:52 AM
VINIT SHARMA
VINIT SHARMA - avatar
+ 1
tutorialspoint.com realpython.com w3schools.com stackoverflow.com docs.python.org
10th Oct 2020, 11:56 AM
Slick
Slick - avatar
+ 1
Slick thanks again will check them out soon! 😀
10th Oct 2020, 11:58 AM
VINIT SHARMA
VINIT SHARMA - avatar
+ 1
Thanks so much Lothar for giving me your time & explaining wonderfully! 😀
10th Oct 2020, 4:32 PM
VINIT SHARMA
VINIT SHARMA - avatar
0
No problem at all
10th Oct 2020, 11:58 AM
Slick
Slick - avatar