-1

Instructions:

Define a function called summer() that sums the elements in a list of numbers. summer() takes a single list argument. First you need to initialize an accumulator to zero, then use a for-loop to add the value of each element in the list, and finally return the total sum to the calling program.

Question:

I know how to do this very easily with the sum() function but I am not allowed to use this. I must find a way to sum a lists value and print that sum.

i.e

>>> x = [9, 3, 21, 15]
>>> summer(x)
48

What I've tried:

xlist=[9,3,21,15]
sumed=0
def summer(x):
    for i in x:    
    sumed+=i

print(sumed)


summer(xlist)

I keep getting 'sumed' ref. before assignment with this one

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Montop20
  • 23
  • 6

1 Answers1

1

Let me translate the instructions step by step:

  • Step1

Define a function called summer() that sums the elements in a list of numbers.

def summer():
  "This function sums the elements in a list"
  • Step2

summer() takes a single list argument.

def summer(a_list):
  "This function sums the elements in a list"
  • Step3

First you need to initialize an accumulator to zero

def summer(a_list):
  "This function sums the elements in a list"
  accumulator = 0
  • Step4

, then use a for-loop to add the value of each element in the list,

def summer(a_list):
  "This function sums the elements in a list"
  accumulator = 0
  for elem in a_list:
    accumulator+= elem

and finally return the total sum to the calling program.

def summer(a_list):
  "This function sums the elements in a list"
  accumulator = 0
  for elem in a_list:
    accumulator+= elem
  return accumulator

Now, you can try in the shell:

>>> def summer(a_list):
...   "This function sums the elements in a list"
...   accumulator = 0
...   for elem in a_list:
...     accumulator+= elem
...   return accumulator
...
>>> x = [9, 3, 21, 15]
>>> summer(x)
48
balki
  • 26,394
  • 30
  • 105
  • 151