dimanche 24 octobre 2021

Trying to print a "Triangle of triangles" using for loops. Can't seem to print horizontally

The program needed is one that takes an integer as input to make a triangle out of triangles, like so: sample of input and output

I've tried this code:

num = int(input())


for i in range(0, num):
    for j in range(0, num - i - 1):
        print(" ", end = "")
    for k in range(0, 2 * i + 1):
        for l in range(num):
            print(" " * (num - l - 1) + "*" * (2 * l + 1))
            
    print()

It prints out the triangles the right amount, but they're on top of each other: vertical triangles

I tried adding end = "" to the print(" " * (num - l - 1) + "*" * (2 * l + 1)) and it kind of fixes the vertical printing. It's just that the smaller triangles are printed horizontally as well, like so: horizontal lines

Is there any way to print out strings horizontally without using end = "" ? Or am I just taking the wrong approach to the problem? I hope I'm explaining this correctly, I'm just new to coding. Thanks!

Aucun commentaire:

Enregistrer un commentaire