0

I have a code in Jupyter (Python) gives me that warning and doesn't run the code but... well, the "variable" that doesn't run is a function. In one cell I have something like

def rr1(x):
    return x[0]+x[1]

And in the next cell I have

def function_2(y,z):
    A=np.random.rand(y[0],y[1])
    B=rr1(A[0])
    C=abs(B)**2
    for it in range(z):
    [d,e,f]=[rr1(A[it+1]),rr2(A[it+1]),rr3(A[it+1])]
    if(things.happen()):
    ...
    for blablabla:
        [rr1,rr2,rr3]=[more,things,in_lists]
    return blabla

cosa=function_2([3,5],4)

When I try to implement function_2 it gives me the warning local variable rr1 referenced before asignement". Why? What I can do? Well... all the problem was that after using the function a few times, I called a few variables with the name of the function... Brilliant :face_palm: Trying to make the "Minimal, Reproducible example" worked. Many thanks.

Uli_WH
  • 1
  • 1
  • 2
    Post all your code please in a code block by highlighting it and pressing CTRL-K. – no ai please Jul 10 '21 at 02:19
  • 1
    It's pages long, do I need to post all of it? That's the only thing I changed and it's where it fails... – Uli_WH Jul 10 '21 at 02:22
  • 3
    @Uli_WH Create a [minimal reproducible exmaple](https://stackoverflow.com/help/minimal-reproducible-example). – Amith Jul 10 '21 at 02:23
  • Oh, ok. I'll do that. – Uli_WH Jul 10 '21 at 02:27
  • Just try running the before cell where function is written – PCM Jul 10 '21 at 02:34
  • @Amith I'll like to upvote your answer. It was very helpfull. – Uli_WH Jul 10 '21 at 03:49
  • Add `global rr1` to the function, since you don't *want* a local variable. While you can read globals by fallback, writing them requires you to tell the compiler that. – o11c Jul 10 '21 at 03:53
  • Does this answer your question? [Local variable referenced before assignment?](https://stackoverflow.com/questions/18002794/local-variable-referenced-before-assignment) – o11c Jul 10 '21 at 03:54
  • Not, because rr1 isn't a variable (even if I added then a variable that was called like the function... things happen when recycling code without being careful...) – Uli_WH Jul 10 '21 at 03:56

1 Answers1

0

Run the first cell containing the function rr1 first then the second function where you reference rr1. It can't find the first function probably because you haven't executed it yet.

Jerven Clark
  • 1,191
  • 2
  • 13
  • 26
  • Sometimes, when you close jupyter and continue after some time, the variable gets deleted. So, this answer should solve your problem. – PCM Jul 10 '21 at 03:00