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:
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))