-3

This works.

a = [2,5,3,7,9,12]
def mean_list(x):
      b = 0
      for i in x:
            b=b+i
            c = b/len(x)
      return c
print(mean_list(a))

but this doesn't work, even though I have declared my list as global. Why?

def mean_list(x):
      global a
      a = [2,5,3,7,9,12]
      b = 0
      for i in x:
            b=b+i
            c = b/len(x)
      return c
print(mean_list(a))
  • Define *"doesn't work"*. Why are you using global state anyway? And why are you passing the same thing as a parameter? – jonrsharpe Jun 14 '16 at 11:52
  • What do you mean with "doesn't work"? Does it throw an Error? If so, add the complete traceback with the error. Before you call the function there is no `a` so you can't pass `a` into the function (because it does not exist). – syntonym Jun 14 '16 at 11:52
  • In the second example you define the function which defines `a`. Then you try to call the function by passing `a` as a parameter. The problem is that `a` has not been defined yet because the function has not been called! – Farhan.K Jun 14 '16 at 11:52
  • a is not defined, when you call global. create it outside of the function and it will work. But it is prettier to call with 2 arguments... – Destrif Jun 14 '16 at 12:01

1 Answers1

1

Your list (a) is only created when you call the function. So it is not created unless you call the function once, try calling the function with another variable and then a

noteness
  • 2,440
  • 1
  • 15
  • 15