If you really cant use the sum()
function, here is a function to sum the rows, I've written it explicitly to show the steps but it would be worth looking at list comprehensions once you understand what is going on:
def row_sums(square):
# list to store sums
output = []
# go through each row in square
for row in square:
# variable to store row total
total = 0
# go through each item in row and add to total
for item in row:
total += item
# append the row's total to the output list
output.append(total)
# return the output list
return output
This can then be used as such:
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
row_totals = row_sums(square)
EDIT:
In answer to your comment, I'd do something like this:
def sum_columns(square):
# as before have a list to store the totals
output = []
# assuming your square will have the same row length for each row
# get the number of columns
num_of_columns = len(square[0])
# iterate over the columns
for i in xrange(0, num_of_columns):
# store the total for the column (same as before)
total = 0
# for each row, get the value for the column and add to the column total
# (value at index i)
for row in square:
total += row[i]
# append the total to the output list
output.append(total)
# return the list of totals
return output