return sum(h_in_second, m_in_second, s_second) TypeError: sum expected at most 2 arguments, got 3

Viewed 26

Why I can't return sum value in function ?

def second_since_midnight(h, m, s):
    
    h_in_second = 3600 * h
    m_in_second = m * 60
    s_second = s
    
    return sum(h_in_second, m_in_second, s_second)


print(second_since_midnight(13, 30, 45))

Kind regard

2 Answers

Putting jasonharper's answer here since it seems to have solved the problem.

You need to encase your values in an iterable, like a list or tuple

sum() takes a single sequence of values, not individual parameters.

Instead of sum(h_in_second, m_in_second, s_second) try encapsulating your values in a list like this sum([h_in_second, m_in_second, s_second])

As noted in comments, sum expects an iterable, rather than individual arguments to sum. However the error code your received says it takes "at most two arguments" which doesn't seem to mesh with this statement.

The second argument is the start value for the sum. As of Python 3.8 and later, this can be specified as a keyword argument.

>>> a = [1, 2, 3]
>>> sum(a)
6
>>> sum(a, 1)
7
>>> sum(a, start=1)
7
Related