An alternative is to make a loop from 1 to n, increasing the number (adding the new digit at the end) and printing using the formatting options:
def triangulo(n):
x = 0
for i in range(1, n + 1):
x = i + (x * 10)
print(f'{x:.>{n}}')
triangulo(5)
At each iteration I multiply the number by 10 and add the new digit (thus, 1 becomes 12, which then becomes 123, etc).
To print I use .>{n}
, that says to print the number on the right (>
), occupying n
positions and filling the missing spaces with the point.
Of course you can also make concatenating strings:
def triangulo(n):
x = '1'
pontos = '.' * (n - 1)
for i in range(1, n + 1):
print(f'{pontos}{x}')
x += str(i + 1) # adiciona um dígito
pontos = pontos[:-1] # remove um ponto
triangulo(5)
But I find it unnecessary to keep creating so many strings (each iteration creates a new string for the "number" and another for the points), when some simple accounts and the use of formatting options already solve.
Very good! Thank you!!
– bagre