miniminimish
miniminimish

Reputation: 97

Printing an upside down right triangle in Python 3.7

I have been trying to print an upside down right triangle in Python 3.7. This is the code I wrote:

n=4
for i in range (0, n):
    for j in range(0,n):
        print("*", end="")
        n-=1
    print()

According to what I understood about loops, the nested for loop should iterate n times while the outer for loop iterates once. Following that logic, the column loop should print four asterisks, then one less each time the loop turns because the value of n reduces by one.

But the output I get is this:

****

I don't understand what I'm doing wrong.

Edit: I know and understand the alternative ways of solving this problem. It's just that I don't get why this particular piece of code is not working.

Upvotes: 2

Views: 1622

Answers (1)

azrael
azrael

Reputation: 45

You will be better off using the * operator to build your string.

n = 4
for i in range(n):
    print('*' * (n-i))

Output:

****
*** 
**
*

Upvotes: 3

Related Questions