Question :
Pyramid of asterisks program in Python
I’ve written a program in C++ that displays a pyramid of asterisk (see below) and now I’d like to see how it’s done in Python but it’s not as easy as I’d thought it would be.
Has anyone tried this and if so could you show me code that would help out?
Thanks in advance.
*
***
*****
*******
*********
***********
*************
***************
Answer #1:
def pyramid(rows=8):
for i in range(rows):
print ' '*(rows-i-1) + '*'*(2*i+1)
pyramid(8)
*
***
*****
*******
*********
***********
*************
***************
pyramid(12)
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
Answer #2:
Or you could try:
def pyramid(size=8):
for i in range(size):
row = '*'*(2*i+1)
print row.center(2*size)
Answer #3:
You can use string multiplication like so:
>>> for i in range(size):
... print '%s%s'%(' '*(size-(i-1)),'*'*((i*2)-1))
...
Answer #4:
This code isn’t very pythonic, but it’s readable. Look at Hugh Bothewell’s answer for a compact pyramid drawing function:
def drawPyramid(rows):
result = ''
for i in xrange(rows):
row = ''
row += ' ' * (rows - i - 1)
row += '*' * (2 * i + 1)
result += row + 'n'
return result
print drawPyramid(20)
Answer #5:
I would suggest the following function:
def pyramid(rows=8):
pyramid_width = rows * 2
for asterisks in range(1, pyramid_width, 2):
print("{0:^{1}}".format("*" * asterisks, pyramid_width))
Then try with:
pyramid()
or with:
pyramid(4)
Answer #6:
If you like list comprehensions:
> n = 5
> print("n".join((i*"*").center(n*2) for i in range(1, n*2, 2)))
*
***
*****
*******
*********
Answer #7:
Pyramid, Inverted Pyramid and Diamond Rhombus in Python:
Pyramid
i=1
j=5
while i<=5:
print((j*' ')+i*'* ')
j=j-1
i=i+1
*
* *
* * *
* * * *
* * * * *
Inverted Pyramid
i=1
j=5
while i<=5:
print((i*' ')+j*'* ')
j=j-1
i=i+1
* * * * *
* * * *
* * *
* *
*
Diamond Rhombus
i=1
j=5
while i<=5:
print((j*' ')+i*'* ')
while j<=5 & i==5:
print(((j+1)*' ')+(5-j)*'* ')
j=j+1
j=j-1
i=i+1
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Answer #8:
user_input = input("How many rows do you want to print? n")
def stars(a):
size = int(a)
for i in range(1, size+1):
print(" "*(size-i),"*"*(i*2-1))
stars(user_input)
How many rows do you want to print?
20
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
*************************
***************************
*****************************
*******************************
*********************************
***********************************
*************************************
***************************************