Pyramid of asterisks program in Python

jimmyc3po picture jimmyc3po · Feb 6, 2011 · Viewed 48.9k times · Source

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

Hugh Bothwell picture Hugh Bothwell · Feb 6, 2011
def pyramid(rows=8):
    for i in range(rows):
        print ' '*(rows-i-1) + '*'*(2*i+1)

pyramid(8)
       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************

pyramid(12)
           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
***********************