-2

I'm new to python and I want to convert a loop "for" into a function. My loop I created enables me to multiply all the number of a list and print the result. This is my loop:

a=[1,2,3,4,9]
y=1
for x in a:
   y=y*x
   print(y)

As you can see I tried it with a certain list and I always put y=1 to start my loop and it works very well but when I want to create a function of that loop it fails, so far I tried that:

a=[]
y=1
def produit_entier(a):
   for x in a:
       y=y*x
       return y  
a=[1,2,3,4,9]
y=1
print(produit_entier(a))

As you can see I tried it with a certain list and when I run my code it tells me "local variable 'y' referenced before assignment", and when I remove the "y=1" line and put it right after the "for x in a:" this message disappear but the result is always 1.

So I'm lost here, my function is almost exactly the same as my loop, but my loop works very well and not my function, so I would really appreciate help here. Thx in advance

  • Possible duplicate: https://stackoverflow.com/questions/11904981/local-variable-referenced-before-assignment – ForceBru Mar 20 '22 at 19:53

3 Answers3

2

The y needs to be declared inside the function, since it is used by the function.

def produit_entier(a):
   y = 1
   for x in a:
       y=y*x
   return y
QWERTYL
  • 1,355
  • 1
  • 7
  • 11
0

Karim!

First of all, there is a problem with the return statement. You placed it the wrong way, it should be like this:

def produit_entier(a):
   for x in a:
       y=y*x
   return y  

Secondly, if you want to modify a value inside a function, which is not passed or declared inside the function - you gotta specify a global keyword to make it accessible for the modification (if you only want to read it - you do not have to specify global keyword):

def produit_entier(a):
   global y
   for x in a:
       y=y*x
   return y  

Thirdly, you do not have to return a value of y though it is a global one, just print it after.

And fourthly, using global variables is actually a bad practice (since you might modify if accidentally somewhere you do not want to and it will be difficult to find). I suggest you either declare it inside the function:

def produit_entier(a):
   y = 1
   for x in a:
       y=y*x
   return y  

Or just pass a value as an argument:

def produit_entier(a, y):
   for x in a:
       y=y*x
   return y

Best of luck!

Akado2009
  • 381
  • 1
  • 4
  • 11
0

I'll provide an alternative answer using reduce:

from functools import reduce

def produit_entier(a):
    return reduce(lambda x,y: x*y,a)

Or just the built-in reduce(int.__mul__, a)

Attersson
  • 4,755
  • 1
  • 15
  • 29