SMc
SMc

Reputation: 45

For/While loops triangle in Python not working

Working on my 2nd triangle but it is not giving me the result needed using the while nested loop and I should have the following output.

Using for loop:

0
01
012
0123
01234
012345

Using while loops:

     5
    45
   345
  2345
 12345
012345

Code:

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()

my current results are..

Using for loop

0
01
012
0123
01234
012345

Using while loop

012345
01234
0123
012
01
0

Upvotes: 0

Views: 1091

Answers (3)

gdef_
gdef_

Reputation: 1936

Here is a while-loop solution without any for-loop:

print('Using While loop')
print()
cnt = 6
v = cnt
while(cnt != -1):
    j = cnt
    print(' ' * cnt, end='')
    while(j < v):
        print(j, end='')
        j += 1

    cnt -=1
    print()

Upvotes: 0

you have lot of syntax error use this

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()

Upvotes: 1

Austin
Austin

Reputation: 26039

Your logic is wrong. Also you have many syntax errors. Use this:

print('Using While loop')
print()
cnt = 6
v = cnt
while(cnt != -1):
    print(' ' * cnt, end='')
    for j in range(cnt, v):
        if j < cnt+1:
            print(j, end='')
        else:
            print(j, end='')
    cnt -=1
    print()

Output:

Using While loop

     5
    45
   345
  2345
 12345
012345

Upvotes: 0

Related Questions