How to make a pyramid using recursion in python?

Question:

I need to make a pyramid in python using recursion.
Already made it, but I need help making it with recursion.

def pyramid(n):
    for i in range(0, n):

        for j in range(0, i+1):
    
            print("* ",end="")
      
        print("r")
 
pyramid(5)
Asked By: Alitaliano

||

Answers:

Recursion = the repeated application of a recursive procedure.

Code:

def pyramid(n):
    if n==0:
        return
    else:
        pyramid(n-1)
        print("* "*n)

n = 10
pyramid(n)

This just repeats the function until n = 0.

Answered By: Matei Piele

Matei’s solution is reasonable, but since the original used a nested for loop instead of repeat, it’s worth mentioning that both loops can be replaced by recursive calls:

def nstars(n):
    if n<=0:
        print('')
        return
    print('*',end='')
    nstars(n-1)

def pyramid(n):
    if n<=0:
        return
    pyramid(n-1)
    nstars(n)
Answered By: Mark Reed
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.