JE3 JE3 - 6 days ago 6
Python Question

How to make Right asterisk triangle using while loop

This is the code I have, but I keep getting left triangles:

def RTriangle(n):
row = 1
while row <= n:
col = 1
while col <= row:
print("*", end="")
col = col + 1
print()
row = row - 1


def test_rt():
for i in range(5, 12, 3):
RTriangle(i)
print()

test_rt()

Answer

In Python you can actually multiply a string (this will copy the string x times), which means you don't have to print it out one by one. For example, "cat" * 3 gives "catcatcat"

Here is the solution:

def RTriangle(n):
    col = 0 
    while col <= n:
        print(" " * (n - col),"*" * col)
        col = col + 1

def test_rt():
    for i in range(5, 12, 3):
        RTriangle(i)
        print()

test_rt()

Here are some other useful operations you can do on strings:

String methods

Comments