How to create expression that returns 1,12,123,1234 in Python

Asked

Viewed 381 times

2

I’m learning the basics of python and I came across an exercise where I have to build the following sequence:

1   
12  
123  
1234  
12345  
123456  
1234567  
12345678  
123456789 

I think it’s something very simple to do even, but someone can help me?

3 answers

4


The code is very simple:

st = ''
for i in range(1, 10):
    st += str(i)
    print st

Online test: link.

  • 1

    I believe that you should not give the answer to the OP but encourage him to think how to solve.

  • Hello! That finally solved it. I was trying to create it using the while function and I wasn’t getting to the values. After all the trick was in doing through string and not in numerical. Thank you

1

If you want to generalize this question to the point of power especificar the number of lines in this triangle, you can use the following algorithm...

# Capturando e tratando a quantidade de linhas:
while True:
    try:
        n = int(input('Digite o número de linhas do triângulo: '))
        if n <= 0:
            print('\033[31mValor INVÁLIDO! Digite apenas números inteiros maiores que "0"!\033[39m')
            n = int(input('Digite o número de linhas do triângulo: '))
        else:
            break
    except:
        print('\033[31mValor INVÁLIDO! Digite apenas números inteiros!\033[39m')

print(f'\033[32mO triângulo criado com colunas iguais é: ')
# Controla o número de linhas
for c in range(1, n + 1):
    # Controla a organização e inserção dos elementos na linha.
    for i in range(1, c + 1):
        print(i, end='')
        print('  ' if i < 10 else '  ', end='')
    print()

See here the functioning of the algorithm.

Note that in this algorithm you can especificar the number of lines that will be displayed.

Another thing, the primeiro for controls the number of lines in the triangle. The segundo for, controls the insertion and organisation of.

Also note that this algorithm can work with an undefined number of lines.

0

You can use a loop that has the minimum value and rotates while it is smaller and/or equal to the maximum value and print the value before increment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.