Python 程序打印单位矩阵


如果需要打印单位矩阵,可以使用嵌套循环。

以下是演示 −

示例

 演示

n = 4
print("The value of n has been initialized to " +str(n))
for i in range(0,n):
   for j in range(0,n):
      if(i==j):
         print("1",sep=" ",end=" ")
      else:
         print("0",sep=" ",end=" ")
   print()

输出

The value of n has been initialized to 4
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 初始化 'n' 的值。
  • 一个 'for' 循环从 0 到 'n'。
  • 另一个嵌套 'for' 循环从 0 到 'n'。
  • 如果第一个和第二个 'for' 循环中的变量相等,则打印 '1'。
  • 否则,如果不相等,则在控制台上打印 '0'。

更新于: 11-Mar-2021

725 浏览

职业生涯

完成课程即可获得认证

开始
广告