pythonfor-loopcycle

Python.The problem is in solving the problem with cycles


The sum() function takes a series of numbers (a string) and returns their sum.

def sum(numbers):
    result = 0
    for num in:
        result += 
    return result

sum("12345")  # 15

I started learning the language recently. In one of the sites I came across this problem that I can not solve.

def sum(numbers):
    result = 0
    for num in numbers:
        result += 1

This is how I see the solution to this problem, but it is not correct.


Solution

  • You have to convert str num to int before adding:

    def sum1(numbers):
        result = 0
        for num in numbers:
            result += int(num)  # add each number from numbers
        return result
    
    sum1('12345')
    
    #15