Home > Back-end >  How Do I return Nested Loop from a function in Python?
How Do I return Nested Loop from a function in Python?

Time:06-22

I have a code where I need to return a value of 2D list after processing a function.

The code for the function is

def Jacobian(N_xi,N_et,X,Y):
  J=[[0,0],[0,0]]
  for i in range(len(X)):
    J[0][0]=J[0][0] N_xi[i]*X[i]
    J[0][1]=J[0][1] N_xi[i]*Y[i]
    J[1][0]=J[1][0] N_eta[i]*X[i]
    J[1][1]=J[1][1] N_eta[i]*Y[i]
    return J

This function later runs as

J=[]
N_xi=[1,0,-1]
N_eta=[0,1,-1]
X=[0.123,1.265,2.221]
Y=[1.235,1.1763,2.224]
J=Jacobian(N_xi,N_eta,X,Y)

When I run this my Value for J is always [[0.125,0.125],[0,0]] Which is incorrect. I thought this was because the block of code I was running that was not working.

However, When I include the function in the main body of the code, then it returns the correct value.

i.e.

J=[]
N_xi=[1,0,-1]
N_eta=[0,1,-1]
X=[0.123,1.265,2.221]
Y=[1.235,1.1763,2.224]
#J=Jacobian(N_xi,N_eta,X,Y)
J=[[0,0],[0,0]]
for i in range(len(X)):
    J[0][0]=J[0][0] N_xi[i]*X[i]
    J[0][1]=J[0][1] N_xi[i]*Y[i]
    J[1][0]=J[1][0] N_eta[i]*X[i]
    J[1][1]=J[1][1] N_eta[i]*Y[i]

This gives the value of J as [[-2.098, -0.9890000000000001], [-0.9560000000000002, -1.0477000000000003]]

This means I am doing something inside the function. Could someone please help me with this. I am really struggling with Lists and other Arrays.

If you know a good resource on practicing with Lists and Arrays, then I would also really appreciate that.

Thank you very much for your time in advance.

CodePudding user response:

Misplaced return statement

By looking at the function, the function will return the value after the first iteration, as the return statement is within the block(indent) of the loop.

If you want the loop to be executed fully and then return the value then place the return statement in the same indent as for loop.

CodePudding user response:

On the Jacobian() function, you need to apply the correct indentation for the return statement, so the for would run appropriately:

def Jacobian(N_xi,N_et,X,Y):
  J=[[0,0],[0,0]]
  for i in range(len(X)):
    J[0][0]=J[0][0] N_xi[i]*X[i]
    J[0][1]=J[0][1] N_xi[i]*Y[i]
    J[1][0]=J[1][0] N_eta[i]*X[i]
    J[1][1]=J[1][1] N_eta[i]*Y[i]
  return J

If you add spaces to the return instruction, you are inserting it into the loop execution, so it will only traverse 1 time the range(). That's why it's malfunctioning.

CodePudding user response:

There is a problem with indentation in your code. return J is inside the for loop, therefore the loop will execute only once. The return statement needs to be outside the loop, so de-indent it.

  • Related