Variable number of parameters in Python (according to the book "A byte of Python") [duplicate]

This question is already answered here: What does * (asterisk) and ** double asterisk mean in Python? (1 answer) Closed 11 months ago.

Good day to all. Who can explain to me in detail how it works? The moment starts with line 2 and ends with "return" (inclusive). On the rest of the topic figured out, at this point I'm racking my head. I apologize if I made it wrong.

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))
Author: nomnoms12, 2020-04-01

1 answers

In the second line, the initial value is written to count. If you call the function so print (total (initial=10)) or so print (total(7)), the program will output 10 or 7, respectively. In the third line, there is a loop over all the values from numbers that are obtained when setting positive arguments. In the fourth one, these arguments are added to count. In the fifth, there is a loop for all the keys from keywords that were obtained when setting keyword arguments. In the sixth line there is an addition of values from a specific key to count. Accordingly, return returns the value count.

I advise you to read this small article, here a detailed answer is given on a slightly different example.

 0
Author: Ildar Akhmetov, 2020-04-02 01:12:56