Linda Acquaviva Linda Acquaviva - 25 days ago 6
Python Question

Triangular n x n pattern program

This program is supposed to print an n x n triangular pattern like this:

n = 6

* * * * * *
. * * * * *
. . * * * *
. . . * * *
. . . . * *
. . . . . *


However I am getting this:

n = 6

* * * * * *
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .


where is my mistake?

import sys

n = int(sys.argv[1])

def triangle(n):
for i in range(n):
if i == 0:
for k in range(n):
print('*', end=' ')
print()
if i > 0:
for k in range(n):
print('.', end=' ')
print()

triangle(n)

Answer Source

Currently you are printing stars only if you are on the first line and dots for every other line. You need to print dots and stars on each line increasing the number of dots and decreasing the stars:

def triangle(n):
    for i in range(n):
        for k in range(i):
            print('.', end=' ')

        for k in range(n - i):
            print('*', end=' ')

        print()