Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create the LEFT half of a triangle with * using only WHILE PYTHON

I have this code:

    numero = int(input("Escriba el número de filas de la pirámide: "))
if numero > 0:
    patron = "+"
    contador = 1
    while contador <= numero:
        print( patron * contador )
        contador = contador + 1
else:
    print("El número de filas de la pirámide debe ser mayor que 0")

output

I need this triangle to reverse like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

triangule reverse

I have solved it with FOR but in this case I want to do it with the conditional WHILE, which would be needed in the code?

>Solution :

You need to pad, for this you can add as many spaces as needed:

numero = int(input("Escriba el número de filas de la pirámide: "))
if numero > 0:
    patron = "+"
    contador = 1
    while contador <= numero:
        print(' '*(numero-contador) + patron * contador)  # changed here
        contador = contador + 1
else:
    print("El número de filas de la pirámide debe ser mayor que 0")

If you can use string methods (rjust), it’s even better:

print((patron * contador).rjust(numero))

output:

Escriba el número de filas de la pirámide: 6
     +
    ++
   +++
  ++++
 +++++
++++++
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading