Code is unreachable -error

newb here, i am trying to compare the difference between a matrix and its tranposed matrix with a tollerance. First thing is i need to check that it is a square and then if the differnce is with tollerance.I am getting an error that the last two lines of codes are unreachable. The output should be True True for the above but I only get the first True (ie it is a square matrix.

import numpy as np
a= np.array(([[1, 2, 3,],[2, 3, 4],[3, 4, 1]]))
def check_symmetric(a,tol): b = a.transpose(1, 0) print (a) print(b) rows = a.shape[1] col = a.shape[0] z= abs(a-b) print(z) if rows != col: #check to make sure the list is a square return False return True; result = (abs(a - b) <= tol).all() print(result)
print check_symmetric(a,tol=1e-8)

2 Answers

Move your return statement to the bottom of the function:

return True;
result = (abs(a - b) <= tol).all()
print(result)

would become:

result = (abs(a - b) <= tol).all()
print(result)
return True;

A return statement will stop the execution of a function and return control back to the context it was called from, in this case the line:

print check_symmetric(a,tol=1e-8) 

That means the way your code is right now, the last two lines will never be executed because the context for execution is back outside the function already. That's why you don't see that second print statement.

There's a return True; just before the last two lines. The function will return at that point, and will never execute those lines. That's why they're unreachable.

Most probably you want to move that line to the end?

5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like