Home > Blockchain >  How can I fix value error on for-loop in python array?
How can I fix value error on for-loop in python array?

Time:01-15

For a homework assignment we were asked to generate the specific array below and find the count of the even numbers in the array using a for loop. I'm running into a value error after running my for loop.

Q2 = np.random.randint(0, 1000, size = (10, 10))
print("The list of numbers in Q2 array = ", Q2)

even_count = 0
odd_count = 0            

for i in range(len(Q2)):
    if(Q2[i] % 2 == 0):
        even_count = even_count   1
    else:
        odd_count = odd_count   1

print("The count of the even numbers in Q2 array = ", even_count)

I'm getting the following message when I run the for loop: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I've searched for an answer for this problem and have found all kinds of explanation of the value error and Booleans, but none of them helped specific with my type of code. Or didn't elaborate enough for someone who is very new to Python to understand (me!) Any help would be much appreciated!

CodePudding user response:

Q2 is an array of array so you need another for loop.

import numpy as np


Q2 = np.random.randint(0, 1000, size = (10, 10))
print("The list of numbers in Q2 array = ", Q2)

even_count = 0
odd_count = 0            

for i in Q2:
    for j in i:
      if (j % 2 == 0):
        even_count = even_count   1
      else:
        odd_count = odd_count   1

print("The count of the even numbers in Q2 array = ", even_count)

CodePudding user response:

You are generating a two-dimensional array (10 x 10). So Q2[i] is still a (one-dimensional) array, not a single integer as you seem to expect. Hence the error, because in your subarray you may have both even and odd numbers - in other words the truth value of your check is ambiguous, as the error message says.

Male two loops, or simply create a one-dimension array

  • Related