E
E
Evgeny Kolesov2018-08-08 07:33:14
Python
Evgeny Kolesov, 2018-08-08 07:33:14

What does sum = arg[0] code snippet do? (explained below)!?

Here's a question: there's an exercise in Lutz's book on learning python. You need to create a function that will calculate an arbitrary number of arguments.

def adder(*args):
    print('adder', end=" ")
    sum = args[0]  # остальное понимаю, а вот тут не понятно, почему именно 0, как этот кусок когда работает? И пробовал менять значения с [0] на [1] и в случае с единицей при последующем присваивании аргументов он их перемножал, а не складывал, как в случае с [0].
    for next in args[1:]: # тут тоже не до конца понял
        sum =+ next
    return sum

PS below I write adder (value1, value2, etc.), everything works, but I can’t figure out exactly how it works in that code fragment

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Jock Tanner, 2018-08-08
@Tanner

Here is the place in the official docs:
https://docs.python.org/3/tutorial/controlflow.htm...
Here is a good article on this topic:
https://tproger.ru/translations/python-args-and- kwargs/

K
KhD, 2018-08-08
@KhD

Why rename the existing sum function?
You can simply:

def adder(*args):
    print('adder')
    return sum(arg)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question