首页 > 解决方案 > Python中的For / While循环三角形不起作用

问题描述

处理我的第二个三角形,但它没有给我使用 while 嵌套循环所需的结果,我应该有以下输出。

使用 for 循环:

0
01
012
0123
01234
012345

使用 while 循环:

     5
    45
   345
  2345
 12345
012345

代码:

print('Using for loop')
print()
M = 6 #constant
cnt = 1

for i in range(0,M):
    for j in range(0,cnt):
        if(j<M):
            print(j,'',end='')
        else:
            print('',end='')
    cnt+=1
    print()
print()
print('Using While loop')
print()
cnt = 6

while(cnt != -1):
    for j in range(0,cnt-1):
        if(j<cnt+1):
            print(j,'',end='')
        else:
            print(j)
    cnt -=1
    print()
print()

我目前的结果是..

使用 for 循环

0
01
012
0123
01234
012345

使用 while 循环

012345
01234
0123
012
01
0

标签: pythonfor-loopwhile-loopnested-loops

解决方案


你有很多语法错误使用这个

print('Using for loop')
print()
M = 6 #constant
cnt = 1

for i in range(0,M):
    for j in range(0,cnt):
        if(j<M):
            print(j,'',end='')
    cnt+=1
    print()
print('\nUsing While loop\n')
cnt = 0

while(cnt != M):
    for j in range(0,M-(cnt+1)):
        print(' ','',end='')
    for j in range(0,cnt+1):
        print(M-(cnt+1-j),'',end='')
    cnt +=1
    print()
print()

推荐阅读