2 years ago

#72662

test-img

the_fledgling_programmer

How do I iterate over a 2D array and check each value within the array?

I am trying to iterate over a 2D array to check whether my numbers are between 1 and 9. The console's output does not reflect what I have input.

My code (input):

import numpy as np

array_test = np.array([[1,2,3], [4,5,6], [7,8,9]])
print("this is the test: ", "\n", array_test)

for row in array_test:
    for col in row:
        if col > 0 and col <= 9:
            print(True)
        else:
            print(False)

Output:

this is the test:  
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
True
True
True
True
True
True
True
True
True

I recognize the print() statement is iterating over 9 times as well which is also what I am trying to fix. Essentially, is there a way to check for each number in each row and column, if that number is > 0 and <= 9, and if all 9 blocks in the array meet those conditions, then it prints "True" once? Am I nesting the for-loops correctly? Is the 9 printed "True" values representing each different number?

arrays

python-3.x

conditional-statements

iteration

0 Answers

Your Answer

Accepted video resources