Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Exercise Example 38

Python Exercise Example 38

Python 100 Examples Python 100 Examples

**Question:** Find the sum of the main diagonal elements of a 3*3 matrix.

**Program Analysis:** Use nested for loops to control the input of a two-dimensional array, then accumulate a[i][i] and output it.

Program source code:

Example

#!/usr/bin/python

-- coding: UTF-8 --

if

name

==

'

main

'

:

a

=

[

]

sum

=

0.0

for

i

in

range

(

3

)

:

a

.

append

(

[

]

)

for

j

in

range

(

3

)

:

a

[

i

]

.

append

(

float

(

input

(

"

input num:

\n

"

)

)

)

for

i

in

range

(

3

)

:

sum

+=

a

[

i

]

[

i

]

print

(

sum

)

The output of the above example is:


input num:
78
input num:
34
input num:
23
input num:
34
input num:
56
input num:
33
input num:
12
input num:
21
input num:
2
136.0

Python 100 Examples Python 100 Examples