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)
row = ""
for a in range(9):
row += "*"
print(row)
Hint #1
row = ""
# to print 2 sets of 9 stars
for b in range(2):
for a in range(9):
row += "*"
# with 1 star in the middle
if(b == 0):
row += " * "
print(row)
# to print 2 sets of 9 stars
for b in range(2):
for a in range(9):
row += "*"
# with 1 star in the middle
if(b == 0):
row += " * "
print(row)
Hint #2
# print 9 rows of stars
for c in range(9):
row = ""
for b in range(2):
for a in range(9):
row += "*"
if(b == 0):
row += " * "
print(row)
for c in range(9):
row = ""
for b in range(2):
for a in range(9):
row += "*"
if(b == 0):
row += " * "
print(row)
Hint #3
# use a variable space that decreases
space = 8
for c in range(9):
row = ""
# add spaces before first star of row
for d in range(space):
row += " "
# decrease space variable by 1
space -= 1
for b in range(2):
for a in range(9):
row += "*"
if(b == 0):
row += " * "
print(row)
space = 8
for c in range(9):
row = ""
# add spaces before first star of row
for d in range(space):
row += " "
# decrease space variable by 1
space -= 1
for b in range(2):
for a in range(9):
row += "*"
if(b == 0):
row += " * "
print(row)
Solution
space = 8
# use a variable star that increases
star = 1
for c in range(9):
row = ""
for d in range(space):
row += " "
space -= 1
for b in range(2):
# user star variable with range
for a in range(star):
row += "*"
if(b == 0):
row += " * "
# increase star variable by 1
star += 1
print(row)
# use a variable star that increases
star = 1
for c in range(9):
row = ""
for d in range(space):
row += " "
space -= 1
for b in range(2):
# user star variable with range
for a in range(star):
row += "*"
if(b == 0):
row += " * "
# increase star variable by 1
star += 1
print(row)