0

Here is my code but I'm having trouble getting the pyramid to be spaced correctly like a pyramid and also to only have odd number of asterisks per line. Output when you enter 7 for the base should be

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

This is my code:

base = int(input( 'enter an odd number for the base : ' ) )
for i in range( 0, base ):
    print '*' * i
Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
user3317056
  • 37
  • 2
  • 7
  • 1
    Wow, this is a blast from the past: http://stackoverflow.com/questions/4911341/pyramid-of-asterisks-program-in-python/4911427#4911427 – Hugh Bothwell Mar 04 '14 at 18:00

2 Answers2

2

You could use str.center():

for i in range(1, base + 1, 2):
    print ('*' * i).center(base)

but do use a step size of 2, and adjust your range. The first line starts with 1 star always, and range() doesn't include the last value.

For 7, that means you want to print 1, 3, 5 and 7 stars, incrementing by 2 each iteration.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • If i now wanted to do the same thing with odd numbers and 2 for each iteration but make a diamond shape, how do i do that? i'm assuming you would have to have the triangle mirror itself but i don't know how to do that – user3317056 Mar 04 '14 at 18:33
  • Use *two* loops; the second would use negative step to range down. The first loop can go from `range(1, base, 2)` and the second would go `range(base, 0, -2)`. – Martijn Pieters Mar 04 '14 at 18:35
  • actually i just tried that before i saw your comment but am having trouble getting rid of the base showing up twice – user3317056 Mar 04 '14 at 18:41
  • @user3317056: that's why you run the *first* range with `range(1, base, 2)`, *not* `base + 1`, so that it is not included. – Martijn Pieters Mar 04 '14 at 18:42
1

There are some errors in your code:

  1. since you're using print '...' instead of function print, you may be in python2, where raw_input is needed instead of input;
  2. range(1, base+1, 2) is needed instead, for your sample output.

Demo:

In [6]: base = int(raw_input( 'enter an odd number for the base : ' ) )
   ...: for i in range(1, base+1, 2):
   ...:     print ('*' * i).center(base)

enter an odd number for the base : 7
   *   
  ***  
 ***** 
*******
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108