The program i wrote a program so that main calls the following functions:
getMatrix – creates and returns a 3 x 3 matrix
printMatrix – prints the matrix row by row
sumRow – returns the sum of the elements of a single row of the matrix (pass in the matrix and the row index)
The problem i am facing is that it is asking for the input twice, instead of once.
def getMatrix():
matrix = []
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter number of columns: "))
for row in range(numberOfRows):
matrix.append([])
for column in range(numberOfColumns):
value = eval(input("Enter an element and press enter: "))
matrix[row].append(value)
return matrix
# Print 2 dimensional list
def printMatrix(matrix):
matrix = getMatrix()
for row in range(len(matrix)):
for column in range(len(matrix[row])):
print(matrix[row][column], end = " ")
print()
# Add each element in row to total
def sumRow(matrix):
for row in range(len(matrix[0])):
total = 0
for column in range(len(matrix)):
total += matrix[row][column]
print("Sum for matrix", row, "is", total)
def main():
matrix = getMatrix()
printMatrix(matrix)
total = sumRow(matrix)
main()
In main
:
matrix = getMatrix()
printMatrix(matrix)
In printMatrix
:
matrix = getMatrix()
Which immediately masks the matrix
argument you passed in, by the way.
In getMatrix
:
matrix = []
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter number of columns: "))
You should be using int()
, by the way, not eval()
.
So there are two calls to getMatrix()
, which means two requests for input. Remove matrix = getMatrix()
from printMatrix
. That's not what that function is supposed to be doing, anyway.