Program for an upright and inverted triangle pattern with one For loop and if-else statement

Question:

I am new to Python and wanted to create a program which prints this star pattern using one for loop and an if-else statement:

*
**
***
****
*****
****
***
**
*

What I’ve done so far:

stars = "*"
for i in range (0,10):
    if i <5:
        print(stars)
        stars = stars + "*"
   # else:

Output:

*
**
***
****
*****

Not sure what to put in the else statement?

I’ve tried looking online but all solutions I’ve seen use two for loops, which makes sense. Is it possible to use one loop?

Asked By: Thandi

||

Answers:

What you should do is is to increase the number of stars in each row up to a certain point, and then decrease the number of stars in each subsequent row.

Here’s how you can do it:

stars = "*"
for i in range(1, 9):
    if i <= 4:
        print(stars)
        stars = stars + "*"
    else:
        print(stars)
        stars = stars[:-1]
print("*")
Answered By: XMehdi01

This doesn’t really answer the question because there’s no explicit for loop and there’s no conditional test.

W = 9

stars = ["*"*i for i in range(1, W//2+2)]

print(*(stars[:-1]+stars[-1::-1]), sep="n")

Output:

*
**
***
****
*****
****
***
**
*

Note:

Only works when W > 0 and is an odd integer

Answered By: Codist
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.