-2

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)
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378

3 Answers3

1

Instead of checking the loop index simply use it to print the number of dots. Then print n - i stars, e.g.:

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

Or just using the multiplication operator:

def triangle(n):
    for i in range(n):
        print(*["."]*i + ["*"]*(n-i), sep=" ")
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

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()
DobromirM
  • 2,017
  • 2
  • 20
  • 29
  • This is exactly the same code that my (earlier) answer has. – Eugene Yarmash Sep 24 '17 at 07:33
  • It had a different counters in the `for` loop initially that you consequently edited and I also wanted to try and give a better explanation because you didn't have that either. – DobromirM Sep 24 '17 at 07:45
0

Try this Its alot more simple

count = 0
count2 = 5
while count2 >= 1:
    for i in range(count):
        print(".", end = " ")
    for i in range(count2):
        print("*", end = " ")
    print()
    count = count + 1
    count2 = count2 - 1
Kieron
  • 21
  • 7