M = [[1,2,3], [4,5,6], [7,8,9]]
x=0
for i in range(3):
       x = x + M[i][i]
print x

-------

M = [[1,2,3], [4,5,6], [7,8,9]]
x=0
for i in range(3):
	for j in range(3):
		x = x + M[i][j]
print x

----------

M = [[1,2,3], [4,5,6], [7,8,9]]
x=0
for i in range(3):
	for j in range(i):
		x = x + M[i][j]
print x

Recommended Answers

All 2 Replies

I know the answer for the first code is 15 but the rest start to get confusing... :/
any ideas?

4c4,5
<        x = x + M[i][i]
---
> 	for j in range(3):
> 		x = x + M[i][j]
4c4
< 	for j in range(3):
---
> 	for j in range(i):
6c6
< print x
---
> print x
\ No newline at end of file
4,6c4,5
< 	for j in range(i):
< 		x = x + M[i][j]
< print x
\ No newline at end of file
---
>        x = x + M[i][i]
> print x
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.