Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print right Pascal triangle with one for loop and if-else statement in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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?

>Solution :

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("*")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading