0
rows = eval(input("enter the number of rows:"))
columns = eval(input("enter the numbers of columns:"))

matrix = []                                         
matrix2 = []
matrix3 = []

for i in range(0, rows):                            
   matrix.append([])
   for j in range (0,columns):
       val = eval(input("Enter a number:"))        
       matrix[i].append(val)                       
print(matrix)
for i in range(0, rows):                            
   matrix2.append([])
   for j in range (0,columns):
       val2 = eval(input("Enter a number:"))        
       matrix2[i].append(val2)
print(matrix2)



for i in range(0, rows):
 if i % 2 == 0:
   matrix3.append([])
   for j in range (0,columns):
       val3 = matrix[i][j] + matrix2[i][j]
       matrix3[i].append(val3)
print(matrix3)

I am stuck regarding finding out how to only add the even numbers into matrix 3. Was trying to use a basic function if % 2 == 0 which would tell me the even numbers but do not know where to go after that.

  • `i` is the row index, not the number. – Barmar Apr 26 '22 at 16:22
  • May I ask why you're using `eval()` as opposed to `int()`? Using [`eval()`](https://stackoverflow.com/q/661084/17769815) in this way is a pretty massive security risk. – BrokenBenchmark Apr 26 '22 at 16:25
  • As @Barmar mentioned, check in your code what "i" represents. In your line "if i % 2 == 0:" i is not your current number from the matrix but the current row. – al1en Apr 28 '22 at 11:20

1 Answers1

0

You're testing the row numbers for evenness, not the numbers in the matrixes.

for row1, row2 in zip(matrix, matrix2):
    new_row = []
    for num1, num2 in zip(row1, row2):
        new_num = 0
        if num1 % 2 == 0:
            new_num += num1
        if num2 % 2 == 0:
            new_num += num2
        new_row.append(new_num)
    matrix2.append(new_row)
Barmar
  • 741,623
  • 53
  • 500
  • 612