2

I have a if/else statement like this:

import numpy as np
rows_b = int(input("Enter the number of rows of matrix B : " ))
column_b = int(input("Enter the number of columns of matrix B : "))

print("Input elements of matrix B1:")
B1= [[float(input()) for i in range(column_b)] for j in range(rows_b)]
   
print("Input elements of matrix B2:")
B2= [[float(input()) for i in range(column_b)] for j in range(rows_b)]

b1 = np.array(B1)
b2 = np.array(B2)

result = np.all(b1 == b2[0])
if result:
    print('matrix B1 = B2')
    #if matrix B1 = B2, go to the next algorithm

else:
    print('matrix B1 and B2 are not equivalent') 
    #if B1 and B2 are not equivalent, stop here.

B = np.array(B1)
print("Matrix B is: ") 
for x in B:
    print(x)

I want if B1 = B2 then continue to the next step (B = np.array (B1)) but (else) if B1 and B2 are not equal then stop algorithm (not continue to B = np.array (B1)), how ?

Mira Wadu
  • 53
  • 6
  • Either keep rest of the code from `B = np.array(B1)` inside the `if` condition, or use `exit()`in `else` part. – ThePyGuy Aug 04 '21 at 12:29
  • Obligatory warning: you can't [compare floating point](https://stackoverflow.com/q/588004/6486738) values! You need to compare it with an epsilon, or with [`isclose` in numpy](https://stackoverflow.com/q/39757559/6486738). – Ted Klein Bergman Aug 04 '21 at 12:38
  • 2
    @ThePyGuy No, `exit` is not the way to go. To cite the [documentation of `exit` and `quit`](https://docs.python.org/3/library/constants.html#exit): "They are useful for the interactive interpreter shell and should not be used in programs." – Matthias Aug 04 '21 at 12:39
  • @Matthias, That's is also `True`. `exit` is not a recommended way – ThePyGuy Aug 04 '21 at 12:50

1 Answers1

1

Put it inside if

if B1 == B2:
  B = np.array(B1)
  print("Matrix B is: ") 
  for x in B:
    print(x)

else:
    print('matrix B1 and B2 are not equivalent') 
    #if B1 and B2 are not equivalent, stop here.
Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68
  • I'd suggest adding the same warning here. `B1 == B2` will compare all elements, and floating-point values [can't accurately be compared with equality](https://stackoverflow.com/q/588004/6486738). – Ted Klein Bergman Aug 04 '21 at 12:40
  • so what should i do to compare with float value? – Mira Wadu Aug 04 '21 at 13:07
  • how to use np.isclose() in if/else statment? – Mira Wadu Aug 04 '21 at 13:26
  • @MiraWadu If you just want to check if all elements in one array is equal to all the elements in the other array, you could use `if np.allclose(B1, B2)`. Read up on it [here](https://numpy.org/doc/stable/reference/generated/numpy.allclose.html). – Ted Klein Bergman Aug 04 '21 at 13:32