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 do I get this star pattern to work with only one for loop in python?

Very new to python and coding in general!
Trying to get a star pattern that looks like this:

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

to work using a for loop, but I’m only allowed to use a single for loop, and embed an if/else statement inside to get it to work. If I could use 2 for loops I’d know how to do it but not sure why my current solution isn’t working, as it only outputs the first 5 lines of stars and then stops. Any help appreciated 🙂

My current codebase:

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

print("Pattern: ")

# Stores the * as a variable, not entirely necessary but negates having to type out "*" 
star = "*"

for i in range(9):
    if i in range(5):
     print(star * (i + 1))
    elif i in range(4, 0, -1):
       print(star * i)

>Solution :

As others have mentioned in the comments, your range() structure is flawed.

You can simplify the approach by using > and < in your if else like this:

print("Pattern: ")

star = "*"

for i in range(9):
    if i < 5:
        print(star * (i + 1))
    else:
        print(star * (9 - i))
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