Python Exercise Example 38

Python 100例Python 100 Examples

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

Program analysis:Use a double for loop 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 result 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例Python 100 Examples

Other Extensions