Doubt in script logic

1

Well, I was wondering why number 2 is not the first one to be printed in this script, I'm not understanding logic.

altura = 5
linha = 1

while linha <= altura:
    print ('1', end = '')
    coluna = 2

    while coluna < altura:

        if linha == 1 or linha == altura:
            print ('2')

        else:
            print(end = '')
        coluna = coluna + 1

    print ('3')
    linha = linha + 1
    
asked by anonymous 21.06.2018 / 18:10

2 answers

2

Leandro, to understand this script it is good to understand how the while loop works.

The first while will only run if your condition is met, so:

while linha <= altura: #linha(1) é de fato menor que altura(5) 
print ('1', end = '')
coluna = 2

When there is a loop inside another, the subsequent loop is also executed and only after its end the outer loop returns its normal execution, thus:

    while coluna < altura:

    if linha == 1 or linha == altura:
        print ('2')

    else:
        print(end = '')
    coluna = coluna + 1

Your second while has to be executed until your condition is satisfied and then fall back into the outer loop again.

Anderson's tip is valid, desktop tests can help you debug these simpler code errors, but a good understanding of programming logic is also necessary, keep studying.

    
21.06.2018 / 18:38
1

In your code you have two while . The% from outside% is executed before and the content of it is executed as well. The code does not start with% internal%, I think this has confused you.

So by doing a simulation of the first run and the values:

altura = 5                                   # altura = 5
linha = 1                                    # linha = 1

while linha <= altura:                       # 1 <= 5
    print ('1', end = '')                    # imprime 1, aqui já explica o motivo
    coluna = 2                               # coluna = 2

    while coluna < altura:                   # 2 < 5

        if linha == 1 or linha == altura:    # 1 == 1 or 1 == 5
            print ('2')                      # imprime 2, formando 12, o primeiro valor
    
22.06.2018 / 23:27