Draw a Pyramid

Python Exercises

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

Draw this pyramid using for loop or while loop

Hint: Nested loops may be required.

# Start
row = ""
for a in range(9):
  row += "*"
print(row)

1

row =""
# to print 2 sets of 9 stars
forbinrange(2):
  forainrange(9):
    row+= "*"
  # with 1 star in the middle
  if(b==0):
    row+= " * "
print(row)

1

# print 9 rows of stars
forcinrange(9):
  row =""
  forbinrange(2):
    forainrange(9):
      row+= "*"
    if(b==0):
      row+= " * "
  print(row)

1

# use a variable space that decreases
space =8
forcinrange(9):
  row =""
  # add spaces before first star of row
  fordinrange(space):
    row+= " "
  # decrease space variable by 1
  space-=1
  forbinrange(2):
    forainrange(9):
      row+= "*"
    if(b==0):
      row+= " * "
  print(row)

Solution

space =8
# use a variable star that increases
star =1
forcinrange(9):
  row =""
  fordinrange(space):
    row+= " "
  space-=1
  forbinrange(2):
    # user star variable with range
    forainrange(star):
      row+= "*"
    if(b==0):
      row+= " * "
  # increase star variable by 1
  star+=1
  print(row)