Micro,
A possible solution would be for you to print the blanks before your second for
, something like that:
print((num_linhas - linha) * " ", end="")
With this you would generate the spaces to the left before printing, see that here was also used the end
empty to avoid line breaking. With this, your code would look like this:
def matriz2(num_linhas):
for linha in range(1,num_linhas+1):
print((num_linhas - linha) * " ", end="")
for i in range(linha,0,-1):
print(i,end=' ')
print()
See online: https://repl.it/repls/NarrowUnderstatedAccess
You can also create a variable and add the numbers and spaces, printing only once in the for
main, in this example I used f-string
and also of rjust
to generate the spaces:
def matriz2(num_linhas):
for linha in range(1,num_linhas+1):
toPrint = ""
for i in range(linha,0,-1):
toPrint = f"{toPrint}{i} "
print(toPrint.rjust(num_linhas * 2))
See online: https://repl.it/repls/PettyGigaDifferences
Here another way of how this can be done, just as an example, can be sure that there are other ways of doing:
def matriz(num_linhas):
for linha in range(1, num_linhas+1):
print("".join([str(num) + " " for num in range(num_linhas - (num_linhas - linha), 0, -1)]).rjust(num_linhas * 2))
Here I use the join
to turn a list into a string and rjust
to put the blanks, I also use the str
to turn the number into a string.
See this other online example: https://repl.it/repls/OffshoreOutstandingFilesize