Python Inverse Pyramid

Hello. I needed some guidance on an assignment problem I was given. Basically I am supposed to create an upside down pyramid that is centered. Pretty basic. Before this, I had to create a normal up-right pyramid, which I will attach below as well. The only thing I cannot figure out is how to center the pyramid. I have tried a lot of combinations, but can’t seem to figure it out. Pretty sure it is a simple solution haha! *** I cannot use the .reverse or .center functions. If anyone knows a method I could try I would appreciate it. TIA.

Here is the code for the normal pyramid:

def pyramid_helper(height,level):
    if level<=height:
        print (" "*(height-level)+"*"*(2*level-1))
        pyramid_helper(height,level+1)
    

def pyramid (height):
    pyramid_helper(height,1)
    
pyramid(3)
pyramid(7)

Now, here is the code I have tried for the inverse pyramid, basically the same thing:

def pyramid_helper(height,level):
    if level<=height:
        print (" "*(level-height)+"*"*(2*level-1))
        pyramid_helper(height,level-1)
    

def pyramid (height):
    pyramid_helper(height,3)
    
pyramid(3)

Hi emmak,
you should look into python string formatting, there are several options for this in python and lots of tutorials online.
My personal preference are f-strings, for which you can find a nice overview here that also covers centering:
https://medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e

1 Like

Thank you I will look at that!!

Hi emmak!

Have you tried something like that:

print('{:^100s}'.format(""*(height-level)+"*"*(2*level-1)))

Please use "" and not " "!

1 Like

Where would I put the “and not” part? I will try this!

you need to use the quotes like this "" , make sure to use only the quotes and not with a space inside (" ")

1 Like

Gotcha. Thanks everyone!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.