Frosty Elsa Frosty Elsa - 2 months ago 13
Python Question

Asterisk Triangle manipulation using For loops only

base=int(input("Enter the triangle size: "))
for r in range(base):
for c in range (r+1):
print('*',end='')
print()

=============== RESTART: C:\Users\ELSA\Desktop\star.py ===============
Enter the triangle size: 4
*
**
***
****
>>>


I am also trying to create an output that looks like the following:

****
***
**
*


and...

*
**
***
****


and...

****
***
**
*


Any help would be greatly appreciated -- note: I need to use for loops for this program identical to the one in my first example.

Answer

You can code the 4 cases as follows (Note that you need to use ' ' instead of '')

base=int(input("Enter the triangle size: "))
# Four loops for four different patterns
for i in range(1, base + 1):
    print (('*' * i) + (' ' * (base - i)))

for i in range(1, base + 1)[::-1]:
    print (('*' * i) + (' ' * (base - i)))

for i in range(1, base + 1):
    print ((' ' * (base - i)) + ('*' * i))

for i in range(1, base + 1)[::-1]:
    print ((' ' * (base - i)) + ('*' * i))