[SOLVED] Is the function I made is the same as SUM()?

Issue

I wrote this code:

def myFunction(*array):
  i = 0
  j = 0
  while i < len(array):
    j = j + array[i]
    i = i + 1
  return j

array=[1,2,3,4]

myFunction(array)

but I got this error:

j = j + array[i]

TypeError: unsupported operand type(s) for +: 'int' and 'list'

I looked for a solution and found one on
TypeError: unsupported operand type(s) for +=: 'int' and 'list'

If I change j = j + array[i] to j += sum(array[i]), there is no error and I get a value.

Why did my error happen? Is array[i] a 2D array? Why I must use the sum function?

Solution

this will work for you:

def myFunction(array):
  i = 0
  j = 0
  while i < len(array):
    j = j + array[i]
    i = i + 1
  return j

array=[1,2,3,4]

myFunction(array)

Answered By – Tal Folkman

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *