Printing pattern using while loop

Can you see how the above example works? As an exercise, try printing the following pattern using a while loop (Hint: use string concatenation):

``````          *
**
***
****
*****
******
*****
****
***
**
*
``````

i could solve this using 2 nested while loops , but how to solve using string and concatenate ?

2 Likes

I tried doing it by changing the jovian module example a bit,
this solution has 2 while loops.

``````def rev_star(n):
line = '*'

while len(line) <= n-1:
space = n-len(line)   # Counter for number of spaces
print(' '*space, line)   # Statement to print required number of spaces and line(*)
line += "*"

while len(line) > 0:      # Similar loop but for 2nd half of the pattern
space = n-len(line)
print(' '*space, line)
line = line[:-1]
``````

I tried to do it with 1 while loop,

``````def rev_star2(n):
line = '*'
i = len(line)

while i <= 2*n-1:
space = n-i

if(i>n):  # Condition for decreasing 2nd half
print(' '*-space, line*(2*n-i))   # -space to print spaces for the decreasing 2nd half
else:
print(' '*space, line*i)          # space to print spaces for increasing 1st half
i += 1
``````

But I donβt think Iβm using string concatenation in the 2nd example(rev_star2).

Output for both:
`rev_star(6)` and `rev_star2(6)`

``````      *
**
***
****
*****
******
*****
****
***
**
*
``````

Edit:
I tried the 2nd example without using `i=len(line)` and that does have string concatenation,

``````def rev_star3(n):
line = '*'

while len(line) <= 2*n-1:
space = n-len(line)

if(len(line)>n):  # Condition for decreasing 2nd half
print(' '*-space, line[:2*n-len(line)])   # -space to print spaces for the decreasing 2nd half

else:
print(' '*space, line)          # space to print spaces for increasing 1st half

line += '*'       # String concatenation
``````
2 Likes

line = β*β
max_length = 8

while len(line) <= max_length:
print(" " * (max_length - len(line)) + β" * len(line))
line += "
β

while len(line) > 0:
print(" " * (max_length -(len(line) - 2)) + β*β * (len(line) - 2))
line = line[:-1]