Metrokett
Metrokett

Reputation: 29

How to print a pyramid in Python?

How to make a pyramid?

I need to make a function, that prints a full pyramid.

For example

(13 is the base width of the pyramid and 1 is the width of the top row.)

pyramid(13, 1)

Result:

       .

     .....

   .........

 ............. 

The step should be 4, so each row differs from the last row by 4 dots.

Edit:

This is what I have so far, but I only got the half of the pyramid and the base isn't what it's supposed to be.

def pyramid(a, b):
    x = range(b, a+1, 4)
    for i in x:
        print(" "*(a-i) + "."*(i))

pyramid(17,1)

Upvotes: 0

Views: 1635

Answers (3)

Henrique Branco
Henrique Branco

Reputation: 1930

Here is my contribution, using - character instead of blank space, for a better visualization:

def pyramide(base, top, step=4):
    dot = "."
    for i in range(top, base+1, step):
        print((dot*i).center(base, "-"))

pyramide(13,1)

Output

------.------
----.....----
--.........--
.............

Upvotes: 2

Ali Hassan
Ali Hassan

Reputation: 966

# Function to demonstrate printing pattern triangle 
def triangle(n): 

    # number of spaces 
    k = 2*n - 2

    # outer loop to handle number of rows 
    for i in range(0, n): 

        # inner loop to handle number spaces 
        # values changing acc. to requirement 
        for j in range(0, k): 
            print(end=" ") 

        # decrementing k after each loop 
        k = k - 1

        # inner loop to handle number of columns 
        # values changing acc. to outer loop 
        for j in range(0, i+1): 

            # printing stars 
            print("* ", end="") 

        # ending line after each row 
        print("\r") 

# Driver Code 
n = 5
triangle(n) 

Upvotes: 1

Sarangan
Sarangan

Reputation: 967

Try this :

def pyramid(a, b):
    for i in range(b,a+1,4) :
        print(str( " " *int((a-i)/2) )+ "."*(i)+ str( " " *int((a-i)/2) ))

Output:

pyramid(17,1)

        .        
      .....      
    .........    
  .............  
.................

Upvotes: 3

Related Questions